Compare commits

..
32 Commits
Author SHA1 Message Date
836061373 8cdd315093 docs: 补记推送后 Gitea Actions 仍为 0 次运行(B4 实证),master 与 tag 现状
- 23d8846 已推送,master 推进到该提交;tag v0.1.0 仍指向 5d05d63(B2)。
- 推送后 Actions 页面仍显示 0 workflow runs(CI/CD 两个工作流可见但未触发),
  B4「CI 未运行」在迁移后的平台依旧成立。
2026-12-05 23:54:52 +08:00
836061373 23d8846898 chore: 仓库链接迁移到 gitea.guichumo.com 并修复 gradlew 执行位
- plugin.yaml 的 homepage / repo / issues / author.website 从裸 IP + HTTP
  (http://101.43.163.221:3000/…)改为 https://gitea.guichumo.com/836061373/halo-ops-audit
  (实测 HTTPS 200、HTTP 301 跳转、/issues 200),修复发布阻断项 B7。
- 两处 gradlew 在 Git 索引中加执行位(100644 → 100755),修复阻断项 B3:
  Linux runner 上 ./gradlew 才能执行。
- 文档同步:验收确认报告把 B7 / B3 标为已修复(剩余 B1、B2、B4、B5、B6),
  证据块记录新旧两个制品的 SHA-256 与差异;测试报告新增「链接域名迁移」小节,
  根 README 的阻断计数改为 2 个代码问题 + 3 项发布流程/上架资料。

重新 clean build -Pversion=0.1.0 生成新制品
b26623e9fbbe39e8f57072f554d9c018c1fa603bdcc5d8810f220d09e3b2eaa0(121,673 字节)。
与通过完整矩阵的上一制品(8391674a…)逐条目对比:56/57 个条目逐字节相同,
仅 plugin.yaml 变化。

验证:全新 Halo 2.26.1 实例安装检查 11/11(Plugin CR 四处链接均为新域名),
核心套件 93/93、0 失败;./gradlew -p plugin-operation-audit test 通过(286/286);
node --test demo/test/audit-core.test.mjs 61/61。
2026-12-05 23:53:34 +08:00
836061373 2da6f518b3 docs: 第六轮发布制品复核——结论改为「暂不可发布」并记录阻断项
对当前 HEAD(00c8d3f)的正式版制品 plugin-operation-audit-0.1.0.jar
(SHA-256 8391674a…)重做整份发布验收清单与上架前自查:

- 测试报告新增第六轮记录:Halo 2.26.0/2.26.1/2.27.4 五个一次性实例上的
  安装、启停、重启、升级、卸载与 Console 浏览器冒烟结果,及未覆盖项;
  附 10 张 r6 截图证据。
- 验收清单确认报告新增第六节:逐节结论、7 项阻断(B1~B7)、证据块、
  修复顺序;第一~五节与旧「发布就绪」结论就地标注已被取代。
- 待办完成记录加「已被取代」提示,避免据旧结论发布。
- README 与插件 README 更正「敏感字段自动脱敏」的表述:脱敏只按字段名
  匹配 password/passwd/secret/token/credential,apiKey 等命名会明文落库
  (实测证据见测试报告),并新增发布状态说明。

阻断项:B1 脱敏覆盖面不足(P0)、B2 远端 tag v0.1.0 指向修复前提交(P0)、
B3 gradlew 无执行位(P0)、B4 CI 从未运行(P0)、B5 入库 API 客户端非生成器
产物(P1)、B6 LICENSE 与 README 隐私/升级/卸载说明缺失(P1)、B7 链接为
裸 IP + HTTP(P1)。

验证:./gradlew -p plugin-operation-audit test 通过(286/286,缓存命中,
源码未改动);node --test demo/test/audit-core.test.mjs 61/61。
2026-12-05 23:08:47 +08:00
836061373 00c8d3f1df docs: 测试报告补充「登录页访问误记为登录成功」修复的真实环境验证记录(fc79842)
第五轮复测记录:生产现场反馈、修复前复现、修复内容,以及交付 JAR
(SHA-256 73b4fb37…)在真实 Halo 2.26.1 升级场景下的脚本复核与 Console 页面检查。

- 第二轮「GET /login 记为登录属设计内覆盖,非噪声缺陷」的原判断处加注推翻
- 归档截图 t6 / t7 / t8;补充一次性实例与脚本的残留说明
- 更正 README 中过期的测试用例数(后端 286、demo 61)
2026-12-05 15:16:17 +08:00
836061373 fc7984291f fix: 登录页访问不再记成「登录成功」——认证端点只记录 POST,登录成败以响应确认为准
现场反馈:审计列表「没有失败,全是成功,登录失败也显示成功」。在 Halo 2.26.1 上
复现(afda8d0 构建):GET /login、GET /login?authentication_required 只是打开登录页
(HTTP 200),却被记成「未知用户 · 登录 200」,列表里看起来全是登录成功;POST /login
本身的成败判定是对的,但被这些记录淹没。

- 捕获:AuthEndpointAuditWebFilter 只记录 POST /login(登录尝试)与 POST /logout
  (登出);登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出
  确认页)原样透传不记录(CaptureRule.isAuthOperation)
- 判定:LoginOutcome 只有响应明确确认才算成功——302 跳回登录页(含 error 参数或
  路径即 /login)、缺失 Location、4xx/5xx 一律判失败;移除失败回显页判定
- 结果语义:新增 AuditResult(成功 / 失败 / 页面访问),结果筛选、CSV 导出与前端
  resultBadge 共用同一规则;登录成功显示「成功」,与「失败」对称
- 历史数据:升级前落库的登录页访问记录(GET,标注 login/logout)展示与导出为
  「访问登录页/登出页」且不计成败,结果筛选与「登录/登出」语义动作筛选均排除;
  落库标注不改写
- demo 同步同一套规则;README 与设计/技术文档同步

测试:后端 286、UI 74、demo 61 全过;真实 Halo 2.26.1 升级场景联调记录见测试报告
2026-12-05 13:24:26 +08:00
836061373 afda8d04fd feat(demo): 按插件当前实现重写演示页
- 列表/筛选对齐真实 Console:八维筛选、语义动作中文描述、登录失败结果语义
- 详情抽屉展示字段级 diff(脱敏/截断/封顶)与 AuditLog Extension 原始 JSON
- 新增行内「历史」快捷、按筛选条件导出 UTF-8 BOM CSV
- 设置页覆盖审计开关/字段变更/系统变更/保留期与登录失败告警(含测试与模拟触发)
- 模拟器支持 HTTP 捕获管线与系统内部变更两条通道
- 核心纯函数重写并扩充至 56 个单元用例
2026-11-23 00:05:12 +08:00
836061373 602744debd chore: 新增 .gitattributes 统一换行策略与二进制文件处理
- 文本统一 LF(脚本/sh 强制 LF,批处理 CRLF),仓库现状已全部为 LF,无大规模重写
- png/jar/zip/pdf 等标记 binary,避免文本转换与 diff 噪音
- package-lock.json 标记为生成物
2026-11-22 23:54:53 +08:00
836061373 9329f313f4 chore: 整理仓库结构与文档——测试截图归档至 docs/assets,修正报告并补全文档索引
- gui-test-screenshots/ 迁至 docs/assets/gui-test-screenshots/,测试证据归入 docs
- 修正测试报告中的截图路径与“未纳入版本控制”矛盾表述,测试凭据脱敏
- README 仓库结构补全 .github/.agents/转发脚本/锁文件,文档表补全全部文档
2026-11-22 23:54:53 +08:00
836061373 fd43c069ae docs: 新增发布验收待办完成记录(6 项待办执行总结归档至 docs)
- docs/operation-audit-release-todos-completion.md:待办完成总览表、
  正式构建/CI-CD/卸载/2.26.0 下探/元数据与 ui/ 迁移的关键执行细节、
  提交记录、剩余发布动作与环境备注
- 验收清单确认报告参考链接补充该完成记录
2026-11-22 23:44:31 +08:00
836061373 5d05d63b8e docs: 发布验收全部待办完成——2.26.0 下探通过,验收报告更新为发布就绪
- 测试报告第四轮补充 2.26.0 最低版本下探实测(官方发布 JAR,sha256 与官方 .sha256
  一致;一次性全新实例):setup/login/install/enable/审计捕获(含 2.26.0 特有的
  401 登录失败响应仍正确标注 login-failure)/query/export/匿名拒绝/ui/ ESM bundle
  全部通过,实例日志 0 ERROR
- 验收清单确认报告更新:头部速览改为发布就绪;章节一补正式版三处一致复核;
  章节二 UI 迁移与 manifest 元数据标记完成;章节三补卸载与 2.26.0 下探结论;
  章节四 CI/CD 配置详情;章节五发布证据块(0.1.0 制品 SHA-256、tag v0.1.0 说明)
- 6 项待办(2×P0/2×P1/2×P2)全部闭环
2026-11-22 23:41:41 +08:00
836061373 753de51f7b docs: 测试报告补卸载(uninstall)生命周期实测记录(P1 待办完成)
- 0.1.0-SNAPSHOT→0.1.0 upgrade API 实测(历史数据保留)
- 卸载全流程对齐 Console 卸载并删除配置分支(停用→删 CR→删 Setting/ConfigMap)
- 卸载后核对:CR/JAR/Setting/ConfigMap/RoleTemplate 清理;RoleBindings 孤儿残留
  (Halo 平台行为,记录);AuditLog 数据保留、重装后 169→172 条回归
- 重装闭环:install→enable→STARTED;pf4j disabled.txt 残留被 Halo 自动清除
- 卸载测试对应验收清单第 6 步(生命周期核对),原未覆盖项消除
2026-11-22 23:27:16 +08:00
836061373 44eca75e6e ci: 发布验收 P0 项——补齐 CI/CD 工作流
- .github/workflows/ci.yml: push/PR 触发,复用 halo-sigs/reusable-workflows
  plugin-ci.yaml@v5 执行 ./gradlew clean build(全部测试+检查)
- .github/workflows/cd.yml: GitHub Release published 触发,复用 plugin-cd.yaml@v5,
  按发布 tag 去 v 前缀注入 -Pversion 构建(-x check,不替代发布前 CI),
  skip-appstore-release: true——首次上架审核前只上传 Release 资产,不自动同步应用市场
- 根目录 gradlew/gradlew.bat: 转发到 plugin-operation-audit/ 的 Gradle wrapper
  (官方可复用工作流从仓库根执行 ./gradlew,build-args 以 -p 指定子项目目录)
- artifacts-path 限定 plugin-operation-audit/build/libs(仅插件 JAR,不误传其他制品)
2026-11-22 23:26:07 +08:00
836061373 81693e4778 chore: 发布验收 P2 项——UI 产物迁至 ui/ 规范目录,补齐 manifest 元数据
- build.gradle: processUiResources 输出目录 console/ -> ui/(目标 Halo >=2.25.0 官方规范位置),
  doFirst 同时清理旧构建残留的 console/ 目录;vite.config.ts 注释同步
- plugin.yaml: 新增 spec.logo(logo.svg)/homepage/repo/issues/author.website 与 license.url,
  logo.svg 以相对路径随包内置(官方插件同款方式)
- 已验证: ./gradlew check 全绿(后端 270 + UI 69),clean build -Pversion=0.1.0
  三处版本一致(JAR 文件名/plugin.yaml spec.version/Manifest Implementation-Version 均 0.1.0),
  ui-plugin.json 声明的入口与样式均存在于 JAR 内
2026-11-22 22:53:36 +08:00
836061373 b6a21dfaa7 docs: 新增发布验收清单确认报告(CI 缺失与 SNAPSHOT 版本为 P0 待办) 2026-11-22 22:26:09 +08:00
836061373 1987412e07 docs: 按 plugin-testing.md 分层流程第三轮复测插件(fd3ea71,自动化+联调+权限矩阵+生命周期全过) 2026-11-22 21:27:45 +08:00
836061373 fd3ea71e31 docs: 按 plugin-testing.md 分层流程复测插件(99bd109,自动化+联调冒烟全过)
- 后端 270/270、UI vitest 69/69、类型检查、check 与 clean build 全部通过
- 复用 8099 冒烟实例完成真实 Halo 联调:登录/登出审计、权限拒绝、无效输入、
  导出、告警 SSRF 守卫失败路径均符合设计
- haloServer 因本机无 Docker 失败(pipe 不存在),如实记入 Known limitations
2026-11-22 19:17:32 +08:00
836061373 99bd109e80 docs: 测试报告补充 P0 修复状态(f4d1200,含联调复测结论) 2026-11-22 18:51:37 +08:00
836061373 f4d1200d46 fix: P0 修复——认证端点改由 BeforeSecurityWebFilter 在 Security 链最前捕获
根因(测试报告 P0 实证):OperationAuditWebFilter 经 AfterSecurityWebFilter 注册于
Security 过滤链尾、认证环节之后,表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中
POST /login、POST /logout 后直接完成 302 响应、不再向下游传递——链尾审计过滤器
永远看不到认证端点请求,登录/登出记录与登录失败告警生产路径均为死代码。

- 新增 AuthEndpointAuditWebFilter:BeforeSecurityWebFilter 扩展点(链首)承接
  /login、/logout 捕获,操作者记未知用户(链首无认证上下文),登录尝试账号、
  登录结果判定、失败告警回调随迁
- CaptureRule 分治:shouldCapture 仅覆盖 /apis/** 写操作,isAuthEndpoint 归链首
  过滤器,互不重叠不重复记录;OperationAuditWebFilter 移除认证端点死分支
- 修复 LoginAttemptCapture 表单提取通道:改经 getFormData() 共享缓存读取——原实现
  缓存原始请求体并装饰 exchange 后,下游 CSRF 过滤器经原始 exchange 解析已被消费
  的 body、读不到 _csrf 表单参数,真实 Halo 登录页表单提交整体 403(联调实证);
  JSON 形态仍走缓存+装饰(下游无表单语义),并增加用户名长度上限
- 新增真实 Spring Security 过滤链集成测试(按 Halo SecurityWebFiltersConfigurer
  组装:FIRST/FORM_LOGIN/AUTHENTICATION/LOGOUT/LAST):断言 POST /login 成败、
  POST /logout 必产生记录且链尾不重复记录;含启用 CSRF + 表单参数令牌的
  回归测试锁死 getFormData 通道;doFinally 晚于完成信号回调,断言统一
  以 Mockito timeout 等待
- 同步产品设计/技术方案/合规文档与 README(含 Windows JAR 锁定升级注意事项)

验证:后端 270/270(3 连跑无 flaky)、UI 69/69、check 与 clean build 通过;
真实 Halo 2.26.1 联调:浏览器表单登录(错误密码 302→error、正确密码 302→/uc)、
登出 302→/login?logout 均产生审计记录,Console 列表登录失败红色标注正常。
2026-11-22 18:51:14 +08:00
836061373 cc2c618fe7 docs: 新增操作审计插件测试报告(P0 缺陷:POST /login、/logout 永不达审计过滤器)
按 docs/plugin-testing.md 分层验证流程执行:
- 自动化检查全过(后端 265/265,UI 69/69,check 与 clean build 通过)
- Halo 2.26.1 独立 JAR 真实安装联调:安装/启停/升级/重启/权限矩阵
- 浏览器级 UI 验证(桌面 + 390px 窄屏),截图证据入库 gui-test-screenshots/
- 发现并定位 P0 缺陷:表单登录/登出不再向下游传递,审计过滤器从未被调用,
  审计记录与登录失败告警在生产路径均为死代码;附复现命令与修复方向
2026-11-22 17:27:25 +08:00
836061373 34764c7641 fix: 操作审计移动端改为题头+横向滚动,修复 :deep 作用域失配
上一轮「隐藏题头 + 数据行纵向堆叠」在真机上整批失效:VEntity 是
多根 Fragment 组件(tr + 可选 footer tr),其 <tr> 拿不到本组件的
scoped 作用域 ID,所有锚定 .audit-row 的 :deep 规则永远无法匹配
(Vue 仅在元素为组件 subTree 根时附加父作用域 ID),窄屏下字段仍按
固定列宽横排并被视口截断,且横向滑动也被控制台裁剪。

改为窄屏保持「题头 + 固定列宽」的表格形态:
- 题头与数据行置于同一横向滚动容器 .audit-list(overflow-x: auto,
  同官方 EntityList 的 w-full overflow-x-auto 模式),整体左右
  滑动看全六列,列对齐关系与桌面一致;容器够宽时无滚动条
- .audit-header 增加 min-width: max-content(下划线随内容延伸,
  滑动后不断裂)、.header-col 增加 flex-shrink: 0(列不被压缩)
- 行悬停手型改为锚定自身元素 .audit-list 经 :deep 穿透到
  entity-wrapper,并移除永远失配的 .audit-row 选择器
- 筛选栏窄屏 2 列(≤480px 单列)、分页条换行等此前已生效的
  适配保持不变

重写 AuditLogList.mobile.spec.ts:新增滚动容器/题头可见/列不收缩/
无失效堆叠规则等断言,防止失效方案回归;并在浏览器中于 390×844、
1280×800 与 1024px+侧栏三种宽度下验证横向滑动与列对齐。
2026-11-22 16:27:43 +08:00
836061373 87ae0c79bb fix: 操作审计页移动端适配(窄屏筛选 2 列/隐藏题头/数据行堆叠)
桌面布局的 9 列筛选行在窄屏下每列仅剩数十像素(标签逐字换行、
输入框压扁),固定列宽列表合计约 61rem 必然横向溢出被截断。

≤1023px(手机横竖屏/平板竖屏/半屏小窗口)改为:
- 筛选栏 2 列、操作按钮独占整行;≤480px 手机竖屏单列
- 隐藏固定列宽列题头,entity 行纵向堆叠(覆盖组件内联 width)
- 截断类字段放宽到 100%,分页条允许换行
≥1024px 维持桌面布局不变。

新增 AuditLogList.mobile.spec.ts 结构性回归测试(8 项)。
2026-11-22 15:59:52 +08:00
836061373 9e89ed75ed fix: 登录失败按 Halo 登录端点契约判定,不再被 200/302 掩盖
Halo 2.26 登录端点表单提交的成功与失败均为 302 重定向(成功 → /uc,
失败 → /login?error=...&method=...),失败回显页 GET /login?error=...
渲染 HTTP 200;旧逻辑按「2xx 即成功」判定导致:

- 审计列表中失败登录显示绿色 200/302,误读为登录成功
- 登录失败告警把表单成功登录也计为失败,成功清零失效、可误报警

修复:
- 新增 LoginOutcome 纯函数:2xx 成功;3xx 以重定向目标查询串是否含
  error 参数判定(含无值形式);其余(401、状态码缺失)失败
- 失败的登录尝试与失败回显(GET /login?error=...)落库标注语义动作
  login-failure(spec.action),HTTP 状态码仍如实记录
- Console 列表/详情与 CSV:登录失败记录显示红色「失败」而非裸状态码,
  语义动作筛选与「结果=失败」筛选均命中登录失败记录
- LoginFailureAlertService 改由过滤器传入 LoginOutcome 判定结果,
  成功清零、失败累计恢复正常
- 历史局限:升级前落库的表单登录失败(302)无法由路径重新推导,
  仍按登录展示;升级后新记录捕获时标注,不再有此局限

测试:后端 265 例、前端 60 例全部通过;文档与 README 同步更新。
2026-11-22 15:47:47 +08:00
836061373 9865149ab3 fix: 落实官方规范评审修复(生成 API 客户端 / SSRF 防护 / 凭据迁 Secret)
对应 docs/operation-audit-halo-compliance.md 评审的两项不符合与第 5 节修复建议:

1. API 客户端生成(清单第 2 条):build.gradle 配置 haloPlugin.openApi 管线;
   查询/导出/测试端点补 tag、参数声明与类型化 response(生成契约输入);
   bootstrap OpenAPI 规范 JSON(与 Springdoc 声明一一对手工对齐)驱动 devtools
   generateApiClient 产出 TS 客户端(ui/src/api/generated,openapi-generator 7.7.0);
   UI 经 ui/src/api 封装层复用宿主 axiosInstance,替换手写类型与裸 fetch;
   @halo-dev/api-client 由死依赖转为 axiosInstance 实际来源。

2. 出站安全与凭据(清单第 4 条):新增 OutboundUrlGuard——URI 解析 + scheme 白名单 +
   禁止用户名/密码形态 + 全量 DNS 解析并拒绝环回/私网/链路本地/组播/未指定/
   云元数据(169.254.169.254、100.100.100.200、fd00:ec2::254)/CGNAT/ULA/Teredo/
   6to4/文档与保留段;PinnedAddressResolverGroup 钉定校验地址建连(DNS rebinding
   防护,TLS SNI/Host 仍取原主机名);重定向显式关闭、三层超时 10 秒。
   Webhook 地址凭据迁移 Halo Secret(settings.yaml 改 secret 输入存引用,服务端经
   ReactiveExtensionClient 解析键 webhookUrl,fail closed);日志只记主机名,
   不再记录可能内嵌 access_token 的完整地址。

测试:后端 244 用例(新增守卫地址段枚举/Secret 解析 fail closed/建连钉定证明等
25 例)+ UI vitest 54 用例 + vue-tsc + ./gradlew build 全部通过。
2026-11-22 15:15:32 +08:00
836061373 7257008af3 docs: 新增插件测试指南(Halo 官方 testing 文档存档) 2026-11-22 14:10:32 +08:00
836061373 f59cab95a0 docs: 新增插件发布验收清单 2026-11-22 14:10:31 +08:00
836061373 197c5a3830 docs: 新增 AI 辅助开发文档(Halo 文档上下文/生成前检查清单/Agent Skill) 2026-11-22 14:09:45 +08:00
836061373 a38cb4a3b5 chore: 安装 halo-plugin-dev 技能到当前项目(skills CLI 项目级) 2026-11-22 14:06:53 +08:00
836061373 19dc0da1eb docs: 新增官方开发规范符合性评审(2 项不符合:generateApiClient / Secret+SSRF) 2026-11-22 14:00:03 +08:00
836061373 cb3ff6ef17 feat: 列表行内「查看该资源历史」快捷动作(P1-1,纯前端)
- AuditLogList 资源列行内新增「历史」小链接(仅有资源名称的记录展示),
  点击预填资源类型 + 资源名关键字(关键字匹配资源名称/路径)并刷新列表,
  停止冒泡避免触发行点击的详情抽屉
- 不新增后端参数,与现有筛选/导出条件共用同一套状态(buildQuery 不变)
- 新增 vitest 结构性回归测试(预填与请求参数生成/行内渲染/冒泡阻止)
2026-11-22 00:12:57 +08:00
836061373 3269bafbc4 feat: Webhook「发送测试告警」(P0-2,设置页入口+结果化推送)
- AlertWebhookSender 新增 sendForResult:结果化推送(送达与否 + 原因摘要),
  超时/网络错误/非 2xx/URL 非法一律归一为失败结果,永不抛出;
  send(fire-and-forget)复用同一实现,真实告警路径语义不变
- 新增 AlertTestEndpoint:POST /apis/.../alerts/-/test 以 type=test 测试消息
  推送到已保存的 Webhook 地址并同步等待结果返回;Webhook 未配置/非法返回 400;
  RBAC 资源组合 alerts + alerts/test(create 动词)不在只读角色模板授权内
- 设置页「告警通知」区新增「发送测试告警」自定义 FormKit 输入
  (Halo 2.25+ formkit.inputs,@formkit/vue 为宿主共享外部模块),
  推送结果以设置页提示 + 运行日志反馈,ignore:true 不新增设置项
- 更新 README(功能/设置表/告警负载/技术说明)
2026-11-22 00:11:24 +08:00
836061373 08e7bd8a12 feat: 登录失败记录尝试的用户名(P0-1,告警/落库/CSV)
- 新增 LoginAttemptCapture:为登录端点单独缓存请求体(表单/JSON 双形态,
  Content-Length 预检 + 64KB 上限,下游可重复读),字段白名单制仅提取
  username,兜底经现有敏感字段脱敏规则(ChangeDiffEngine)复核,
  密码绝不提取落库;任何失败静默降级,不影响登录主流程
- AuditLogSpec 新增 spec.attemptedUsername(不建索引),AuditRecorder 透传落库
- 告警负载 data 新增 attemptedUsername,content 增加尝试的账号段
- CSV 导出新增"尝试用户"列(操作者之后)
- 详情抽屉展示"尝试用户"(仅登录请求落库时显示)
- 更新 README(功能/告警负载示例/已知局限移除对应条目/技术说明)
2026-11-22 00:06:13 +08:00
836061373 cb86a3d305 docs: 新增功能增减评审与实施顺序建议(roadmap) 2026-11-21 23:43:15 +08:00
127 changed files with 12085 additions and 1481 deletions
+72
View File
@@ -0,0 +1,72 @@
---
name: halo-plugin-dev
description: >
Create or modify Halo CMS plugins, including Java backend code, plugin.yaml and
extension resources, Gradle and DevTools configuration, plugin APIs and lifecycle,
and Vue-based Console or User Center UI. Use for Halo plugin implementation,
migration, debugging, or integration work; do not use for theme-only changes.
---
# Halo Plugin Development
Work from the target plugin and fetch current Halo documentation only when the
task needs a Halo-specific contract. Do not rely on API details embedded in the
skill or recalled from training data.
## Establish the Target
- Inspect the existing Gradle files, `src/main/resources/plugin.yaml`, UI package
manifest and build configuration, and nearby implementations before editing.
- Determine both the Halo platform dependency and `plugin.yaml` `spec.requires`.
Do not silently raise the requirement or switch the UI build format.
- Preserve an existing plugin's structure and tooling. For a new plugin, prefer
the official `pnpm create halo-plugin` scaffold unless the user chose another
starting point.
## Fetch Documentation on Demand
1. Start with the [plugin documentation index](https://docs.halo.run/developer-guide/plugin/index.md)
when the task involves Halo plugin APIs, configuration, lifecycle, UI, DevTools,
security, or integration contracts.
2. Use the complete [Halo documentation index](https://docs.halo.run/llms.txt)
only when the route is unclear or the task crosses documentation sections.
3. Fetch only the Markdown pages relevant to the current task. Do not load
`llms-full.txt` by default.
4. For version-sensitive work, also read the [plugin API changelog](https://docs.halo.run/developer-guide/plugin/api-changelog.md),
then verify exact signatures and behavior against the target dependency,
source, or existing callers. The target version wins over current-site docs.
If online docs are unavailable, continue from the target checkout and dependency
sources when possible, and disclose what could not be verified instead of guessing.
## Halo-Specific Boundaries
- Keep blocking work off reactive WebFlux paths; follow the current
[reactive development guide](https://docs.halo.run/developer-guide/plugin/basics/server/reactive-development.md).
- Reuse Halo-provided UI components, FormKit inputs, shared utilities, and the
project's installed build tooling before adding dependencies or custom equivalents.
- Use Setting YAML for ordinary plugin settings instead of creating a duplicate
settings route. Use FormKit for page and modal forms, and reuse Halo list,
search, modal, feedback, and permission components before native replacements;
follow the current [forms and page components guide](https://docs.halo.run/developer-guide/plugin/basics/ui/forms.md).
- Use the project's `generateApiClient` task to generate TypeScript models and API
methods from custom models and documented `SpringdocRouteBuilder` endpoints.
Reuse Halo's `axiosInstance`; do not handwrite generated resource types or create
a separate Axios client for `/api` or `/apis`. Follow the current
[API request guide](https://docs.halo.run/developer-guide/plugin/api-reference/ui/api-request.md).
- Treat generated API clients and built UI assets as generated files: change their
inputs and use the project's generator or build task rather than editing output.
- Store passwords, tokens, API keys, and private keys in Halo `Secret`, never in a
ConfigMap or custom-model spec. Validate user-controlled outbound destinations
against SSRF and redirect risks before attaching credentials, and keep public
APIs or security switches closed when configuration loading fails. Follow the
current [outbound HTTP guide](https://docs.halo.run/developer-guide/plugin/security/outbound-http.md).
- Add RoleTemplates only when non-super-admin or anonymous access is required;
grant the narrowest permissions needed.
## Verify
Use the project's existing Gradle and UI scripts. Run the narrowest relevant tests
and checks, and verify packaging when manifest, UI output, or generated resources
affect the plugin JAR. When a runnable Halo instance is available, smoke-test the
changed Console, User Center, API, lifecycle, or theme integration path.
@@ -0,0 +1,4 @@
interface:
display_name: "Halo Plugin Development"
short_description: "Build Halo CMS plugins with Java backend and Vue frontend"
default_prompt: "Help me create a Halo plugin"
@@ -0,0 +1,45 @@
{
"skill_name": "halo-plugin-dev",
"evals": [
{
"id": 1,
"prompt": "Implement a Project custom model, a synchronization endpoint described with SpringdocRouteBuilder, and a Console project list in a Halo 2.26 plugin. Complete the Java API and Vue request code. Do not assume the project has already generated a TypeScript client.",
"expected_output": "Java models and OpenAPI descriptions remain the source of truth, Gradle generates the TypeScript API client, and the UI reuses Halo's axiosInstance.",
"files": [],
"expectations": [
"generateApiClient is configured and run for the custom model and SpringdocRouteBuilder endpoint",
"The UI uses generated models, parameters, and API methods without handwritten duplicate resource types or API paths",
"Generated API classes reuse axiosInstance from @halo-dev/api-client",
"No separate Axios instance is created for /api or /apis",
"Generated directories, build artifacts, and lockfiles are not hand-edited"
]
},
{
"id": 2,
"prompt": "Add ordinary runtime settings and create/edit dialogs for Project resources to a Halo plugin. Implement the Console UI so its visuals, validation, loading states, and error feedback match Halo's built-in pages.",
"expected_output": "Ordinary configuration uses Setting YAML, business forms use the host FormKit installation, and page interactions reuse Halo components.",
"files": [],
"expectations": [
"Ordinary plugin settings are rendered from Setting YAML without a duplicate settings route",
"Create and edit forms use Halo's registered FormKit installation instead of a custom form system",
"Pages, dialogs, lists, search, and feedback reuse @halo-dev/components where available",
"Untrusted input is validated on both frontend and backend, and UI permissions match backend permissions",
"No host component source is copied and no new UI framework is added merely to imitate Halo styling"
]
},
{
"id": 3,
"prompt": "Implement a Halo plugin that periodically synchronizes projects from GitHub or a self-hosted GitLab instance. Administrators can configure the base URL and access token and may enable an anonymous public API. Implement secure storage, outbound requests, and configuration failure handling.",
"expected_output": "Credentials are stored in Secret resources, reactive requests validate SSRF and redirects before attaching credentials, and public access fails closed.",
"files": [],
"expectations": [
"The token is stored in a Halo Secret while ConfigMap and custom models store only the Secret name",
"WebFlux paths use WebClient and reactive Halo APIs without block calls or blocking clients",
"Custom destinations restrict schemes, hosts, resolved DNS addresses, and redirects before credentials are attached",
"Connection, response, and overall request timeouts and response size limits are configured",
"The anonymous API is enabled only after configuration loads successfully and explicitly enables it",
"Logs, errors, and public responses do not expose tokens or Secret contents"
]
}
]
}
+21
View File
@@ -0,0 +1,21 @@
# 统一换行:仓库内文本一律 LF,避免跨平台提交产生无意义 diff
* text=auto eol=lf
# 脚本与 Windows 批处理
*.sh text eol=lf
gradlew text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
# 二进制文件不做文本转换与 diff
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.jar binary
*.zip binary
*.pdf binary
# 锁文件按生成物处理,减少 diff 噪音
package-lock.json linguist-generated=true
+27
View File
@@ -0,0 +1,27 @@
name: CD
# Halo 官方可复用插件 CD 工作流:基于 GitHub Release tag 注入版本号构建 JAR 并
# 上传到 Release 资产。可复用工作流内部执行:
# ./gradlew clean build -x check -Pversion=${tag 去 v 前缀} <build-args>
# 因此 Release tag(如 v0.1.0)自动保证 JAR 文件名 / plugin.yaml spec.version /
# Manifest Implementation-Version 三处一致。
# 注意:CD 构建带 -x check,不能替代发布前必须通过且不可跳过的 CI 与测试。
# 首次上架应用市场审核通过前,skip-appstore-release: true —— 只上传
# GitHub Release 资产,不自动同步应用市场;审核通过后按官方发布文档
# 配置 app-id 与最小权限的个人令牌(HALO_PAT)后再开启同步。
on:
release:
types:
- published
jobs:
cd:
uses: halo-sigs/reusable-workflows/.github/workflows/plugin-cd.yaml@v5
permissions:
contents: write
with:
ui-path: "plugin-operation-audit/ui"
artifacts-path: "plugin-operation-audit/build/libs"
build-args: "-p plugin-operation-audit"
skip-node-setup: true
skip-appstore-release: true
+25
View File
@@ -0,0 +1,25 @@
name: CI
# Halo 官方可复用插件 CI 工作流:./gradlew clean build(含全部后端测试与 UI 检查)。
# 本仓库 Gradle 构建根在 plugin-operation-audit/ 子目录:
# - 根目录 gradlew/gradlew.bat 是转发脚本;
# - build-args 传 -p 指定项目目录。
# UI 子项目使用 npm(package-lock.json),没有 pnpm-lock.yaml,
# 因此 skip-node-setup: true,由 ubuntu-latest 预装的 Node/npm 配合
# node-gradle 插件(download = false)完成前端构建与 vitest 测试。
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
ci:
uses: halo-sigs/reusable-workflows/.github/workflows/plugin-ci.yaml@v5
with:
ui-path: "plugin-operation-audit/ui"
artifacts-path: "plugin-operation-audit/build/libs"
build-args: "-p plugin-operation-audit"
skip-node-setup: true
+33 -9
View File
@@ -9,10 +9,11 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
| 能力 | 说明 | | 能力 | 说明 |
|---|---| |---|---|
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) | | 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获认证操作 `POST /login`、`POST /logout`(含登录失败);登录/登出页面的 GET 访问不是操作,不记录 |
| 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 | | 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 |
| 语义动作标注 | 捕获时标注语义动作键(登录/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 | | 语义动作标注 | 捕获时标注语义动作键(登录/登录失败/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 | | 登录成败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成败均为 302 重定向,以重定向目标是否跳回登录页区分,只有响应明确确认才算成功):失败尝试在列表/详情/CSV 中显示红色「失败」,成功显示「成功」;升级前落库的登录页访问记录(`GET /login`,曾被显示成绿色「登录 200」)纠正为灰色「—」的「访问登录页」,不计成败 |
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;字段名命中敏感规则的字段以 `******` 落库(当前覆盖 password / passwd / secret / token / credential,`apiKey` 等命名尚未覆盖,见插件 README「已知局限」),JSON Patch 与 Merge Patch 均支持 |
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) | | Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) |
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) | | 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) |
| 登录失败告警 | 统计窗口内登录失败达到阈值时向 Webhook 地址异步推送通用 JSON 告警(默认 5 分钟 / 5 次,告警后窗口重开,登录成功清零;独立于审计开关,默认关闭) | | 登录失败告警 | 统计窗口内登录失败达到阈值时向 Webhook 地址异步推送通用 JSON 告警(默认 5 分钟 / 5 次,告警后窗口重开,登录成功清零;独立于审计开关,默认关闭) |
@@ -27,7 +28,12 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
│ ├── src/ # 捕获过滤器、审计模型、查询端点、保留期清理 │ ├── src/ # 捕获过滤器、审计模型、查询端点、保留期清理
│ └── ui/ # Console 前端(Vue 3 + vitest) │ └── ui/ # Console 前端(Vue 3 + vitest)
├── demo/ # Console UI 静态演示页(纯前端、模拟数据、零构建依赖) ├── demo/ # Console UI 静态演示页(纯前端、模拟数据、零构建依赖)
├── docs/ # 设计文档:产品设计 · 技术方案 ├── docs/ # 设计 / 验收 / 测试文档
│ └── assets/gui-test-screenshots/ # 浏览器级 UI 验收截图证据
├── .github/workflows/ # CI/CD(复用 halo-sigs 官方可复用工作流)
├── .agents/skills/ # 项目级 AI 技能(halo-plugin-dev)
├── gradlew / gradlew.bat # 仓库根转发脚本:CI 在根目录执行,转发到 plugin-operation-audit/
├── skills-lock.json # 技能安装锁文件
└── AGENTS.md # AI 协作约定(每次改动需 commit、测试全绿后交付) └── AGENTS.md # AI 协作约定(每次改动需 commit、测试全绿后交付)
``` ```
@@ -57,21 +63,39 @@ cd demo
python -m http.server 8721 # 访问 http://127.0.0.1:8721/ python -m http.server 8721 # 访问 http://127.0.0.1:8721/
``` ```
也可直接双击打开 `demo/index.html`(`file://` 下可运行)。演示页内置若干故事线, 也可直接双击打开 `demo/index.html`(`file://` 下可运行)。演示页已按当前插件实现重写,
可体验"排查这篇文章谁改过""登录爆破回溯""误操作定位"等典型场景, 包含八维筛选、语义动作与中文描述、字段级变更 diff、登录失败标注与告警、CSV 导出、
并通过"模拟一次操作"按钮验证捕获规则的边界。 系统内部变更,以及复现捕获管线的「模拟一次操作」。内置故事线可直接体验
"排查这篇文章谁改过""登录爆破回溯""定时发布归属""误操作定位"等场景。
### 运行演示测试 ### 运行演示测试
```bash ```bash
node --test demo/test/audit-core.test.mjs node --test demo/test/audit-core.test.mjs # 61 个用例
``` ```
## 发布状态
**暂不可发布**(2026-12-05 第六轮复核,commit `00c8d3f`):制品在 Halo 2.26.0 / 2.26.1 /
2.27.4 上的安装、启停、升级、卸载与 Console 页面全部通过,但仍有 2 个代码问题(敏感字段
脱敏覆盖面不足、入库的 API 客户端不是生成器产物)和 3 项发布流程 / 上架资料阻断。
阻断项清单与修复顺序见
[docs/operation-audit-release-checklist-review.md](docs/operation-audit-release-checklist-review.md#六第六轮复核2026-12-05commit-00c8d3f--结论暂不可发布)。
## 相关文档 ## 相关文档
| 文档 | 内容 | | 文档 | 内容 |
|---|---| |---|---|
| [plugin-operation-audit/README.md](plugin-operation-audit/README.md) | 插件详情:功能、安装、设置、模型 group 与已知局限 | | [plugin-operation-audit/README.md](plugin-operation-audit/README.md) | 插件详情:功能、安装、设置、模型 group 与已知局限 |
| [demo/README.md](demo/README.md) | 演示页说明:演示了什么、与真实实现的差异 | | [demo/README.md](demo/README.md) | 演示页说明:演示了什么、故事线复现方式、与真实实现的差异 |
| [docs/operation-audit-design.md](docs/operation-audit-design.md) | 产品设计:MVP 范围、设计原则 | | [docs/operation-audit-design.md](docs/operation-audit-design.md) | 产品设计:MVP 范围、设计原则 |
| [docs/operation-audit-tech-design.md](docs/operation-audit-tech-design.md) | 技术方案:架构、数据模型、风险预案 | | [docs/operation-audit-tech-design.md](docs/operation-audit-tech-design.md) | 技术方案:架构、数据模型、风险预案 |
| [docs/operation-audit-roadmap.md](docs/operation-audit-roadmap.md) | 功能增量评估(MVP 之后的候选能力) |
| [docs/operation-audit-halo-compliance.md](docs/operation-audit-halo-compliance.md) | Halo 官方开发规范符合性评审 |
| [docs/plugin-release-checklist.md](docs/plugin-release-checklist.md) | 插件发布验收清单(官方流程存档) |
| [docs/operation-audit-release-checklist-review.md](docs/operation-audit-release-checklist-review.md) | 发布验收逐项确认报告 |
| [docs/operation-audit-release-todos-completion.md](docs/operation-audit-release-todos-completion.md) | 发布验收待办完成记录 |
| [docs/plugin-testing.md](docs/plugin-testing.md) | Halo 官方测试流程文档存档 |
| [docs/operation-audit-test-report.md](docs/operation-audit-test-report.md) | 分层测试报告(源码级 + 联调 + UI 验收) |
| [docs/ai-assisted.md](docs/ai-assisted.md) | AI 辅助开发说明与文档上下文 |
| [docs/assets/gui-test-screenshots/](docs/assets/gui-test-screenshots/) | 浏览器级 UI 验收截图证据 |
+84 -34
View File
@@ -1,8 +1,12 @@
# 操作审计插件 · Console UI Demo # 操作审计插件 · Console UI Demo
> 对应文档:[operation-audit-design.md](../docs/operation-audit-design.md)(产品设计)· [operation-audit-tech-design.md](../docs/operation-audit-tech-design.md)(技术方案) > 已按**当前已实现的插件**(Halo 2.26.1)重写:不再是最初的界面原型,而是把插件的
> 查询/筛选、字段级 diff、登录结果判定、CSV 导出、登录失败告警与系统内部变更等能力
> 用纯前端方式完整复现,便于在没有 Halo 实例时体验与验收。
> >
> **纯前端静态 Demo,无任何后端与构建依赖**,用于在开发真实插件前验证界面布局与操作流程是否合理。 > 对应实现:[plugin-operation-audit](../plugin-operation-audit/) · 设计文档:
> [operation-audit-design.md](../docs/operation-audit-design.md) ·
> [operation-audit-tech-design.md](../docs/operation-audit-tech-design.md)
## 快速开始 ## 快速开始
@@ -18,46 +22,81 @@ python -m http.server 8721
## 演示了什么 ## 演示了什么
模拟 Halo Console 外壳(左侧菜单新增"操作审计"插件入口),包含两个页面: ### 审计日志(与真实 Console 页面一致)
### 审计日志(产品设计 4.2) - **列表列**:操作者 / 时间、动作(HTTP 方法徽标)、资源 / 路径、描述、结果、IP。
描述列展示语义动作的中文短语(登录、登录失败、发布文章、启用插件、修改密码……),
不是裸的 HTTP 方法。
- **八维筛选**:操作者(精确匹配)、资源类型、动作、语义动作、结果、关键字
(资源名称 / 路径模糊匹配)、开始时间、结束时间。下拉即时生效,文本与时间用「查询」
或回车;筛选条件摘要与「清除筛选」始终可见。
- **认证操作与结果**:只记录真正的认证操作——`POST /login`(登录尝试)与 `POST /logout`
(登出);登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出确认页)
不是操作,不记录。表单登录成败在 HTTP 层都是 302,按重定向目标是否跳回登录页判定:
失败显示红色「失败」,成功显示绿色「成功」。升级前落库的登录页访问记录(GET,
HTTP 200,曾显示成绿色「登录 200」)纠正为灰色「—」的「访问登录页」,不计成败。
- **行内「历史」快捷**:有资源名称的记录可一键预填「资源类型 + 资源名关键字」,
直接回答"这篇文章被谁改过"。
- **只读详情抽屉**:操作者、尝试用户、描述、动作、资源、结果、路径、时间、IP、
User-Agent、记录标识,以及**字段变更**(新增 / 修改 / 删除,旧值删除线 → 新值)
与原始 `AuditLog` Extension JSON;不提供任何删除/修改入口。
- **CSV 导出**:按当前筛选条件导出全部记录,UTF-8 BOM + CRLF,列与界面一致
(含「尝试用户」「操作描述」「变更」),带引号转义与公式注入防护,Excel/WPS 直开不乱码。
- **分页**:10 / 20 / 50 条每页。
- 列表:时间、操作者、动作(HTTP 方法徽标)、资源(类型 + 名称)、结果(状态码)、来源 IP ### 插件设置
- 筛选:操作者 / 资源类型 / 动作 / 结果 / 时间范围 / 关键字(资源名称与路径模糊匹配)
- 分页:10 / 20 / 50 条每页
- 详情:点击任意行打开右侧抽屉,展示全部字段(含完整路径、User-Agent、原始 JSON),**只读,无任何修改/删除入口**(设计原则 3)
- 数据内置若干"故事线",可直接体验典型场景:
- **排查"这篇文章谁改过"**:关键字输入 `hello-halo`
- **安全回溯**:资源类型选 `auth` + 结果选"失败"(可见 20 天前同一攻击 IP `203.0.113.66` 的 6 次登录爆破)
- **误操作定位**:关键字输入 `weekly-2026-w45`(1 天前被删除的文章)
### 插件设置(产品设计 4.3 / 技术方案 D5、D6) - **审计设置**:启用审计、记录字段变更、记录系统内部变更、保留天数(最小 7 天);
关闭审计后日志页出现横幅,新操作不再记录。
- **告警通知**:启用登录失败告警、Webhook Secret 引用、触发阈值、统计窗口、
「发送测试告警」与「模拟 5 次登录失败」。达阈值后页面顶部出现红色告警横幅,
并可一键筛选"只看失败记录";告警 JSON 负载在设置页展示。
演示页不发起真实网络请求(真实插件由后端推送并带 SSRF 防护)。
- **清理预览**:按保留期实时统计待清理条数,可模拟一次定时清理。
- 审计开关:关闭后日志页出现横幅,新操作不再记录 ### 模拟一次操作(复现捕获管线)
- 保留天数:修改后"清理预览"实时计算待清理条数,可点击"模拟一次清理"体验定时清理效果
### 模拟一次操作(技术方案 D1 / 5.1 / 5.2) 右上角「模拟一次操作」有两个通道:
右上角"模拟一次操作"按钮可模拟任意后台请求,Demo 按真实捕获管线逐步判定: 1. **页面 / API 操作**:填写操作者、方法、路径、响应状态、重定向目标
(登录用)、尝试的用户名与请求体 JSON,演示页按真实管线判定:
- `shouldCapture`:`/apis/**` 写操作、`POST /login`、`POST /logout`;匿名 / 读操作 /
登录页 GET 访问不记录;
- `resolveResource`:从路径解析资源类型与名称;
- `classifyLogin`:302 重定向跳回登录页(含 `error` 参数)→ 登录失败(标注
`login-failure`);只有响应明确确认才算成功;
- 字段级 diff:PUT / PATCH(Merge Patch 或 JSON Patch)/ POST / DELETE,
自动脱敏密码/令牌类字段,超长截断、超 30 条封顶。
预设按钮覆盖:编辑文章(含 diff)、发布文章、升级插件、修改密码(脱敏)、
登录失败(表单 302)、登录成功、打开登录页(不记录)、读操作不记录。
2. **系统内部变更**:模拟定时发布等非页面操作,执行者记为「系统」、无 IP/UA、
状态恒 200,仅更新/删除两类事件,附字段变更。
1. `shouldCapture`:是否命中捕获规则(`/apis/**` 写操作 + `/login`、`/logout`;匿名请求不记录) ## 故事线(可直接复现)
2. `resolveResource`:从路径解析资源类型与名称
3. 命中则生成审计记录置顶高亮;未命中则用 toast 解释原因(读操作 / 匿名 / 路径不匹配)
预设按钮包含"登录失败""查询文章列表(读)"等例子,可直观验证规则边界(登录失败记"未知用户")。 | 场景 | 操作 |
|---|---|
| 排查 hello-halo 被谁改过 | 关键字输入 `hello-halo`,或点击任意该资源记录的「历史」;打开详情看字段 diff |
| 登录爆破回溯 | 语义动作选「登录失败」:20 天前同一 IP `203.0.113.66` 的 6 次撞库;不带筛选时同 IP 还能看到升级前落库的「访问登录页」记录(灰色「—」,不计成败) |
| 定时发布(系统内部变更) | 操作者输入 `system`,或资源类型选 `posts` + 关键字 `weekly-2026-w46` |
| 插件生命周期 | 关键字 `plugin-link` / `plugin-search-widget`;语义动作可筛「升级」「启用」「卸载」 |
| 误操作定位 | 关键字 `weekly-2026-w45`:1 天前的删除记录,详情含被删字段快照 |
| 越权与异常 | 结果选「失败」:403 越权、404 资源不存在、500 发布异常 |
| 登录失败告警 | 插件设置 → 填写 Webhook Secret 引用 → 启用并保存 → 「模拟 5 次登录失败」 |
## 目录结构 ## 目录结构
``` ```
demo/ demo/
├── index.html # 页面骨架(Console 外壳 + 列表/设置/抽屉/弹窗) ├── index.html # Console 外壳 + 列表/设置/详情抽屉/模拟器
├── assets/ ├── assets/
│ ├── audit-core.js # 核心纯函数:捕获规则、资源解析、筛选、分页、保留期(UMD,浏览器/Node 共用) │ ├── audit-core.js # 纯函数核心(UMD,浏览器/Node 共用):捕获、解析、语义动作、
│ ├── mock-data.js # 模拟数据生成器(种子随机、确定性输出,约 142 条 + 故事线) │ │ # 登录判定、字段 diff、八维筛选、CSV、告警窗口
│ ├── app.js # 交互层(渲染、事件、模拟管线) │ ├── mock-data.js # 种子随机模拟数据(约 141 条 + 7 条故事线,确定性输出)
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components:#4ccba0 / #0e1731 / #d71d1d) │ ├── app.js # 交互层(渲染、筛选、历史、导出、设置、告警、模拟管线)
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components)
└── test/ └── test/
└── audit-core.test.mjs # 单元测试(node:test,29 个用例) └── audit-core.test.mjs # 单元测试(node:test,61 个用例)
``` ```
## 运行测试 ## 运行测试
@@ -66,18 +105,29 @@ demo/
node --test demo/test/audit-core.test.mjs node --test demo/test/audit-core.test.mjs
``` ```
覆盖:捕获规则各分支(方法/路径/匿名/登录端点)、资源解析(集合/单资源/深层子资源/auth)、 覆盖:捕获规则(HTTP / 认证操作 / 登录页 GET 不记录 / 匿名 / 读操作)、资源解析(含查询串与深层子资源)、
筛选(操作者/资源类型/动作/结果/时间范围/关键字)、分页越界收敛、保留期统计、模拟数据确定性与字段完整性。 语义动作推导与中文描述(含登录页访问纠正)、登录结果判定(2xx / 302 跳回登录页 / 缺失 Location / 401)、
结果语义(登录失败 / 登录成功 / 页面访问不计成败)、
字段 diff(PUT / PATCH Merge / PATCH JSON Patch / POST / DELETE、元数据过滤、敏感字段脱敏、
截断、30 条封顶)、八维筛选(登录失败结果语义、时间闭区间、关键字)、分页与保留期、
CSV(BOM / CRLF / 列顺序 / 转义 / 公式注入防护 / 升序)、告警窗口(阈值、告警后重开、
成功清零、窗口过期)、模拟数据确定性与故事线完整性。
## 与真实实现的差异 ## 与真实实现的差异
| 项 | Demo | 真实插件 | | 项 | Demo | 真实插件 |
|---|---|---| |---|---|---|
| 数据 | 页面内存中的模拟数据,刷新即重置 | `AuditLog` Extension 落库 + 索引查询 | | 数据 | 页面内存中的模拟数据,刷新即重置 | `AuditLog` Extension 落库 + 索引查询 |
| 捕获 | 手动在弹窗里"发送请求"模拟 | `AfterSecurityWebFilter` 自动捕获 | | 捕获 | 弹窗里手动构造请求 | 双过滤器自动捕获(`/apis/**` + 认证操作 `POST /login`、`POST /logout`) |
| 写入 | 直接 unshift 到数组 | `ReactiveExtensionClient` 异步直写、失败降级 | | 字段 diff | 与 Java 版同规则的 JS 简化实现(对象递归、数组整体比较、脱敏/截断/封顶) | `ChangeDiffEngine`(含 Halo 服务端字段更细的降噪与 JSON Pointer 解析) |
| 设置 | 页面内存 | `settings.yaml` + ConfigMap(60s TTL 缓存) | | 查询 | 前端数组筛选 | 自有查询端点(fieldSelector + 时间区间 + 模糊匹配) |
| 清理 | 点击按钮模拟 | 每日定时任务自动执行 | | 导出 | 浏览器 Blob 下载 | 后端全量流式 CSV(分批 200 条) |
| 设置 | 页面内存 | `settings.yaml` + ConfigMap(60s TTL) |
| 告警 | 本地阈值窗口 + JSON 预览 | Webhook JSON POST + SSRF 防护 + Secret 存储地址 |
| 系统变更 | 手动模拟 | `ReactiveExtensionClient.watch` 全局 Watcher |
| 权限 | 未演示(本地即超管视角) | 角色模板 `role-template-audit-view`,仅 `get/list` | | 权限 | 未演示(本地即超管视角) | 角色模板 `role-template-audit-view`,仅 `get/list` |
UI 结构(筛选维度、列定义、详情字段、设置项)与真实插件将保持一致,确认交互合理后即可按技术方案里程碑 4 实现 Console 页面。 静态演示页与真实 Console 页面(Vue 3)共享同一套展示语义(列定义、筛选维度、
描述推导、结果徽标、字段变更展示),但真实页面源码在
[`plugin-operation-audit/ui/src/views/`](../plugin-operation-audit/ui/src/views/),由 Halo
Console 宿主渲染。
+833 -294
View File
File diff suppressed because it is too large Load Diff
+1169 -75
View File
File diff suppressed because it is too large Load Diff
+310 -79
View File
@@ -15,6 +15,8 @@
--warn-tint: rgba(217, 119, 6, 0.1); --warn-tint: rgba(217, 119, 6, 0.1);
--info: #2563eb; --info: #2563eb;
--info-tint: rgba(37, 99, 235, 0.1); --info-tint: rgba(37, 99, 235, 0.1);
--purple: #7c3aed;
--purple-tint: rgba(124, 58, 237, 0.1);
--gray-50: #f9fafb; --gray-50: #f9fafb;
--gray-100: #f3f4f6; --gray-100: #f3f4f6;
--gray-200: #e5e7eb; --gray-200: #e5e7eb;
@@ -30,12 +32,16 @@
* { box-sizing: border-box; } * { box-sizing: border-box; }
html, body { height: 100%; } /* hidden 属性优先于组件的 display 声明(如 .alert-banner{display:flex}) */
[hidden] { display: none !important; }
html { height: 100%; }
body { body {
margin: 0; margin: 0;
min-height: 100vh;
display: flex; display: flex;
min-width: 1080px; min-width: 1100px;
font-size: 14px; font-size: 14px;
color: var(--gray-900); color: var(--gray-900);
background: var(--gray-100); background: var(--gray-100);
@@ -165,6 +171,8 @@ body {
.readonly-hint { color: var(--primary-dark); } .readonly-hint { color: var(--primary-dark); }
.header-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.tabs { .tabs {
display: flex; display: flex;
gap: 4px; gap: 4px;
@@ -207,6 +215,13 @@ body {
padding: 14px 18px 0; padding: 14px 18px 0;
} }
.card-sub {
font-size: 12.5px;
color: var(--gray-500);
line-height: 1.6;
padding: 6px 18px 0;
}
.btn { .btn {
appearance: none; appearance: none;
border: none; border: none;
@@ -219,12 +234,17 @@ body {
align-items: center; align-items: center;
gap: 6px; gap: 6px;
transition: filter 0.15s, background 0.15s; transition: filter 0.15s, background 0.15s;
white-space: nowrap;
} }
.btn svg { .btn svg {
width: 13px; width: 14px;
height: 13px; height: 14px;
fill: currentColor; fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
} }
.btn-primary { background: var(--primary); color: #fff; } .btn-primary { background: var(--primary); color: #fff; }
@@ -237,6 +257,8 @@ body {
} }
.btn-outline:hover { border-color: var(--primary); color: var(--primary-dark); } .btn-outline:hover { border-color: var(--primary); color: var(--primary-dark); }
.btn-sm { padding: 6px 12px; font-size: 12.5px; }
.btn-link { .btn-link {
appearance: none; appearance: none;
border: none; border: none;
@@ -244,10 +266,8 @@ body {
color: var(--primary-dark); color: var(--primary-dark);
font-size: 13px; font-size: 13px;
cursor: pointer; cursor: pointer;
padding: 8px 4px; padding: 6px 4px;
align-self: flex-end;
} }
.btn-link:hover { text-decoration: underline; } .btn-link:hover { text-decoration: underline; }
.icon-btn { .icon-btn {
@@ -262,8 +282,8 @@ body {
cursor: pointer; cursor: pointer;
line-height: 1; line-height: 1;
} }
.icon-btn:hover { background: var(--gray-100); color: var(--gray-900); } .icon-btn:hover { background: var(--gray-100); color: var(--gray-900); }
.icon-btn[disabled] { opacity: 0.35; cursor: not-allowed; }
.input { .input {
border: 1px solid var(--gray-300); border: 1px solid var(--gray-300);
@@ -277,12 +297,13 @@ body {
} }
.input:focus, .input:focus,
select:focus { select:focus,
textarea:focus {
border-color: var(--primary); border-color: var(--primary);
box-shadow: 0 0 0 2px var(--primary-tint); box-shadow: 0 0 0 2px var(--primary-tint);
} }
select, .input { min-width: 0; } select, .input, textarea { min-width: 0; }
select { select {
appearance: none; appearance: none;
@@ -296,8 +317,21 @@ select {
cursor: pointer; cursor: pointer;
} }
textarea {
border: 1px solid var(--gray-300);
border-radius: 6px;
padding: 8px 10px;
font-family: ui-monospace, Consolas, monospace;
font-size: 12px;
line-height: 1.55;
resize: vertical;
width: 100%;
}
.hint { font-size: 12px; color: var(--gray-400); } .hint { font-size: 12px; color: var(--gray-400); }
.muted { color: var(--gray-400); font-size: 12px; } .muted { color: var(--gray-400); font-size: 12px; }
.mono { font-family: ui-monospace, Consolas, monospace; }
.break-all { word-break: break-all; }
/* ============ 横幅 ============ */ /* ============ 横幅 ============ */
.banner { .banner {
@@ -305,31 +339,64 @@ select {
padding: 10px 14px; padding: 10px 14px;
font-size: 13px; font-size: 13px;
margin-bottom: 14px; margin-bottom: 14px;
line-height: 1.55;
} }
.banner-warn { background: var(--warn-tint); color: var(--warn); border: 1px solid rgba(217, 119, 6, 0.25); } .banner-warn { background: var(--warn-tint); color: var(--warn); border: 1px solid rgba(217, 119, 6, 0.25); }
.banner-danger { background: var(--danger-tint); color: var(--danger); border: 1px solid rgba(215, 29, 29, 0.25); }
.alert-banner {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.alert-banner-body { flex: 1; }
.alert-banner-actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.alert-banner-actions .btn-link { color: var(--danger); }
/* ============ 筛选栏 ============ */ /* ============ 筛选栏 ============ */
.filter-bar { .filter-card {
display: flex;
align-items: flex-end;
gap: 12px;
padding: 12px 16px; padding: 12px 16px;
margin-bottom: 14px; margin-bottom: 14px;
flex-wrap: wrap;
} }
.filter-item { display: flex; flex-direction: column; gap: 4px; } .filter-grid {
.filter-item.grow { flex: 1; min-width: 180px; } display: grid;
.filter-item label { font-size: 11px; color: var(--gray-500); font-weight: 600; } grid-template-columns: repeat(8, minmax(0, 1fr)) auto;
.filter-item select, .filter-item .input { min-width: 120px; width: 100%; } gap: 10px 12px;
align-items: end;
}
/* ============ 表格 ============ */ .filter-item { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.filter-item > span { font-size: 11px; color: var(--gray-500); font-weight: 600; white-space: nowrap; }
.filter-item input,
.filter-item select { width: 100%; height: 32px; font-size: 12.5px; }
.filter-actions { display: flex; gap: 8px; }
.filter-note {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 10px;
padding-top: 10px;
border-top: 1px dashed var(--gray-200);
font-size: 12px;
color: var(--gray-500);
}
/* ============ 列表 ============ */
.table-card { overflow: hidden; } .table-card { overflow: hidden; }
.audit-list-wrap { overflow-x: auto; }
.audit-table { .audit-table {
width: 100%; width: 100%;
min-width: 900px;
border-collapse: collapse; border-collapse: collapse;
table-layout: fixed;
} }
.audit-table th { .audit-table th {
@@ -337,17 +404,18 @@ select {
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
color: var(--gray-500); color: var(--gray-500);
padding: 10px 16px; padding: 10px 14px;
background: var(--gray-50); background: var(--gray-50);
border-bottom: 1px solid var(--gray-200); border-bottom: 1px solid var(--gray-200);
white-space: nowrap; white-space: nowrap;
} }
.audit-table td { .audit-table td {
padding: 10px 16px; padding: 9px 14px;
border-bottom: 1px solid var(--gray-100); border-bottom: 1px solid var(--gray-100);
font-size: 13px; font-size: 13px;
vertical-align: middle; vertical-align: middle;
overflow: hidden;
} }
.audit-table tbody tr { .audit-table tbody tr {
@@ -356,20 +424,20 @@ select {
} }
.audit-table tbody tr:hover { background: var(--gray-50); } .audit-table tbody tr:hover { background: var(--gray-50); }
.audit-table tbody tr.selected td { background: var(--primary-tint); } .audit-table tbody tr.selected td { background: var(--primary-tint); }
@keyframes rowFlash { @keyframes rowFlash {
0% { background: var(--primary-tint); } 0% { background: var(--primary-tint); }
100% { background: transparent; } 100% { background: transparent; }
} }
tr.row-new td { animation: rowFlash 2.8s ease-out; }
tr.row-new td { animation: rowFlash 2.6s ease-out; } .td-ip { color: var(--gray-500); font-variant-numeric: tabular-nums; white-space: nowrap; }
.td-time { color: var(--gray-700); font-variant-numeric: tabular-nums; white-space: nowrap; } .cell-user { display: flex; align-items: center; gap: 8px; min-width: 0; }
.td-ip { color: var(--gray-500); font-variant-numeric: tabular-nums; } .user-lines { min-width: 0; }
.u-name { font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cell-user { display: flex; align-items: center; gap: 8px; } .u-time { font-size: 11.5px; color: var(--gray-400); font-variant-numeric: tabular-nums; white-space: nowrap; }
/* 动作徽标 */ /* 动作徽标 */
.method { .method {
@@ -384,10 +452,17 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.m-post { background: var(--info-tint); color: var(--info); } .m-post { background: var(--info-tint); color: var(--info); }
.m-put { background: var(--warn-tint); color: var(--warn); } .m-put { background: var(--warn-tint); color: var(--warn); }
.m-delete { background: var(--danger-tint); color: var(--danger); } .m-delete { background: var(--danger-tint); color: var(--danger); }
.m-patch { background: rgba(124, 58, 237, 0.1); color: #6d28d9; } .m-patch { background: var(--purple-tint); color: var(--purple); }
.m-get { background: var(--gray-100); color: var(--gray-500); } .m-get { background: var(--gray-100); color: var(--gray-500); }
/* 资源列 */ /* 资源列 */
.res-line {
display: flex;
align-items: center;
gap: 6px;
overflow: hidden;
white-space: nowrap;
}
.rt { .rt {
display: inline-block; display: inline-block;
font-size: 11px; font-size: 11px;
@@ -396,29 +471,66 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
background: var(--gray-100); background: var(--gray-100);
border-radius: 4px; border-radius: 4px;
padding: 2px 7px; padding: 2px 7px;
margin-right: 8px;
}
.rn { color: var(--gray-500); font-size: 12.5px; word-break: break-all; }
/* 结果徽标 */
.result {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
font-weight: 500;
font-variant-numeric: tabular-nums;
}
.result i {
width: 7px;
height: 7px;
border-radius: 50%;
flex-shrink: 0; flex-shrink: 0;
} }
.result.ok { color: #16a34a; } .rn {
.result.ok i { background: #16a34a; } color: var(--gray-700);
.result.fail { color: var(--danger); } font-size: 12.5px;
.result.fail i { background: var(--danger); } overflow: hidden;
text-overflow: ellipsis;
}
.history-link {
flex-shrink: 0;
font-size: 11.5px;
color: var(--primary-dark);
text-decoration: none;
cursor: pointer;
}
.history-link:hover { text-decoration: underline; }
.path-line {
margin-top: 2px;
font-family: ui-monospace, Consolas, monospace;
font-size: 11px;
color: var(--gray-400);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 描述列 */
.action-desc {
display: inline-block;
max-width: 100%;
font-size: 12.5px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.changes-hint {
display: inline-block;
margin-left: 4px;
padding: 1px 5px;
border-radius: 4px;
font-size: 10.5px;
color: var(--warn);
background: var(--warn-tint);
vertical-align: middle;
}
/* 结果徽标 */
.status-badge {
display: inline-block;
padding: 2px 7px;
border-radius: 4px;
font-size: 11.5px;
font-weight: 600;
font-family: ui-monospace, Consolas, monospace;
}
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
.status-fail { color: var(--danger); background: rgba(215, 29, 29, 0.12); }
/* 页面访问(登录页/登出页的 GET,不计成败):中性灰 */
.status-na { color: #6b7280; background: rgba(107, 114, 128, 0.12); }
/* 空状态 */ /* 空状态 */
.empty-state { .empty-state {
@@ -444,11 +556,11 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.pg-right { display: flex; align-items: center; gap: 8px; } .pg-right { display: flex; align-items: center; gap: 8px; }
.pg-right select { padding: 5px 24px 5px 8px; font-size: 12.5px; } .pg-right select { padding: 5px 24px 5px 8px; font-size: 12.5px; }
.icon-btn[disabled] { opacity: 0.35; cursor: not-allowed; } .pg-page { font-size: 12.5px; color: var(--gray-500); font-variant-numeric: tabular-nums; }
/* ============ 设置页 ============ */ /* ============ 设置页 ============ */
#panel-settings .settings-card { max-width: 780px; } #panel-settings .settings-card { max-width: 820px; }
.settings-card { margin-bottom: 16px; padding-bottom: 6px; } .settings-card { margin-bottom: 16px; padding-bottom: 4px; }
.setting-row { .setting-row {
display: flex; display: flex;
@@ -459,11 +571,18 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
border-bottom: 1px solid var(--gray-100); border-bottom: 1px solid var(--gray-100);
} }
.setting-text { max-width: 640px; } .setting-text { max-width: 620px; }
.s-name { font-size: 14px; font-weight: 600; margin-bottom: 4px; } .s-name { font-size: 14px; font-weight: 600; margin-bottom: 4px; }
.s-desc { font-size: 12.5px; color: var(--gray-500); line-height: 1.5; } .s-desc { font-size: 12.5px; color: var(--gray-500); line-height: 1.55; }
.s-desc code {
background: var(--gray-100);
border-radius: 4px;
padding: 1px 5px;
font-size: 11.5px;
}
.input.num { width: 90px; text-align: center; } .input.num { width: 96px; text-align: center; flex-shrink: 0; }
.input.secret-input { width: 280px; flex-shrink: 0; }
.settings-actions { .settings-actions {
display: flex; display: flex;
@@ -480,7 +599,16 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
} }
.clean-stats .num-warn { color: var(--danger); font-weight: 600; } .clean-stats .num-warn { color: var(--danger); font-weight: 600; }
.settings-card .btn { margin: 0 18px 16px; } .alert-preview {
margin: 0 18px 16px;
padding: 12px;
background: var(--secondary);
color: #d1fae5;
border-radius: 6px;
font-size: 11.5px;
line-height: 1.55;
overflow-x: auto;
}
/* 开关 */ /* 开关 */
.switch { position: relative; display: inline-block; width: 40px; height: 22px; flex-shrink: 0; } .switch { position: relative; display: inline-block; width: 40px; height: 22px; flex-shrink: 0; }
@@ -525,7 +653,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
flex-shrink: 0; flex-shrink: 0;
} }
.avatar.sm { width: 22px; height: 22px; font-size: 10px; } .avatar.sm { width: 24px; height: 24px; font-size: 11px; }
.c-a { background: #4ccba0; } .c-a { background: #4ccba0; }
.c-b { background: #6366f1; } .c-b { background: #6366f1; }
@@ -545,8 +673,8 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
position: fixed; position: fixed;
top: 0; top: 0;
right: 0; right: 0;
width: 440px; width: 480px;
max-width: 92vw; max-width: 94vw;
height: 100vh; height: 100vh;
background: #fff; background: #fff;
z-index: 50; z-index: 50;
@@ -571,7 +699,13 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
} }
.drawer-title { font-size: 16px; font-weight: 700; } .drawer-title { font-size: 16px; font-weight: 700; }
.drawer-sub { font-size: 12px; color: var(--gray-400); margin-top: 3px; font-family: ui-monospace, Consolas, monospace; } .drawer-sub {
font-size: 11.5px;
color: var(--gray-400);
margin-top: 3px;
font-family: ui-monospace, Consolas, monospace;
word-break: break-all;
}
.readonly-banner { .readonly-banner {
background: var(--primary-tint); background: var(--primary-tint);
@@ -586,24 +720,26 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.detail-list { margin: 0; } .detail-list { margin: 0; }
.detail-list .d-row { .detail-list .d-row {
padding: 9px 0; display: flex;
gap: 12px;
padding: 8px 0;
border-bottom: 1px dashed var(--gray-200); border-bottom: 1px dashed var(--gray-200);
} }
.detail-list dt { .detail-list dt {
font-size: 11.5px; flex: 0 0 5.5rem;
font-size: 12px;
color: var(--gray-500); color: var(--gray-500);
font-weight: 600; font-weight: 600;
margin-bottom: 5px; padding-top: 1px;
} }
.detail-list dd { .detail-list dd {
flex: 1;
margin: 0; margin: 0;
font-size: 13px; font-size: 12.5px;
word-break: break-all; word-break: break-all;
display: flex; min-width: 0;
align-items: center;
gap: 8px;
} }
.path-code { .path-code {
@@ -617,9 +753,48 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
line-height: 1.6; line-height: 1.6;
} }
.ua { font-size: 12px; color: var(--gray-500); line-height: 1.6; } .ua { font-size: 11.5px; color: var(--gray-500); line-height: 1.6; }
.raw-json { margin-top: 16px; } .changes { margin-top: 18px; }
.changes-title {
font-size: 13px;
font-weight: 600;
color: var(--gray-900);
margin: 0 0 6px;
}
.change-row {
display: flex;
gap: 10px;
padding: 8px 0;
border-bottom: 1px dashed var(--gray-200);
}
.change-badge {
flex: 0 0 auto;
align-self: flex-start;
margin-top: 1px;
padding: 1px 6px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
}
.change-added { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
.change-updated { color: var(--warn); background: var(--warn-tint); }
.change-removed { color: var(--danger); background: var(--danger-tint); }
.change-body { flex: 1; min-width: 0; }
.change-field { font-size: 12px; color: var(--gray-900); word-break: break-all; }
.change-values {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 5px;
margin-top: 2px;
font-size: 12px;
color: var(--gray-700);
}
.change-old { color: var(--danger); text-decoration: line-through; }
.change-arrow { color: var(--gray-400); flex-shrink: 0; }
.raw-json { margin-top: 18px; }
.raw-json summary { .raw-json summary {
font-size: 12.5px; font-size: 12.5px;
color: var(--gray-500); color: var(--gray-500);
@@ -631,11 +806,12 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.raw-json pre { .raw-json pre {
background: var(--secondary); background: var(--secondary);
color: #d1fae5; color: #d1fae5;
font-size: 11.5px; font-size: 11px;
border-radius: 6px; border-radius: 6px;
padding: 12px; padding: 12px;
overflow-x: auto; overflow-x: auto;
line-height: 1.6; line-height: 1.6;
max-height: 320px;
} }
/* ============ 模拟操作弹窗 ============ */ /* ============ 模拟操作弹窗 ============ */
@@ -644,8 +820,10 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
top: 50%; top: 50%;
left: 50%; left: 50%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
width: 520px; width: 680px;
max-width: 92vw; max-width: 94vw;
max-height: 90vh;
overflow-y: auto;
background: #fff; background: #fff;
border-radius: 10px; border-radius: 10px;
z-index: 50; z-index: 50;
@@ -656,7 +834,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.modal[hidden] { display: none; } .modal[hidden] { display: none; }
@keyframes popIn { @keyframes popIn {
from { transform: translate(-50%, -50%) scale(0.96); opacity: 0; } from { transform: translate(-50%, -50%) scale(0.97); opacity: 0; }
to { transform: translate(-50%, -50%) scale(1); opacity: 1; } to { transform: translate(-50%, -50%) scale(1); opacity: 1; }
} }
@@ -674,7 +852,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
font-size: 12.5px; font-size: 12.5px;
color: var(--gray-500); color: var(--gray-500);
line-height: 1.6; line-height: 1.6;
margin: 8px 0 14px; margin: 8px 0 12px;
} }
.modal-sub code { .modal-sub code {
@@ -684,9 +862,35 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
font-size: 11.5px; font-size: 11.5px;
} }
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; } .seg-tabs {
display: inline-flex;
background: var(--gray-100);
border-radius: 7px;
padding: 3px;
margin-bottom: 14px;
}
.seg-tab {
appearance: none;
border: none;
background: none;
padding: 6px 14px;
font-size: 12.5px;
font-weight: 500;
color: var(--gray-500);
border-radius: 5px;
cursor: pointer;
}
.seg-tab.active {
background: #fff;
color: var(--gray-900);
font-weight: 600;
box-shadow: var(--shadow);
}
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; min-width: 0; }
.field label { font-size: 12px; color: var(--gray-500); font-weight: 600; } .field label { font-size: 12px; color: var(--gray-500); font-weight: 600; }
.field select, .field .input { width: 100%; } .field select, .field .input { width: 100%; }
.field textarea { width: 100%; }
.field-row { display: flex; gap: 12px; } .field-row { display: flex; gap: 12px; }
@@ -710,7 +914,13 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
gap: 10px; gap: 10px;
margin-top: 6px; /* 弹窗内容超高时操作按钮始终可见 */
position: sticky;
bottom: -20px;
margin: 6px -22px -20px;
padding: 12px 22px 20px;
border-top: 1px solid var(--gray-100);
background: #fff;
} }
/* ============ Toast ============ */ /* ============ Toast ============ */
@@ -729,9 +939,30 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
pointer-events: none; pointer-events: none;
transition: opacity 0.25s, transform 0.25s; transition: opacity 0.25s, transform 0.25s;
z-index: 100; z-index: 100;
max-width: 60vw; max-width: 70vw;
} }
.toast.show { opacity: 1; transform: translate(-50%, 0); } .toast.show { opacity: 1; transform: translate(-50%, 0); }
.toast.ok { background: var(--primary-dark); } .toast.ok { background: var(--primary-dark); }
.toast.warn { background: #92400e; } .toast.warn { background: #92400e; }
/* ============ 响应式(演示页以桌面为主,窄屏保证可用) ============ */
@media (max-width: 1400px) {
.filter-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.filter-actions { grid-column: 1 / -1; }
}
@media (max-width: 1180px) {
body { min-width: 900px; }
.page-header { flex-direction: column; }
.header-actions { align-self: flex-end; }
}
@media (max-width: 760px) {
body { min-width: 0; }
.sidebar { display: none; }
.main { padding: 16px 14px 32px; }
.filter-grid { grid-template-columns: minmax(0, 1fr); }
.field-row { flex-direction: column; gap: 0; }
.modal { width: 94vw; }
}
+609 -112
View File
@@ -1,9 +1,18 @@
/** /**
* 操作审计 · 模拟数据生成器(种子随机,确定性输出) * 操作审计 · 模拟数据生成器(种子随机,确定性输出)
* *
* 记录字段与产品设计 4.1 表格一一对应;resourceType/resourceName 通过 * 记录字段与插件 spec 一致:username / attemptedUsername / method / action /
* AuditCore.resolveResource 从路径解析得出(模拟真实捕获管线)。 * resourceType / resourceName / path / statusCode / remoteIp / userAgent / changes。
* 内置若干"故事线"数据:登录爆破、越权 403、服务端 500 等,便于验证筛选场景。 * 资源解析、语义动作、登录结果与字段 diff 全部经 AuditCore 按真实捕获管线推导,
* 便于在演示页复现「谁改了什么」而不仅是「谁点了什么」。
*
* 内置故事线(固定时间锚点,可直接按演示页提示复现):
* 1. 排查「hello-halo 这篇文章谁改过」(多用户多次编辑,含字段 diff)
* 2. 登录爆破回溯(同一 IP、无差别撞库;另含升级前落库的登录页访问记录)
* 3. 忘记密码后登录成功(失败 → 成功清零)
* 4. 定时发布(系统内部变更,执行者「系统」、无 IP/UA)
* 5. 插件生命周期(升级 / 停用 / 卸载,含字段 diff)
* 6. 越权与异常(403 / 404 / 500)
*/ */
(function (root, factory) { (function (root, factory) {
if (typeof module === 'object' && module.exports) { if (typeof module === 'object' && module.exports) {
@@ -16,7 +25,7 @@
var DAY = 86400000; var DAY = 86400000;
var MIN = 60000; var MIN = 60000;
var BASE_COUNT = 128; // 随机生成的基础记录条数 var BASE_COUNT = 116;
// ---------- 种子随机 ---------- // ---------- 种子随机 ----------
function mulberry32(seed) { function mulberry32(seed) {
@@ -38,10 +47,17 @@
function hex(r, n) { function hex(r, n) {
var s = ''; var s = '';
var chars = '0123456789abcdef'; var chars = '0123456789abcdef';
for (var i = 0; i < n; i++) s += chars[rint(r, 0, 15)]; for (var i = 0; i < n; i++) {
s += chars[rint(r, 0, 15)];
}
return s; return s;
} }
/** 演示用的一次性假口令(运行时生成,非真实凭据;仅用于验证敏感字段脱敏)。 */
function demoSecret(r) {
return 'demo-only-' + hex(r, 12);
}
// ---------- 基础素材 ---------- // ---------- 基础素材 ----------
var UAS = { var UAS = {
chrome: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.2151.97 Safari/537.36', chrome: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.2151.97 Safari/537.36',
@@ -52,156 +68,637 @@
}; };
var USERS = { var USERS = {
'guichumo': { ips: ['192.168.1.23', '116.24.65.187'], uas: ['chrome', 'edge'] }, guichumo: { ips: ['192.168.1.23', '116.24.65.187'], uas: ['chrome', 'edge'] },
'editor.zhang': { ips: ['116.24.65.201'], uas: ['edge', 'firefox'] }, 'editor.zhang': { ips: ['116.24.65.201'], uas: ['edge', 'firefox'] },
'writer.li': { ips: ['120.79.10.45'], uas: ['safari', 'chrome'] } 'writer.li': { ips: ['120.79.10.45'], uas: ['safari', 'chrome'] }
}; };
var SLUGS = ['hello-halo', 'self-host-guide', 'weekly-2026-w46', 'reading-notes-11', 'plugin-dev-diary', 'spring-festival-2026']; var POSTS = [
var PLUGINS = ['plugin-search-widget', 'plugin-comment-widget', 'plugin-sitemap', 'plugin-links']; { name: 'hello-halo', title: '你好,Halo', summary: '从零开始搭建自己的写作空间。' },
{ name: 'self-host-guide', title: '自托管指南', summary: '用 Docker 部署 Halo 的完整步骤。' },
function postPath(r) { return '/apis/content.halo.run/v1alpha1/posts/' + pick(r, SLUGS); } { name: 'reading-notes-11', title: '读书笔记 #11', summary: '本周读完的三本书。' },
function publishPath(r) { return '/apis/api.content.halo.run/v1alpha1/posts/' + pick(r, SLUGS) + '/publish'; } { name: 'plugin-dev-diary', title: '插件开发日志', summary: '从脚手架到上架。' },
function commentPath(r) { return '/apis/content.halo.run/v1alpha1/comments/comment-' + hex(r, 6); } { name: 'weekly-2026-w46', title: '每周摘要 · 2026 W46', summary: '站点一周动态。' },
function approvePath(r) { return '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/approve'; } { name: 'spring-festival-2026', title: '春节计划', summary: '假期更新安排。' }
function replyPath(r) { return '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/reply'; }
function attachPath(r) { return '/apis/storage.halo.run/v1alpha1/attachments/attachment-' + hex(r, 6); }
// [权重, 操作者, 方法, 路径函数, 状态码]
var ACTIONS = [
[16, 'guichumo', 'PUT', postPath, 200],
[10, 'guichumo', 'POST', publishPath, 200],
[6, 'guichumo', 'POST', function () { return '/apis/content.halo.run/v1alpha1/posts'; }, 201],
[5, 'guichumo', 'PUT', function () { return '/apis/v1alpha1/configmaps/system'; }, 200],
[4, 'guichumo', 'PUT', function (r) { return '/apis/plugin.halo.run/v1alpha1/plugins/' + pick(r, PLUGINS); }, 200],
[4, 'guichumo', 'POST', function () { return '/apis/storage.halo.run/v1alpha1/attachments'; }, 201],
[4, 'guichumo', 'DELETE', attachPath, 204],
[3, 'guichumo', 'DELETE', commentPath, 204],
[3, 'guichumo', 'PUT', function () { return '/apis/v1alpha1/roles/role-template-editor'; }, 200],
[2, 'guichumo', 'POST', function () { return '/login'; }, 200],
[2, 'guichumo', 'POST', function () { return '/logout'; }, 200],
[12, 'editor.zhang', 'PUT', postPath, 200],
[6, 'editor.zhang', 'POST', function () { return '/apis/content.halo.run/v1alpha1/posts'; }, 201],
[2, 'editor.zhang', 'POST', function () { return '/login'; }, 200],
[2, 'editor.zhang', 'POST', function () { return '/apis/storage.halo.run/v1alpha1/attachments'; }, 201],
[8, 'writer.li', 'PUT', postPath, 200],
[6, 'writer.li', 'POST', approvePath, 200],
[3, 'writer.li', 'POST', replyPath, 200],
[2, 'writer.li', 'POST', function () { return '/login'; }, 200]
]; ];
var TOTAL_WEIGHT = ACTIONS.reduce(function (sum, a) { return sum + a[0]; }, 0); var PLUGINS = [
{ name: 'plugin-search-widget', displayName: '搜索组件', version: { old: '1.2.0', next: '1.3.0' } },
{ name: 'plugin-comment-widget', displayName: '评论组件', version: { old: '1.5.0', next: '1.6.0' } },
{ name: 'plugin-sitemap', displayName: 'Sitemap', version: { old: '1.0.4', next: '1.0.5' } },
{ name: 'plugin-links', displayName: '友情链接', version: { old: '2.1.1', next: '2.2.0' } }
];
function userCtx(r, name) { // ---------- 文档快照(diff 用,结构贴近 Halo 扩展模型)----------
var u = USERS[name]; function postDoc(entry, patch) {
var spec = {
title: entry.title,
slug: entry.name,
visible: 'PUBLIC',
publish: true,
pinned: false,
allowComment: true,
summary: entry.summary
};
Object.keys(patch || {}).forEach(function (key) {
spec[key] = patch[key];
});
return { return {
username: name, apiVersion: 'content.halo.run/v1alpha1',
remoteIp: pick(r, u.ips), kind: 'Post',
userAgent: UAS[pick(r, u.uas)] metadata: {
name: entry.name,
labels: { 'content.halo.run/pinned': 'false' },
annotations: { 'content.halo.run/permalink-pattern': '/archives/:slug' },
version: 128,
creationTimestamp: '2026-10-01T08:00:00Z'
},
spec: spec,
status: { phase: 'PUBLISHED', permalink: '/archives/' + entry.name }
}; };
} }
function rec(timestamp, username, method, path, statusCode, remoteIp, userAgent) { function commentDoc(name, approved) {
var res = AuditCore.resolveResource(path); return {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Comment',
metadata: { name: name, version: 7 },
spec: {
raw: '写得很好,收藏了。',
owner: { displayName: '访客' + name.slice(-4), kind: 'Email' },
approved: approved,
hidden: false,
allowNotification: true
}
};
}
function pluginDoc(plugin, enabled, version) {
return {
apiVersion: 'plugin.halo.run/v1alpha1',
kind: 'Plugin',
metadata: { name: plugin.name, labels: { 'plugin.halo.run/plugin-name': plugin.name } },
spec: {
displayName: plugin.displayName,
version: version,
enabled: enabled,
author: { name: 'halo-sigs' },
requires: '>=2.20.0'
},
status: { phase: enabled ? 'STARTED' : 'DISABLED' }
};
}
// ---------- 记录组装 ----------
function recCtx(r, username) {
var u = USERS[username] || USERS.guichumo;
return { return {
id: null,
timestamp: timestamp,
username: username, username: username,
method: AuditCore.normalizeMethod(method), remoteIp: pick(r, u.ips),
path: path, userAgent: UAS[pick(r, u.uas)],
resourceType: res.resourceType, authenticated: true
resourceName: res.resourceName,
statusCode: statusCode,
remoteIp: remoteIp,
userAgent: userAgent
}; };
} }
function make(overrides) {
return AuditCore.buildRecord(Object.assign({
statusCode: 200,
authenticated: true,
recordChanges: true
}, overrides));
}
function postPath(name) { return '/apis/content.halo.run/v1alpha1/posts/' + name; }
function postsPath() { return '/apis/content.halo.run/v1alpha1/posts'; }
function commentPath(name) { return '/apis/content.halo.run/v1alpha1/comments/' + name; }
function pluginPath(name) { return '/apis/plugin.halo.run/v1alpha1/plugins/' + name; }
/**
* 基础操作集:[权重, 构造函数(r) → 记录输入]
* 每次构造经过 buildRecord:资源解析、语义动作、登录结果、字段 diff 与插件一致。
*/
var ACTIONS = [
[16, function (r) {
var entry = pick(r, POSTS);
var ctx = recCtx(r, pick(r, ['guichumo', 'editor.zhang', 'writer.li']));
return Object.assign(ctx, {
method: 'PUT',
path: postPath(entry.name),
previous: postDoc(entry),
body: postDoc(entry, {
title: entry.title + '(修订)',
summary: entry.summary + ' 已补充示例。'
})
});
}],
[9, function (r) {
var entry = pick(r, POSTS);
var ctx = recCtx(r, pick(r, ['guichumo', 'editor.zhang']));
return Object.assign(ctx, {
method: 'POST',
path: postPath(entry.name) + '/publish'
});
}],
[7, function (r) {
var ctx = recCtx(r, 'guichumo');
var slug = 'draft-' + hex(r, 5);
return Object.assign(ctx, {
method: 'POST',
path: postsPath(),
statusCode: 201,
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Post',
metadata: { name: slug },
spec: { title: '草稿 · ' + slug, slug: slug, visible: 'PUBLIC', publish: false }
}
});
}],
[6, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/configmaps/system',
previous: {
apiVersion: 'v1alpha1',
kind: 'ConfigMap',
metadata: { name: 'system', version: 9 },
data: { theme: 'theme-earth', locale: 'zh-CN' }
},
body: {
apiVersion: 'v1alpha1',
kind: 'ConfigMap',
metadata: { name: 'system', version: 10 },
data: { theme: 'theme-earth', locale: 'zh-CN', 'site.title': '青竹小站' }
}
});
}],
[5, function (r) {
var plugin = pick(r, PLUGINS);
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: pluginPath(plugin.name) + '/activation',
previous: pluginDoc(plugin, false, plugin.version.old),
body: pluginDoc(plugin, true, plugin.version.old)
});
}],
[5, function (r) {
var ctx = recCtx(r, pick(r, ['editor.zhang', 'writer.li']));
var name = 'attachment-' + hex(r, 6);
return Object.assign(ctx, {
method: 'POST',
path: '/apis/storage.halo.run/v1alpha1/attachments',
statusCode: 201,
body: {
apiVersion: 'storage.halo.run/v1alpha1',
kind: 'Attachment',
metadata: { name: name },
spec: { displayName: 'cover-' + hex(r, 4) + '.png', mediaType: 'image/png', size: rint(r, 80, 640) * 1024 }
}
});
}],
[3, function (r) {
var ctx = recCtx(r, 'editor.zhang');
var name = 'attachment-' + hex(r, 6);
return Object.assign(ctx, {
method: 'DELETE',
path: '/apis/storage.halo.run/v1alpha1/attachments/' + name,
statusCode: 204,
previous: {
apiVersion: 'storage.halo.run/v1alpha1',
kind: 'Attachment',
metadata: { name: name },
spec: { displayName: 'old-cover.png', mediaType: 'image/png', size: 245760 }
}
});
}],
[4, function (r) {
var ctx = recCtx(r, 'writer.li');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/reply',
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Reply',
metadata: { name: 'reply-' + hex(r, 4) },
spec: { raw: '感谢支持,已更新示例。', quoteReply: 'comment-' + hex(r, 4) }
}
});
}],
[3, function (r) {
var ctx = recCtx(r, 'editor.zhang');
var name = 'comment-' + hex(r, 6);
return Object.assign(ctx, {
method: 'DELETE',
path: commentPath(name),
statusCode: 204,
previous: commentDoc(name, true)
});
}],
[3, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/roles/role-template-editor',
previous: {
apiVersion: 'v1alpha1',
kind: 'Role',
metadata: { name: 'role-template-editor', labels: { 'rbac.authorization.halo.run/display-name': '编辑' } },
rules: [{ apiGroups: ['content.halo.run'], resources: ['posts'], verbs: ['get', 'list', 'create', 'update'] }]
},
body: {
apiVersion: 'v1alpha1',
kind: 'Role',
metadata: { name: 'role-template-editor', labels: { 'rbac.authorization.halo.run/display-name': '编辑' } },
rules: [{ apiGroups: ['content.halo.run'], resources: ['posts'], verbs: ['get', 'list', 'create', 'update', 'delete'] }]
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.console.halo.run/v1alpha1/users',
statusCode: 201,
body: {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'alice-' + hex(r, 4) },
spec: {
displayName: 'Alice',
email: 'alice-' + hex(r, 3) + '@example.com',
// 运行时生成的假口令:用于验证 spec.password 在 diff 中被脱敏
password: demoSecret(r),
roles: ['role-template-author']
}
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/users/guichumo/password',
previous: {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'guichumo' },
spec: { password: demoSecret(r) }
},
body: {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'guichumo' },
spec: { password: demoSecret(r) }
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'writer.li');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/content.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/approve'
});
}],
[2, function (r) {
var ctx = recCtx(r, 'editor.zhang');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.console.halo.run/v1alpha1/categories',
statusCode: 201,
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Category',
metadata: { name: 'category-' + hex(r, 4) },
spec: { displayName: '技术随笔', slug: 'tech-notes', priority: 10 }
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'editor.zhang');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/theme.halo.run/v1alpha1/themes/theme-earth/activation'
});
}],
[1, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.halo.run/v1alpha1/settings/basic'
});
}],
[1, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.halo.run/v1alpha1/tags',
statusCode: 201,
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Tag',
metadata: { name: 'tag-' + hex(r, 4) },
spec: { displayName: 'Halo', slug: 'halo' }
}
});
}],
[1, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.halo.run/v1alpha1/menus/menu-primary',
previous: {
apiVersion: 'v1alpha1',
kind: 'Menu',
metadata: { name: 'menu-primary' },
spec: { displayName: '主菜单', menuItems: ['/archives', '/categories'] }
},
body: {
apiVersion: 'v1alpha1',
kind: 'Menu',
metadata: { name: 'menu-primary' },
spec: { displayName: '主菜单', menuItems: ['/archives', '/categories', '/about'] }
}
});
}]
];
var TOTAL_WEIGHT = ACTIONS.reduce(function (sum, item) { return sum + item[0]; }, 0);
/** /**
* 生成模拟审计日志(按时间倒序,id 从旧到新递增) * 生成模拟审计日志(按时间倒序,id 从旧到新递增)
* @param {number} [now] 当前时间戳(默认 Date.now()),测试传固定值保证确定性 * @param {number} [now] 当前时间戳(默认 Date.now()),测试传固定值保证确定性
* @returns {Array} * @returns {Array}
*/ */
function generateLogs(now) { function generateLogs(now) {
if (typeof now !== 'number') now = Date.now(); if (typeof now !== 'number') {
var r = mulberry32(20261121); now = Date.now();
}
var r = mulberry32(20261122);
var logs = []; var logs = [];
// 基础记录:均匀散布在近 90 天 function add(record) {
logs.push(record);
return record;
}
// ---- 基础记录:均匀散布在近 90 天 ----
for (var i = 0; i < BASE_COUNT; i++) { for (var i = 0; i < BASE_COUNT; i++) {
var roll = r() * TOTAL_WEIGHT; var roll = r() * TOTAL_WEIGHT;
var action = ACTIONS[0]; var action = ACTIONS[0][1];
for (var j = 0; j < ACTIONS.length; j++) { for (var j = 0; j < ACTIONS.length; j++) {
roll -= ACTIONS[j][0]; roll -= ACTIONS[j][0];
if (roll <= 0) { action = ACTIONS[j]; break; } if (roll <= 0) {
action = ACTIONS[j][1];
break;
} }
var ctx = userCtx(r, action[1]); }
var time = now - rint(r, 5 * MIN, 90 * DAY); var input = action(r);
logs.push(rec( input.timestamp = new Date(now - rint(r, 5 * MIN, 90 * DAY)).toISOString();
new Date(time).toISOString(), ctx.username, add(make(input));
action[2], action[3](r), action[4],
ctx.remoteIp, ctx.userAgent
));
} }
// ---- 故事线(固定时间锚点)---- // ---- 故事线 1:排查「hello-halo 这篇文章谁改过」 ----
var hello = POSTS[0];
add(make({
username: 'editor.zhang',
remoteIp: '116.24.65.201',
userAgent: UAS.edge,
method: 'PUT',
path: postPath(hello.name),
timestamp: new Date(now - 6 * DAY - 3 * 3600 * 1000).toISOString(),
previous: postDoc(hello),
body: postDoc(hello, { title: '你好,Halo(补充开箱截图)', summary: '从零开始搭建自己的写作空间,附开箱截图。' })
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: postPath(hello.name),
timestamp: new Date(now - 2 * DAY - 5 * 3600 * 1000).toISOString(),
previous: postDoc(hello, { title: '你好,Halo(补充开箱截图)' }),
body: postDoc(hello, { title: '你好,Halo', summary: '从零开始搭建自己的写作空间。', visible: 'PRIVATE' })
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: postPath(hello.name),
timestamp: new Date(now - 2 * DAY - 2 * 3600 * 1000).toISOString(),
previous: postDoc(hello, { visible: 'PRIVATE' }),
body: postDoc(hello, { visible: 'PUBLIC', pinned: true })
}));
// 1. 攻击者爆破登录:20 天前,同一 IP 6 次失败,UA 为 python-requests // ---- 故事线 2:登录爆破回溯(同一 IP、无差别撞库 + 升级前的登录页访问记录) ----
var burstBase = now - 20 * DAY - 3600 * 1000 * 3; // 约 20 天前的凌晨 var burstBase = now - 20 * DAY - 3 * 3600 * 1000;
[0, 41, 88, 135, 210, 400].forEach(function (off) { var attackAccounts = ['admin', 'root', 'oracle', 'test', 'admin', 'postgres'];
logs.push(rec( attackAccounts.forEach(function (account, idx) {
new Date(burstBase + off * 1000).toISOString(), '未知用户', add(make({
'POST', '/login', 401, '203.0.113.66', UAS.bot method: 'POST',
)); path: '/login',
statusCode: 302,
location: '/login?error=invalid-credential&method=form',
attemptedUsername: account,
remoteIp: '203.0.113.66',
userAgent: UAS.bot,
timestamp: new Date(burstBase + [0, 41, 88, 135, 210, 400][idx] * 1000).toISOString()
}));
});
// 升级前落库的登录页访问记录:旧版本把登录/登出页的 GET 访问也记成「登录/登出」
// (HTTP 200,标注 login/logout),现已不再记录;历史记录展示为「访问登录页/登出页」,
// 结果不计成败。失败回显页当时标注 login-failure,仍按登录失败展示。
[
{ at: 30, path: '/login', action: 'login' },
{ at: 70, path: '/login?authentication_required', action: 'login' },
{ at: 401, path: '/login?error=invalid-credential&method=form', action: 'login-failure' }
].forEach(function (visit) {
var legacy = make({
method: 'GET',
path: visit.path,
statusCode: 200,
remoteIp: '203.0.113.66',
userAgent: UAS.bot,
timestamp: new Date(burstBase + visit.at * 1000).toISOString()
});
legacy.action = visit.action;
add(legacy);
}); });
// 2. 站长忘记密码:12 天前输错两次后登录成功 // ---- 故事线 3:忘记密码(失败两次后成功) ----
var b2 = now - 12 * DAY - 3600 * 1000 * 10; var retryBase = now - 12 * DAY - 10 * 3600 * 1000;
[[0, 401], [97, 401], [180, 200]].forEach(function (pair) { [
var ctx = { remoteIp: '192.168.1.23', userAgent: UAS.chrome }; { at: 0, account: 'guichumo', ok: false },
logs.push(rec( { at: 97, account: 'guichumo', ok: false },
new Date(b2 + pair[0] * 1000).toISOString(), { at: 180, account: 'guichumo', ok: true }
pair[1] === 200 ? 'guichumo' : '未知用户', ].forEach(function (step) {
'POST', '/login', pair[1], ctx.remoteIp, ctx.userAgent add(make({
)); username: 'guichumo',
method: 'POST',
path: '/login',
statusCode: 302,
location: step.ok ? '/uc' : '/login?error=bad-credentials&method=form',
attemptedUsername: step.account,
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(retryBase + step.at * 1000).toISOString()
}));
}); });
add(make({
username: 'guichumo',
method: 'POST',
path: '/login',
statusCode: 302,
location: '/challenges/two-factor/totp',
attemptedUsername: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(now - 9 * DAY - 8 * 3600 * 1000).toISOString()
}));
add(make({
username: 'guichumo',
method: 'POST',
path: '/logout',
statusCode: 302,
location: '/login?logout',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(now - 4 * DAY - 11 * 3600 * 1000).toISOString()
}));
// 升级前落库的登出确认页访问(GET,旧版本记成「登出」,现展示为「访问登出页」)
var legacyLogoutPage = make({
username: 'guichumo',
method: 'GET',
path: '/logout',
statusCode: 200,
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(now - 4 * DAY - 11 * 3600 * 1000 - 2000).toISOString()
});
legacyLogoutPage.action = 'logout';
add(legacyLogoutPage);
// 3. 越权尝试:8 天前 editor.zhang 尝试修改系统设置被拒绝 // ---- 故事线 4:定时发布(系统内部变更:无 IP/UA,执行者「系统」) ----
logs.push(rec( add(AuditCore.buildSystemRecord({
new Date(now - 8 * DAY - 3600 * 1000 * 14).toISOString(), 'editor.zhang', id: 'auditlog-system-0001',
'PUT', '/apis/v1alpha1/configmaps/system', 403, '116.24.65.201', UAS.edge timestamp: new Date(now - DAY - 5 * 3600 * 1000).toISOString(),
)); method: 'PUT',
resourceType: 'posts',
resourceName: 'weekly-2026-w46',
path: '/apis/content.halo.run/v1alpha1/posts/weekly-2026-w46',
changes: [
{ field: 'spec.publish', changeType: 'UPDATED', oldValue: 'false', newValue: 'true' },
{ field: 'spec.publishTime', changeType: 'ADDED', oldValue: null, newValue: '2026-11-21T02:00:00Z' }
]
}));
add(AuditCore.buildSystemRecord({
id: 'auditlog-system-0002',
timestamp: new Date(now - 3 * DAY - 4 * 3600 * 1000).toISOString(),
method: 'DELETE',
resourceType: 'posts',
resourceName: 'draft-night-notes',
path: '/apis/content.halo.run/v1alpha1/posts/draft-night-notes',
changes: [
{ field: 'spec.title', changeType: 'REMOVED', oldValue: '夜间随笔(未发布)', newValue: null },
{ field: 'metadata.name', changeType: 'REMOVED', oldValue: 'draft-night-notes', newValue: null }
]
}));
// 4. 权限不足:5 天前 writer.li 尝试删除评论被拒绝 // ---- 故事线 5:插件生命周期(升级 / 停用 / 卸载) ----
logs.push(rec( var search = PLUGINS[0];
new Date(now - 5 * DAY - 3600 * 1000 * 9).toISOString(), 'writer.li', add(make({
'DELETE', '/apis/content.halo.run/v1alpha1/comments/comment-a3f802', 403, '120.79.10.45', UAS.safari username: 'guichumo',
)); remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: pluginPath(search.name) + '/upgrade',
previous: pluginDoc(search, true, search.version.old),
body: pluginDoc(search, true, search.version.next),
timestamp: new Date(now - 7 * DAY - 6 * 3600 * 1000).toISOString()
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: pluginPath(search.name) + '/activation',
previous: pluginDoc(search, true, search.version.next),
body: pluginDoc(search, false, search.version.next),
timestamp: new Date(now - 6 * DAY - 9 * 3600 * 1000).toISOString()
}));
var links = PLUGINS[3];
add(make({
username: 'guichumo',
remoteIp: '116.24.65.187',
userAgent: UAS.edge,
method: 'DELETE',
path: pluginPath(links.name) + '/uninstall',
statusCode: 204,
previous: pluginDoc(links, true, links.version.next),
timestamp: new Date(now - 1 * DAY - 7 * 3600 * 1000).toISOString()
}));
// 5. 资源不存在:3 天前删除一个已不存在的附件 // ---- 故事线 6:越权与异常 ----
logs.push(rec( add(make({
new Date(now - 3 * DAY - 3600 * 1000 * 20).toISOString(), 'guichumo', username: 'editor.zhang',
'DELETE', '/apis/storage.halo.run/v1alpha1/attachments/attachment-dead42', 404, '192.168.1.23', UAS.chrome remoteIp: '116.24.65.201',
)); userAgent: UAS.edge,
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/configmaps/system',
statusCode: 403,
timestamp: new Date(now - 8 * DAY - 14 * 3600 * 1000).toISOString()
}));
add(make({
username: 'writer.li',
remoteIp: '120.79.10.45',
userAgent: UAS.safari,
method: 'DELETE',
path: commentPath('comment-a3f802'),
statusCode: 403,
timestamp: new Date(now - 5 * DAY - 9 * 3600 * 1000).toISOString()
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'DELETE',
path: '/apis/storage.halo.run/v1alpha1/attachments/attachment-dead42',
statusCode: 404,
timestamp: new Date(now - 3 * DAY - 20 * 3600 * 1000).toISOString()
}));
add(make({
username: 'writer.li',
remoteIp: '120.79.10.45',
userAgent: UAS.chrome,
method: 'POST',
path: '/apis/api.content.halo.run/v1alpha1/posts/self-host-guide/publish',
statusCode: 500,
timestamp: new Date(now - 2 * DAY - 6 * 3600 * 1000).toISOString()
}));
// 6. 服务端异常:2 天前发布文章返回 500 // ---- 故事线 7:误操作定位(删除文章,含字段 diff) ----
logs.push(rec( var deleted = { name: 'weekly-2026-w45', title: '每周摘要 · 2026 W45', summary: '站点一周动态。' };
new Date(now - 2 * DAY - 3600 * 1000 * 6).toISOString(), 'writer.li', add(make({
'POST', '/apis/api.content.halo.run/v1alpha1/posts/self-host-guide/publish', 500, '120.79.10.45', UAS.chrome username: 'guichumo',
)); remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'DELETE',
path: postPath(deleted.name),
statusCode: 204,
previous: postDoc(deleted),
timestamp: new Date(now - DAY - 2 * 3600 * 1000).toISOString()
}));
// 7. 误操作定位:1 天前删除了一篇文章 // ---- 排序 + 分配记录标识(最新记录编号最大) ----
logs.push(rec(
new Date(now - DAY - 3600 * 1000 * 2).toISOString(), 'guichumo',
'DELETE', '/apis/content.halo.run/v1alpha1/posts/weekly-2026-w45', 204, '192.168.1.23', UAS.chrome
));
// 排序 + 分配 id(最新记录 id 数字最大)
logs.sort(function (a, b) { logs.sort(function (a, b) {
return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(); return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
}); });
logs.forEach(function (l, idx) { logs.forEach(function (log, idx) {
l.id = 'audit-' + String(logs.length - idx).padStart(4, '0'); if (!log.id || log.id.indexOf('auditlog-system-') !== 0) {
log.id = 'auditlog-' + String(logs.length - idx).padStart(4, '0');
}
}); });
return logs; return logs;
} }
+240 -52
View File
@@ -66,13 +66,24 @@
<div class="page-header"> <div class="page-header">
<div> <div>
<h1>操作审计</h1> <h1>操作审计</h1>
<p class="page-sub">谁 · 在什么时候 · 对什么资源 · 做了什么操作 · 结果如何 <span class="readonly-hint">(只读,不可篡改)</span></p> <p class="page-sub">谁 · 在什么时候 · 对什么资源 · 做了什么操作 · 结果如何 · 改了什么
<span class="readonly-hint">(只读,不可篡改)</span></p>
</div> </div>
<button class="btn btn-outline" id="btn-simulate"> <div class="header-actions">
<button class="btn btn-outline" id="btn-export" title="按当前筛选条件导出全部记录(UTF-8 BOM CSV)">
<svg viewBox="0 0 24 24"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 20h14"/></svg>
导出
</button>
<button class="btn btn-outline" id="btn-refresh" title="按当前筛选重新查询">
<svg viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.6M20 4v4h-4"/></svg>
刷新
</button>
<button class="btn btn-primary" id="btn-simulate">
<svg viewBox="0 0 24 24"><path d="M6 4.5v15l12-7.5z"/></svg> <svg viewBox="0 0 24 24"><path d="M6 4.5v15l12-7.5z"/></svg>
模拟一次操作 模拟一次操作
</button> </button>
</div> </div>
</div>
<div class="tabs" id="tabs"> <div class="tabs" id="tabs">
<button class="tab active" data-tab="logs">审计日志</button> <button class="tab active" data-tab="logs">审计日志</button>
@@ -83,68 +94,101 @@
<b>审计已关闭。</b>当前期间内发生的后台操作不会写入审计日志,重新开启后恢复记录。 <b>审计已关闭。</b>当前期间内发生的后台操作不会写入审计日志,重新开启后恢复记录。
</div> </div>
<!-- 登录失败告警横幅(达到阈值时出现) -->
<div class="banner banner-danger alert-banner" id="alert-banner" hidden>
<div class="alert-banner-body">
<b>登录失败告警已触发。</b>
<span id="alert-banner-text"></span>
</div>
<div class="alert-banner-actions">
<button class="btn-link" id="alert-banner-view">只看失败记录</button>
<button class="icon-btn" id="alert-banner-close" title="关闭">✕</button>
</div>
</div>
<!-- ---- 审计日志 ---- --> <!-- ---- 审计日志 ---- -->
<section id="panel-logs"> <section id="panel-logs">
<div class="filter-bar card"> <div class="card filter-card">
<div class="filter-item"> <div class="filter-grid">
<label for="f-operator">操作者</label> <label class="filter-item">
<select id="f-operator"><option value="">全部</option></select> <span>操作者</span>
</div> <input id="f-operator" type="text" placeholder="用户名,精确匹配" autocomplete="off">
<div class="filter-item"> </label>
<label for="f-type">资源类型</label> <label class="filter-item">
<span>资源类型</span>
<select id="f-type"><option value="">全部</option></select> <select id="f-type"><option value="">全部</option></select>
</div> </label>
<div class="filter-item"> <label class="filter-item">
<label for="f-method">动作</label> <span>动作</span>
<select id="f-method"><option value="">全部</option></select> <select id="f-method">
</div> <option value="">全部</option>
<div class="filter-item"> <option value="POST">POST</option>
<label for="f-result">结果</label> <option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
<option value="PATCH">PATCH</option>
</select>
</label>
<label class="filter-item">
<span>语义动作</span>
<select id="f-action"><option value="">全部</option></select>
</label>
<label class="filter-item">
<span>结果</span>
<select id="f-result"> <select id="f-result">
<option value="">全部</option> <option value="">全部</option>
<option value="success">成功</option> <option value="success">成功</option>
<option value="failure">失败</option> <option value="failure">失败</option>
</select> </select>
</label>
<label class="filter-item">
<span>关键字</span>
<input id="f-keyword" type="search" placeholder="资源名称 / 路径" autocomplete="off">
</label>
<label class="filter-item">
<span>开始时间</span>
<input id="f-start" type="datetime-local">
</label>
<label class="filter-item">
<span>结束时间</span>
<input id="f-end" type="datetime-local">
</label>
<div class="filter-actions">
<button class="btn btn-primary btn-sm" id="btn-apply">查询</button>
<button class="btn btn-outline btn-sm" id="btn-reset">重置</button>
</div> </div>
<div class="filter-item">
<label for="f-time">时间范围</label>
<select id="f-time">
<option value="all">全部时间</option>
<option value="24h">近 24 小时</option>
<option value="7d">近 7 天</option>
<option value="30d">近 30 天</option>
</select>
</div> </div>
<div class="filter-item grow"> <div class="filter-note" id="filter-note" hidden>
<label for="f-keyword">关键字</label> <span id="filter-note-text"></span>
<input id="f-keyword" type="search" placeholder="资源名称 / 路径,如 hello-halo" autocomplete="off"> <button class="btn-link" id="btn-clear">✕ 清除筛选</button>
</div> </div>
<button class="btn-link" id="btn-clear" hidden>✕ 清除筛选</button>
</div> </div>
<div class="card table-card"> <div class="card table-card">
<div class="audit-list-wrap">
<table class="audit-table"> <table class="audit-table">
<thead> <thead>
<tr> <tr>
<th style="width:170px">时间</th> <th style="width:190px">操作者 / 时间</th>
<th style="width:150px">操作者</th> <th style="width:76px">动作</th>
<th style="width:90px">动作</th> <th style="width:300px">资源 / 路径</th>
<th>资源</th> <th style="width:130px">描述</th>
<th style="width:110px">结果</th> <th style="width:84px">结果</th>
<th style="width:140px">来源 IP</th> <th style="width:120px">IP</th>
</tr> </tr>
</thead> </thead>
<tbody id="tbody"></tbody> <tbody id="tbody"></tbody>
</table> </table>
</div>
<div class="pagination"> <div class="pagination">
<span class="pg-info" id="pg-info"></span> <span class="pg-info" id="pg-info"></span>
<span class="pg-right"> <span class="pg-right">
<select id="pg-size" title="每页条数"> <select id="pg-size" title="每页条数">
<option value="10">10 条/页</option> <option value="10">10 条/页</option>
<option value="20">20 条/页</option> <option value="20" selected>20 条/页</option>
<option value="50">50 条/页</option> <option value="50">50 条/页</option>
</select> </select>
<button class="icon-btn" id="pg-prev" title="上一页">‹</button> <button class="icon-btn" id="pg-prev" title="上一页">‹</button>
<span class="pg-page" id="pg-page">1 / 1</span>
<button class="icon-btn" id="pg-next" title="下一页">›</button> <button class="icon-btn" id="pg-next" title="下一页">›</button>
</span> </span>
</div> </div>
@@ -154,34 +198,110 @@
<!-- ---- 插件设置 ---- --> <!-- ---- 插件设置 ---- -->
<section id="panel-settings" hidden> <section id="panel-settings" hidden>
<div class="card settings-card"> <div class="card settings-card">
<div class="card-title">基本设置</div> <div class="card-title">审计设置</div>
<div class="card-sub">对应 settings.yaml 的 audit 分组,Console 自动渲染;演示页保存在内存中。</div>
<div class="setting-row"> <div class="setting-row">
<div class="setting-text"> <div class="setting-text">
<div class="s-name">审计开关</div> <div class="s-name">启用审计</div>
<div class="s-desc">开启后,已登录用户对后台 API(/apis/**)的写操作与登录/登出事件将被记录(对应 settings.yaml,Console 自动渲染)</div> <div class="s-desc">关闭后不再记录新的操作审计日志,已有记录仍可查询</div>
</div> </div>
<label class="switch"> <label class="switch">
<input type="checkbox" id="set-enabled" checked> <input type="checkbox" id="set-enabled" checked>
<span class="slider"></span> <span class="slider"></span>
</label> </label>
</div> </div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">记录字段变更</div>
<div class="s-desc">对成功的新建/修改/删除操作记录字段级新旧值(敏感字段自动脱敏),关闭后仅记录操作元信息</div>
</div>
<label class="switch">
<input type="checkbox" id="set-record-changes" checked>
<span class="slider"></span>
</label>
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">记录系统内部变更</div>
<div class="s-desc">记录定时发布等非页面操作触发的资源变更(执行者记为「系统」),关闭后仅记录页面/API 操作</div>
</div>
<label class="switch">
<input type="checkbox" id="set-record-system" checked>
<span class="slider"></span>
</label>
</div>
<div class="setting-row"> <div class="setting-row">
<div class="setting-text"> <div class="setting-text">
<div class="s-name">保留天数</div> <div class="s-name">保留天数</div>
<div class="s-desc">超过保留期的记录由每日定时任务自动清理,无需人工干预(默认 90 天,最小 7 天)</div> <div class="s-desc">超过保留期的审计记录将在每日自动清理(最小 7 天,默认 90 天)</div>
</div> </div>
<input type="number" id="set-retention" class="input num" min="7" max="365" value="90"> <input type="number" id="set-retention" class="input num" min="7" step="1" value="90">
</div> </div>
<div class="settings-actions"> <div class="settings-actions">
<button class="btn btn-primary" id="btn-save-settings">保存设置</button> <button class="btn btn-primary" id="btn-save-settings">保存设置</button>
<span class="hint">Demo 仅保存在当前页面内存中,刷新后恢复默认</span> <span class="hint">Demo 仅保存在当前页面内存中,刷新后恢复默认</span>
</div> </div>
</div> </div>
<div class="card settings-card">
<div class="card-title">告警通知</div>
<div class="card-sub">独立于审计开关。Webhook 地址凭据只存于 Halo Secret,设置仅保存 Secret 引用;演示页不发起真实网络请求。</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">启用登录失败告警</div>
<div class="s-desc">统计窗口内登录失败达到触发阈值时向 Webhook 地址推送 JSON 告警(默认关闭)</div>
</div>
<label class="switch">
<input type="checkbox" id="set-alert-enabled">
<span class="slider"></span>
</label>
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">Webhook 地址(Secret)</div>
<div class="s-desc">选择或创建存放 Webhook 地址的 Secret(键 <code>webhookUrl</code>)。地址仅在服务端读取,可含 access_token 等凭据</div>
</div>
<input type="text" id="set-alert-secret" class="input secret-input" placeholder="operation-audit-webhook">
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">触发阈值(次)</div>
<div class="s-desc">统计窗口内累计登录失败达到该次数即触发一次告警(默认 5)</div>
</div>
<input type="number" id="set-alert-threshold" class="input num" min="1" step="1" value="5">
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">统计窗口(分钟)</div>
<div class="s-desc">失败次数的累计窗口;告警后窗口重开,登录成功立即清零(默认 5)</div>
</div>
<input type="number" id="set-alert-window" class="input num" min="1" step="1" value="5">
</div>
<div class="settings-actions">
<button class="btn btn-outline" id="btn-test-alert">发送测试告警</button>
<button class="btn btn-outline" id="btn-simulate-alert">模拟 5 次登录失败</button>
<span class="hint">推送 type: "test" 的测试消息,演示页仅预览 JSON 负载</span>
</div>
<pre class="alert-preview" id="alert-test-output" hidden></pre>
</div>
<div class="card settings-card"> <div class="card settings-card">
<div class="card-title">清理预览</div> <div class="card-title">清理预览</div>
<div class="clean-stats" id="clean-stats"></div> <div class="clean-stats" id="clean-stats"></div>
<div class="settings-actions">
<button class="btn btn-outline" id="btn-clean">模拟一次清理</button> <button class="btn btn-outline" id="btn-clean">模拟一次清理</button>
<span class="hint">真实插件由每日定时任务自动执行</span>
</div>
</div> </div>
</section> </section>
</main> </main>
@@ -197,8 +317,18 @@
<span>模拟一次后台操作</span> <span>模拟一次后台操作</span>
<button class="icon-btn" id="modal-close">✕</button> <button class="icon-btn" id="modal-close">✕</button>
</div> </div>
<p class="modal-sub">选择操作者与方法、输入请求路径后发送,Demo 将按技术方案 D1 的捕获规则(<code>/apis/**</code> 写操作 + <code>/login</code>、<code>/logout</code>)判断是否写入审计日志。</p> <p class="modal-sub">
演示页按真实捕获管线逐步判定:<b>捕获规则</b>(<code>/apis/**</code> 写操作、<code>POST /login</code>、<code>POST /logout</code>;
登录/登出页面的 GET 访问不是操作,不记录)
→ <b>资源解析</b> → <b>登录结果</b>(302 重定向是否跳回登录页)→ <b>语义动作标注</b> → <b>字段级 diff</b>。
</p>
<div class="seg-tabs" id="sim-tabs">
<button class="seg-tab active" data-sim-tab="http">页面 / API 操作</button>
<button class="seg-tab" data-sim-tab="system">系统内部变更</button>
</div>
<div id="sim-http-fields">
<div class="field-row"> <div class="field-row">
<div class="field"> <div class="field">
<label for="sim-user">操作者</label> <label for="sim-user">操作者</label>
@@ -214,7 +344,7 @@
<select id="sim-method"> <select id="sim-method">
<option>GET</option> <option>GET</option>
<option>POST</option> <option>POST</option>
<option>PUT</option> <option selected>PUT</option>
<option>DELETE</option> <option>DELETE</option>
<option>PATCH</option> <option>PATCH</option>
</select> </select>
@@ -226,20 +356,14 @@
<input id="sim-path" type="text" placeholder="/apis/content.halo.run/v1alpha1/posts/hello-halo" autocomplete="off" spellcheck="false"> <input id="sim-path" type="text" placeholder="/apis/content.halo.run/v1alpha1/posts/hello-halo" autocomplete="off" spellcheck="false">
</div> </div>
<div class="presets"> <div class="field-row">
<button class="chip" data-preset='{"user":"guichumo","method":"PUT","path":"/apis/content.halo.run/v1alpha1/posts/hello-halo","status":200}'>编辑文章</button>
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/api.content.halo.run/v1alpha1/posts/reading-notes-11/publish","status":200}'>发布文章</button>
<button class="chip" data-preset='{"user":"editor.zhang","method":"POST","path":"/apis/api.halo.run/v1alpha1/comments/comment-8fa2c1/approve","status":200}'>审核评论</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":401}'>登录失败</button>
<button class="chip" data-preset='{"user":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读)</button>
</div>
<div class="field"> <div class="field">
<label for="sim-status">模拟响应</label> <label for="sim-status">响应状态</label>
<select id="sim-status"> <select id="sim-status">
<option value="200">200 成功</option> <option value="200" selected>200 成功</option>
<option value="201">201 创建成功</option> <option value="201">201 创建成功</option>
<option value="204">204 删除成功</option> <option value="204">204 删除成功</option>
<option value="302">302 重定向(登录用)</option>
<option value="400">400 请求错误</option> <option value="400">400 请求错误</option>
<option value="401">401 未认证</option> <option value="401">401 未认证</option>
<option value="403">403 权限不足</option> <option value="403">403 权限不足</option>
@@ -247,6 +371,70 @@
<option value="500">500 服务端异常</option> <option value="500">500 服务端异常</option>
</select> </select>
</div> </div>
<div class="field">
<label for="sim-location">重定向目标(仅 /login)</label>
<input id="sim-location" type="text" placeholder="成功后为 /uc;失败含 error 参数" autocomplete="off">
</div>
</div>
<div class="field-row">
<div class="field">
<label for="sim-attempted">尝试的用户名(登录请求)</label>
<input id="sim-attempted" type="text" placeholder="如 admin,可留空" autocomplete="off">
</div>
<div class="field">
<label for="sim-prev">写入前资源(JSON,可选)</label>
<input id="sim-prev-note" type="text" value="由内置快照自动提供" disabled>
</div>
</div>
<div class="field">
<label for="sim-body">请求体 JSON(可选,用于字段 diff;敏感字段自动脱敏)</label>
<textarea id="sim-body" rows="4" spellcheck="false" placeholder='{"apiVersion":"content.halo.run/v1alpha1","kind":"Post","metadata":{"name":"hello-halo"},"spec":{"title":"新标题"}}'></textarea>
</div>
<div class="presets">
<button class="chip" data-preset='{"user":"editor.zhang","method":"PUT","path":"/apis/content.halo.run/v1alpha1/posts/hello-halo","status":200,"snapshot":"post","body":{"apiVersion":"content.halo.run/v1alpha1","kind":"Post","metadata":{"name":"hello-halo","labels":{"content.halo.run/pinned":"false"}},"spec":{"title":"你好,Halo(Demo 修改)","slug":"hello-halo","visible":"PUBLIC","publish":true,"pinned":false,"allowComment":true,"summary":"从零开始搭建自己的写作空间。"}}}'>编辑文章(含 diff)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/api.content.halo.run/v1alpha1/posts/reading-notes-11/publish","status":200}'>发布文章</button>
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/plugin.halo.run/v1alpha1/plugins/plugin-search-widget/upgrade","status":200,"snapshot":"plugin","body":{"apiVersion":"plugin.halo.run/v1alpha1","kind":"Plugin","metadata":{"name":"plugin-search-widget"},"spec":{"displayName":"搜索组件","version":"1.4.0","enabled":true,"requires":">=2.20.0"}}}'>升级插件(含 diff)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"PUT","path":"/apis/api.console.halo.run/v1alpha1/users/guichumo/password","status":200,"body":{"apiVersion":"v1alpha1","kind":"User","metadata":{"name":"guichumo"},"spec":{"displayName":"guichumo","email":"guichumo@example.com","roles":["role-template-author"],"password":"runtime-demo-value"}}}'>修改密码(脱敏)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"GET","path":"/login?authentication_required","status":200}'>打开登录页(GET,不记录)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":302,"location":"/login?error=invalid-credential&method=form","attempted":"admin"}'>登录失败(表单 302)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":302,"location":"/uc","attempted":"guichumo"}'>登录成功(302 → /uc)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读,不记录)</button>
</div>
</div>
<div id="sim-system-fields" hidden>
<div class="field-row">
<div class="field">
<label for="sys-method">事件类型</label>
<select id="sys-method">
<option value="PUT">更新(PUT 语义)</option>
<option value="DELETE">删除(DELETE 语义)</option>
</select>
</div>
<div class="field">
<label for="sys-type">资源类型</label>
<select id="sys-type"></select>
</div>
</div>
<div class="field">
<label for="sys-name">资源名称</label>
<input id="sys-name" type="text" value="weekly-2026-w46" autocomplete="off">
</div>
<div class="field">
<label for="sys-changes">字段变更(JSON 数组)</label>
<textarea id="sys-changes" rows="4" spellcheck="false">[
{"field":"spec.publish","changeType":"UPDATED","oldValue":"false","newValue":"true"},
{"field":"spec.publishTime","changeType":"ADDED","oldValue":null,"newValue":"2026-11-22T02:00:00Z"}
]</textarea>
</div>
<div class="presets">
<button class="chip" data-sys-preset='{"method":"PUT","type":"posts","name":"weekly-2026-w46","changes":[{"field":"spec.publish","changeType":"UPDATED","oldValue":"false","newValue":"true"},{"field":"spec.publishTime","changeType":"ADDED","oldValue":null,"newValue":"2026-11-22T02:00:00Z"}]}'>定时发布文章</button>
<button class="chip" data-sys-preset='{"method":"DELETE","type":"posts","name":"draft-night-notes","changes":[{"field":"spec.title","changeType":"REMOVED","oldValue":"夜间随笔(未发布)","newValue":null}]}'>清理未发布草稿</button>
</div>
</div>
<div class="modal-actions"> <div class="modal-actions">
<button class="btn btn-outline" id="sim-cancel">取消</button> <button class="btn btn-outline" id="sim-cancel">取消</button>
+703 -137
View File
@@ -2,199 +2,703 @@
* 操作审计 Demo · 核心逻辑单元测试 * 操作审计 Demo · 核心逻辑单元测试
* *
* 运行:node --test demo/test/audit-core.test.mjs * 运行:node --test demo/test/audit-core.test.mjs
* 覆盖对象(与技术方案第 7 节测试策略对应): * 覆盖对象(与插件当前实现一一对应):
* - shouldCapture 捕获规则(D1) * - shouldCapture 捕获规则(CaptureRule / 认证端点链首捕获)
* - resolveResource 资源解析(5.2) * - resolveResource 资源解析(ResourceResolver)
* - applyFilters 筛选(产品设计 4.2) * - deriveAction 语义动作标注 + describeOperation 中文描述
* - paginate 分页 * - classifyLogin 登录结果判定(LoginOutcome:302 重定向目标判定)
* - countExpired 保留期清理(D5) * - diffObjects 字段级变更 diff(PUT/PATCH/POST/DELETE、脱敏、截断、封顶)
* - MockData 模拟数据生成器(确定性、字段完整性) * - applyFilters 八维筛选(含登录失败结果语义)
* - toCsv CSV 导出(BOM/CRLF/转义/公式注入防护)
* - 告警窗口 登录失败告警(阈值、告警后重开、成功清零)
* - MockData 模拟数据(确定性、字段完整性、故事线)
*/ */
import { createRequire } from 'node:module'; import { createRequire } from 'node:module';
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
const AuditCore = require('../assets/audit-core.js'); const C = require('../assets/audit-core.js');
const MockData = require('../assets/mock-data.js'); const MockData = require('../assets/mock-data.js');
// ---------------- shouldCapture(D1 捕获规则) ---------------- // ---------------- shouldCapture(捕获规则) ----------------
test('shouldCapture: 已登录用户对 /apis/** 的写操作应记录', () => { test('shouldCapture: 已登录用户对 /apis/** 的写操作应记录(http 通道)', () => {
assert.deepEqual( for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) {
AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true }), const r = C.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
{ captured: true, reason: '已登录用户对 /apis/** 的写操作,予以记录' } assert.equal(r.captured, true, method);
); assert.equal(r.channel, 'http');
assert.equal(AuditCore.shouldCapture({ method: 'put', path: '/apis/v1alpha1/configmaps/system', authenticated: true }).captured, true); assert.match(r.reason, /写操作/);
assert.equal(AuditCore.shouldCapture({ method: 'DELETE', path: '/apis/content.halo.run/v1alpha1/posts/x', authenticated: true }).captured, true); }
assert.equal(AuditCore.shouldCapture({ method: 'PATCH', path: '/apis/v1alpha1/users/x', authenticated: true }).captured, true);
}); });
test('shouldCapture: 读操作不记录', () => { test('shouldCapture: 读操作不记录', () => {
for (const method of ['GET', 'HEAD', 'OPTIONS']) { for (const method of ['GET', 'HEAD', 'OPTIONS']) {
const r = AuditCore.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true }); const r = C.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
assert.equal(r.captured, false, method + ' 不应被记录'); assert.equal(r.captured, false, method);
assert.match(r.reason, /写操作/); assert.match(r.reason, /写操作/);
} }
}); });
test('shouldCapture: /apis/** 下匿名请求不记录(401/403 场景)', () => { test('shouldCapture: /apis/** 下匿名请求不记录(401/403 场景)', () => {
const r = AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: false }); const r = C.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: false });
assert.equal(r.captured, false); assert.equal(r.captured, false);
assert.match(r.reason, /匿名/); assert.match(r.reason, /匿名/);
}); });
test('shouldCapture: 登录/登出端点始终记录(含匿名登录尝试)', () => { test('shouldCapture: 认证操作 POST /login、POST /logout 始终记录(含匿名登录尝试)', () => {
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/login', authenticated: false }).captured, true); assert.deepEqual(
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).captured, true); C.shouldCapture({ method: 'POST', path: '/login', authenticated: false }),
{
captured: true,
channel: 'auth',
reason: '认证操作始终记录(POST /login 登录尝试、POST /logout 登出,含登录失败)'
}
);
assert.equal(C.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).channel, 'auth');
});
test('shouldCapture: 登录/登出页面的 GET 访问不是操作,不记录', () => {
// 打开登录页、被弹回登录页、失败回显、登出确认页都只是渲染页面(HTTP 200);
// 原先一律落库成「未知用户 · 登录 · 200」,在列表里与登录成功无法区分
for (const path of ['/login', '/login?authentication_required', '/login?error=invalid-credential', '/logout']) {
const r = C.shouldCapture({ method: 'GET', path, authenticated: false });
assert.equal(r.captured, false, path);
assert.equal(r.channel, 'none', path);
assert.match(r.reason, /GET 访问不是操作/, path);
}
}); });
test('shouldCapture: /apis/** 之外的普通路径不记录', () => { test('shouldCapture: /apis/** 之外的普通路径不记录', () => {
const r = AuditCore.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true }); const r = C.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true });
assert.equal(r.captured, false); assert.equal(r.captured, false);
assert.match(r.reason, /捕获范围/); assert.match(r.reason, /捕获范围/);
}); });
test('shouldCapture: 路径匹配 /apis/ 前缀但匿名时,匿名规则优先于方法规则(与 D1 描述一致)', () => { test('shouldCapture: 匿名规则优先于读操作规则(与后端一致)', () => {
// GET + 匿名:期望原因是"匿名",而非"读操作" const r = C.shouldCapture({ method: 'GET', path: '/apis/v1alpha1/posts', authenticated: false });
const r = AuditCore.shouldCapture({ method: 'GET', path: '/apis/v1alpha1/posts', authenticated: false });
assert.equal(r.captured, false); assert.equal(r.captured, false);
assert.match(r.reason, /匿名/); assert.match(r.reason, /匿名/);
}); });
// ---------------- resolveResource(5.2 资源解析) ---------------- // ---------------- resolveResource(资源解析) ----------------
test('resolveResource: 单资源路径 → plural + name', () => { test('resolveResource: 单资源 / 集合 / 深层子资源', () => {
assert.deepEqual( assert.deepEqual(
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz'), C.resolveResource('/apis/content.halo.run/v1alpha1/posts/xyz'),
{ resourceType: 'posts', resourceName: 'xyz' } { resourceType: 'posts', resourceName: 'xyz' }
); );
});
test('resolveResource: 集合路径 → 仅 plural', () => {
assert.deepEqual( assert.deepEqual(
AuditCore.resolveResource('/apis/content.halo.run/v1alpha1/posts'), C.resolveResource('/apis/content.halo.run/v1alpha1/posts'),
{ resourceType: 'posts', resourceName: '' } { resourceType: 'posts', resourceName: null }
); );
});
test('resolveResource: 更深层子资源取前两段,完整路径由 path 兜底', () => {
assert.deepEqual( assert.deepEqual(
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'), C.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'),
{ resourceType: 'posts', resourceName: 'xyz' } { resourceType: 'posts', resourceName: 'xyz' }
); );
assert.deepEqual(
C.resolveResource('/apis/plugin.halo.run/v1alpha1/plugins/plugin-search-widget/upgrade'),
{ resourceType: 'plugins', resourceName: 'plugin-search-widget' }
);
}); });
test('resolveResource: /login、/logout → auth', () => { test('resolveResource: 查询串不影响解析(/login?error=... → auth)', () => {
assert.deepEqual(AuditCore.resolveResource('/login'), { resourceType: 'auth', resourceName: '' }); assert.deepEqual(
assert.deepEqual(AuditCore.resolveResource('/logout'), { resourceType: 'auth', resourceName: '' }); C.resolveResource('/login?error=invalid-credential&method=form'),
{ resourceType: 'auth', resourceName: null }
);
assert.deepEqual(C.resolveResource('/logout'), { resourceType: 'auth', resourceName: null });
}); });
test('resolveResource: 非 /apis 路径与畸形路径 → other', () => { test('resolveResource: 非 /apis 路径与畸形路径 → other', () => {
assert.equal(AuditCore.resolveResource('/console').resourceType, 'other'); assert.equal(C.resolveResource('/console').resourceType, 'other');
assert.equal(AuditCore.resolveResource('/apis/only-group').resourceType, 'other'); assert.equal(C.resolveResource('/apis/only-group').resourceType, 'other');
assert.equal(C.resolveResource('').resourceType, 'other');
}); });
// ---------------- isSuccess / applyFilters(4.2 筛选) ---------------- // ---------------- deriveAction / describeOperation ----------------
test('deriveAction: 登录/登出按方法区分,失败回显由 error 参数识别', () => {
assert.equal(C.deriveAction('POST', 'auth', '/login'), 'login');
assert.equal(C.deriveAction('POST', 'auth', '/login?continue=/uc'), 'login');
assert.equal(C.deriveAction('POST', 'auth', '/logout'), 'logout');
// GET 是页面访问(打开登录页、被弹回登录页、登出确认页)
assert.equal(C.deriveAction('GET', 'auth', '/login'), 'login-page');
assert.equal(C.deriveAction('GET', 'auth', '/login?authentication_required'), 'login-page');
assert.equal(C.deriveAction('GET', 'auth', '/logout'), 'logout-page');
// 升级前落库的失败回显(GET /login?error=...)无标注时现场推导
assert.equal(C.deriveAction('GET', 'auth', '/login?error=invalid-credential'), 'login-failure');
assert.equal(C.deriveAction('GET', 'auth', '/login?errors=1'), 'login-page');
});
test('deriveAction: 子动作段优先于 HTTP 方法', () => {
assert.equal(C.deriveAction('PUT', 'posts', '/apis/api.content.halo.run/v1alpha1/posts/x/publish'), 'publish');
assert.equal(C.deriveAction('PUT', 'posts', '/apis/content.halo.run/v1alpha1/posts/x/restore'), 'restore');
assert.equal(C.deriveAction('DELETE', 'comments', '/apis/content.halo.run/v1alpha1/comments/x/recycle'), 'recycle');
assert.equal(C.deriveAction('POST', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/activation'), 'enable');
assert.equal(C.deriveAction('PUT', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/upgrade'), 'upgrade');
assert.equal(C.deriveAction('DELETE', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/uninstall'), 'uninstall');
assert.equal(C.deriveAction('POST', 'users', '/apis/api.console.halo.run/v1alpha1/users/x/resetpassword'), 'resetpassword');
});
test('deriveAction: 未识别子动作回退 method 映射,未知方法返回 null', () => {
assert.equal(C.deriveAction('POST', 'posts', '/apis/content.halo.run/v1alpha1/posts/x/unknown'), 'create');
assert.equal(C.deriveAction('GET', 'posts', '/apis/content.halo.run/v1alpha1/posts'), 'view');
assert.equal(C.deriveAction('TRACE', 'posts', '/apis/content.halo.run/v1alpha1/posts'), null);
});
test('describeOperation: 语义动作 → 中文短语(列表/详情/导出共用)', () => {
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login' }), '登录');
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login?error=x', action: 'login-failure' }), '登录失败');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'posts', path: '/apis/api.content.halo.run/v1alpha1/posts/x/publish', action: 'publish' }), '发布文章');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'plugins', path: '/apis/plugin.halo.run/v1alpha1/plugins/x/activation', action: 'enable' }), '启用插件');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'themes', path: '/apis/theme.halo.run/v1alpha1/themes/x/activation', action: 'enable' }), '启用主题');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'users', path: '/apis/v1alpha1/users/x/password', action: 'password' }), '修改密码');
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'comments', path: '/apis/x/v1alpha1/comments/x/reply', action: 'reply' }), '回复评论');
});
test('describeOperation: 历史记录无 action 时现场推导;未识别回退 method 动词', () => {
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'posts', path: '/apis/content.halo.run/v1alpha1/posts/x' }), '修改文章');
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'unknowns', path: '/apis/x/v1alpha1/unknowns' }), '新建unknowns');
});
test('describeOperation: 升级前落库的登录页访问记录(GET + login 标注)纠正为页面访问', () => {
// 旧版本把登录页的 GET 访问记成「未知用户 · 登录 · 200」,看起来像登录成功
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login?authentication_required', action: 'login' }), '访问登录页');
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login', action: 'login' }), '访问登录页');
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login' }), '访问登录页');
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/logout', action: 'logout' }), '访问登出页');
// POST 才是登录/登出操作,落库标注照常生效
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login' }), '登录');
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'auth', path: '/logout', action: 'logout' }), '登出');
});
// ---------------- classifyLogin(登录结果判定) ----------------
test('classifyLogin: POST /login 的 2xx/302/401 判定', () => {
assert.deepEqual(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 200 }), { attempt: true, failure: false });
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/uc' }).failure, false);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/challenges/two-factor/totp' }).failure, false);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?error=invalid-credential&method=form' }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?error&method=form' }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?error=rate-limit-exceeded&method=form' }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 401 }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 403 }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: null }).failure, true);
});
test('classifyLogin: 只有响应明确确认才算成功——跳回登录页或缺失 Location 均判失败', () => {
// 不依赖 error 参数:宿主换了失败重定向格式也不会把失败记成成功
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login' }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?authentication_required' }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302 }).failure, true, '缺失 Location 无法确认成功');
// 含 error 字样的其他参数、路径前缀相同都不算跳回登录页
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/uc?errors=1' }).failure, false);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login-callback' }).failure, false);
});
test('classifyLogin: 登录页 GET 与登出不是登录尝试', () => {
for (const input of [
{ method: 'GET', path: '/login', statusCode: 200 },
{ method: 'GET', path: '/login?error=invalid-credential', statusCode: 200 },
{ method: 'GET', path: '/login?authentication_required', statusCode: 200 },
{ method: 'POST', path: '/logout', statusCode: 302 }
]) {
assert.deepEqual(C.classifyLogin(input), { attempt: false, failure: false }, JSON.stringify(input));
}
});
// ---------------- 结果徽标 / 登录失败标注 ----------------
test('resultBadge: 登录失败即使 200/302 也显示「失败」,登录成功显示「成功」', () => {
assert.deepEqual(
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login-failure', statusCode: 302 }),
{ text: '失败', class: 'status-fail' }
);
// 升级前落库的失败回显页(GET,HTTP 200)
assert.deepEqual(
C.resultBadge({ method: 'GET', resourceType: 'auth', path: '/login?error=x', action: 'login-failure', statusCode: 200 }),
{ text: '失败', class: 'status-fail' }
);
// 表单登录成功同样是 302:裸状态码读不出成败,写「成功」与「失败」对称
assert.deepEqual(
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login', statusCode: 302 }),
{ text: '成功', class: 'status-ok' }
);
// 其余记录保持数字状态码徽标
assert.deepEqual(
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/logout', action: 'logout', statusCode: 302 }),
{ text: '302', class: 'status-ok' }
);
assert.deepEqual(
C.resultBadge({ method: 'DELETE', resourceType: 'posts', path: '/apis/x/v1alpha1/posts/x', action: 'delete', statusCode: 403 }),
{ text: '403', class: 'status-fail' }
);
});
test('resultBadge / resultOutcome: 登录页访问记录显示灰色「—」,既不算成功也不算失败', () => {
// 升级前落库的 GET /login(HTTP 200、带 login 标注)原先显示绿色「200」,
// 看起来像未知用户登录成功
const visit = { method: 'GET', resourceType: 'auth', path: '/login?authentication_required', action: 'login', statusCode: 200 };
assert.equal(C.isAuthPageVisit(visit), true);
assert.equal(C.isLoginFailure(visit), false);
assert.deepEqual(C.resultBadge(visit), { text: '—', class: 'status-na' });
assert.equal(C.resultOutcome(visit), 'page-visit');
assert.equal(C.isSuccessRecord(visit), false);
assert.equal(C.isFailureRecord(visit), false);
assert.equal(C.resultOutcome({ method: 'GET', resourceType: 'auth', path: '/logout', action: 'logout', statusCode: 200 }), 'page-visit');
// 无标注的历史记录、页面自身出错(5xx)同样不计成败
assert.equal(C.resultOutcome({ method: 'GET', resourceType: 'auth', path: '/login', statusCode: 500 }), 'page-visit');
// POST 是认证操作
assert.equal(C.isAuthPageVisit({ method: 'POST', resourceType: 'auth', path: '/login' }), false);
assert.equal(C.isAuthPageVisit({ method: 'GET', resourceType: 'posts', path: '/apis/x/v1alpha1/login' }), false);
});
test('isLoginFailure / isSuccessRecord: 兼容历史记录(无 action 时按路径推导)', () => {
assert.equal(C.isLoginFailure({ method: 'GET', resourceType: 'auth', path: '/login?error=x', statusCode: 200 }), true);
assert.equal(C.isLoginFailure({ method: 'POST', resourceType: 'auth', path: '/login', statusCode: 302 }), false);
assert.equal(C.isSuccessRecord({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login-failure', statusCode: 200 }), false);
assert.equal(C.isSuccessRecord({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login', statusCode: 302 }), true);
assert.equal(C.isFailureRecord({ method: 'POST', resourceType: 'posts', path: '/apis/x/v1alpha1/posts', statusCode: 403 }), true);
});
test('displayUsername: unknown → 未知用户,system → 系统', () => {
assert.equal(C.displayUsername('unknown'), '未知用户');
assert.equal(C.displayUsername('system'), '系统');
assert.equal(C.displayUsername(''), '未知用户');
assert.equal(C.displayUsername('guichumo'), 'guichumo');
});
// ---------------- diffObjects(字段级变更) ----------------
test('diffObjects: POST 全量新增,跳过 apiVersion/kind/status,metadata 仅保留可写键', () => {
const changes = C.diffObjects('POST', null, {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Post',
metadata: { name: 'hello', version: 3, labels: { a: 'b' }, annotations: { c: 'd' } },
spec: { title: '标题', publish: false },
status: { phase: 'DRAFT' }
});
const fields = changes.map(c => c.field);
assert.ok(fields.includes('metadata.name'));
assert.ok(fields.includes('metadata.labels.a'));
assert.ok(!fields.includes('apiVersion'));
assert.ok(!fields.includes('kind'));
assert.ok(!fields.includes('status.phase'));
assert.ok(!fields.some(f => f.includes('metadata.version')));
assert.ok(changes.every(c => c.changeType === 'ADDED'));
});
test('diffObjects: PUT 计算新增/修改/删除', () => {
const changes = C.diffObjects('PUT',
{ apiVersion: 'v1', kind: 'K', metadata: { name: 'x' }, spec: { title: '旧', cover: 'a.png', pinned: false } },
{ apiVersion: 'v1', kind: 'K', metadata: { name: 'x' }, spec: { title: '新', pinned: false, summary: '新增' } }
);
const byField = Object.fromEntries(changes.map(c => [c.field, c]));
assert.equal(byField['spec.title'].changeType, 'UPDATED');
assert.equal(byField['spec.title'].oldValue, '旧');
assert.equal(byField['spec.title'].newValue, '新');
assert.equal(byField['spec.cover'].changeType, 'REMOVED');
assert.equal(byField['spec.summary'].changeType, 'ADDED');
assert.equal(byField['spec.summary'].oldValue, null);
});
test('diffObjects: DELETE 全量移除', () => {
const changes = C.diffObjects('DELETE', {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Post',
metadata: { name: 'weekly' },
spec: { title: '每周摘要' },
status: { phase: 'PUBLISHED' }
}, null);
assert.ok(changes.length > 0);
assert.ok(changes.every(c => c.changeType === 'REMOVED'));
assert.ok(changes.some(c => c.field === 'spec.title' && c.oldValue === '每周摘要'));
assert.ok(!changes.some(c => c.field.startsWith('status')));
});
test('diffObjects: PATCH Merge Patch 仅比较 body 中字段,显式 null 视为删除', () => {
const changes = C.diffObjects('PATCH',
{ metadata: { name: 'x' }, spec: { title: '旧', summary: '保留', cover: 'a.png' } },
{ spec: { title: '新', cover: null } }
);
const fields = changes.map(c => c.field);
assert.deepEqual(fields, ['spec.title', 'spec.cover']);
const cover = changes.find(c => c.field === 'spec.cover');
assert.equal(cover.changeType, 'REMOVED');
assert.ok(!fields.includes('spec.summary'), 'body 未携带的字段视为未变更');
});
test('diffObjects: PATCH JSON Patch(RFC 6902)', () => {
const changes = C.diffObjects('PATCH',
{ metadata: { name: 'x' }, spec: { title: '旧', cover: 'a.png' } },
[
{ op: 'replace', path: '/spec/title', value: '新' },
{ op: 'remove', path: '/spec/cover' },
{ op: 'add', path: '/spec/summary', value: '摘要' }
]
);
const byField = Object.fromEntries(changes.map(c => [c.field, c]));
assert.equal(byField['spec.title'].changeType, 'UPDATED');
assert.equal(byField['spec.cover'].changeType, 'REMOVED');
assert.equal(byField['spec.summary'].changeType, 'ADDED');
});
test('diffObjects: 敏感字段脱敏(password / token / secret / credential)', () => {
const changes = C.diffObjects('POST', null, {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'alice' },
spec: { displayName: 'Alice', password: 'plain-text-value' },
annotations: { 'x-token': 'token-value' }
});
const password = changes.find(c => c.field === 'spec.password');
const displayName = changes.find(c => c.field === 'spec.displayName');
assert.equal(password.newValue, '******');
assert.equal(displayName.newValue, 'Alice');
const updated = C.diffObjects('PUT',
{ spec: { password: 'old-value' } },
{ spec: { password: 'new-value' } }
);
assert.equal(updated[0].oldValue, '******');
assert.equal(updated[0].newValue, '******');
assert.equal(C.isSensitiveField('metadata.annotations.x-credential'), true);
assert.equal(C.isSensitiveField('spec.title'), false);
});
test('diffObjects: 超长值截断、变更条数封顶 30 + 汇总条', () => {
const long = 'x'.repeat(260);
const changes = C.diffObjects('PUT', { spec: { text: 'old' } }, { spec: { text: long } });
assert.ok(changes[0].newValue.endsWith('…(截断)'));
assert.ok(changes[0].newValue.length <= 210);
const before = { spec: {} };
const after = { spec: {} };
for (let i = 0; i < 40; i++) {
before.spec['k' + i] = 'a';
after.spec['k' + i] = 'b';
}
const capped = C.diffObjects('PUT', before, after);
assert.equal(capped.length, 31);
assert.equal(capped[30].field, '…');
assert.match(capped[30].newValue, /仅记录前 30 处(共 40 处)/);
});
test('diffObjects: 无变更 / 无法计算返回 null', () => {
assert.equal(C.diffObjects('PUT', { spec: { a: 1 } }, { spec: { a: 1 } }), null);
assert.equal(C.diffObjects('POST', null, null), null);
assert.equal(C.diffObjects('PUT', null, { spec: {} }), null);
assert.equal(C.diffObjects('GET', { a: 1 }, { a: 2 }), null);
});
test('formatChanges: 紧凑中文摘要供 CSV「变更」列使用', () => {
const text = C.formatChanges([
{ field: 'spec.title', changeType: 'UPDATED', oldValue: '旧', newValue: '新' },
{ field: 'spec.cover', changeType: 'ADDED', oldValue: null, newValue: 'a.png' },
{ field: 'spec.slug', changeType: 'REMOVED', oldValue: 'old', newValue: null }
]);
assert.equal(text, '修改 spec.title:旧 → 新;新增 spec.cover:a.png;删除 spec.slug:old');
assert.equal(C.formatChanges(null), '');
assert.equal(C.changeTypeLabel('ADDED'), '新增');
assert.equal(C.changeValueDisplay(null), '∅');
});
// ---------------- buildRecord / buildSystemRecord ----------------
test('buildRecord: HTTP 写操作推导资源、语义动作与操作者', () => {
const record = C.buildRecord({
method: 'put',
path: '/apis/api.content.halo.run/v1alpha1/posts/x/publish',
username: 'editor.zhang',
statusCode: 200,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(record.username, 'editor.zhang');
assert.equal(record.method, 'PUT');
assert.equal(record.action, 'publish');
assert.equal(record.resourceType, 'posts');
assert.equal(record.resourceName, 'x');
assert.equal(C.describeOperation(record), '发布文章');
assert.equal(record.changes, null, '未提供请求体时不计算 diff');
});
test('buildRecord: 登录请求操作者记「未知用户」,失败标注 login-failure', () => {
const failure = C.buildRecord({
method: 'POST',
path: '/login',
username: 'guichumo',
statusCode: 302,
location: '/login?error=invalid-credential&method=form',
attemptedUsername: 'admin',
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(failure.username, 'unknown');
assert.equal(failure.attemptedUsername, 'admin');
assert.equal(failure.action, 'login-failure');
assert.equal(C.resultBadge(failure).text, '失败');
const success = C.buildRecord({
method: 'POST',
path: '/login',
statusCode: 302,
location: '/uc',
attemptedUsername: 'guichumo',
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(success.action, 'login');
assert.equal(C.resultBadge(success).text, '成功');
assert.equal(C.resultBadge(failure).text, '失败');
});
test('buildRecord: 仅 2xx 且 recordChanges 开启时计算 diff', () => {
const body = { spec: { title: '新' } };
const previous = { spec: { title: '旧' } };
const ok = C.buildRecord({
method: 'PUT',
path: '/apis/content.halo.run/v1alpha1/posts/x',
username: 'guichumo',
statusCode: 200,
previous,
body,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(ok.changes.length, 1);
const failed = C.buildRecord({
method: 'PUT',
path: '/apis/content.halo.run/v1alpha1/posts/x',
username: 'guichumo',
statusCode: 403,
previous,
body,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(failed.changes, null);
const disabled = C.buildRecord({
method: 'PUT',
path: '/apis/content.halo.run/v1alpha1/posts/x',
username: 'guichumo',
statusCode: 200,
previous,
body,
recordChanges: false,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(disabled.changes, null);
});
test('buildSystemRecord: 执行者 system、无 IP/UA、状态恒 200', () => {
const record = C.buildSystemRecord({
method: 'PUT',
resourceType: 'posts',
resourceName: 'weekly',
path: '/apis/content.halo.run/v1alpha1/posts/weekly',
changes: [{ field: 'spec.publish', changeType: 'UPDATED', oldValue: 'false', newValue: 'true' }],
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(record.username, 'system');
assert.equal(C.displayUsername(record.username), '系统');
assert.equal(record.statusCode, 200);
assert.equal(record.remoteIp, null);
assert.equal(record.userAgent, null);
assert.equal(record.action, 'update');
assert.equal(C.describeOperation(record), '修改文章');
assert.equal(record.changes.length, 1);
});
test('toWire: 扁平记录 → AuditLog Extension JSON', () => {
const record = C.buildRecord({
method: 'POST',
path: '/apis/content.halo.run/v1alpha1/posts',
username: 'guichumo',
statusCode: 201,
body: { spec: { title: '新文章' } },
timestamp: '2026-11-21T10:00:00Z'
});
record.id = 'auditlog-0001';
const wire = C.toWire(record);
assert.equal(wire.apiVersion, 'audit.guichumo.com/v1alpha1');
assert.equal(wire.kind, 'AuditLog');
assert.equal(wire.metadata.name, 'auditlog-0001');
assert.equal(wire.metadata.creationTimestamp, '2026-11-21T10:00:00Z');
assert.equal(wire.spec.method, 'POST');
assert.equal(wire.spec.action, 'create');
assert.ok(Array.isArray(wire.spec.changes));
});
// ---------------- applyFilters(八维筛选) ----------------
const NOW = new Date('2026-11-21T12:00:00Z').getTime(); const NOW = new Date('2026-11-21T12:00:00Z').getTime();
function fixture() { function fixture() {
return [ return [
{ id: 'a1', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/content.halo.run/v1alpha1/posts/hello', resourceType: 'posts', resourceName: 'hello', statusCode: 200 }, { id: 'a1', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/content.halo.run/v1alpha1/posts/hello', resourceType: 'posts', resourceName: 'hello', statusCode: 200, action: 'update' },
{ id: 'a2', timestamp: '2026-11-21T09:00:00Z', username: 'editor.zhang', method: 'POST', path: '/apis/api.content.halo.run/v1alpha1/posts/hello/publish', resourceType: 'posts', resourceName: 'hello', statusCode: 500 }, { id: 'a2', timestamp: '2026-11-21T09:00:00Z', username: 'editor.zhang', method: 'POST', path: '/apis/api.content.halo.run/v1alpha1/posts/hello/publish', resourceType: 'posts', resourceName: 'hello', statusCode: 500, action: 'publish' },
{ id: 'a3', timestamp: '2026-11-20T08:00:00Z', username: 'guichumo', method: 'POST', path: '/login', resourceType: 'auth', resourceName: '', statusCode: 401 }, { id: 'a3', timestamp: '2026-11-20T08:00:00Z', username: 'unknown', method: 'GET', path: '/login?error=x', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login-failure' },
{ id: 'a4', timestamp: '2026-11-10T08:00:00Z', username: 'writer.li', method: 'PUT', path: '/apis/v1alpha1/configmaps/system', resourceType: 'configmaps', resourceName: 'system', statusCode: 200 } { id: 'a4', timestamp: '2026-11-21T11:30:00Z', username: 'guichumo', method: 'POST', path: '/login', resourceType: 'auth', resourceName: null, statusCode: 302, action: 'login' },
{ id: 'a5', timestamp: '2026-11-10T08:00:00Z', username: 'writer.li', method: 'PUT', path: '/apis/v1alpha1/configmaps/system', resourceType: 'configmaps', resourceName: 'system', statusCode: 403, action: 'update' },
// 升级前落库的登录页访问记录(GET、HTTP 200,带旧版本的 login 标注)
{ id: 'a6', timestamp: '2026-11-20T07:00:00Z', username: 'unknown', method: 'GET', path: '/login?authentication_required', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login' },
{ id: 'a7', timestamp: '2026-11-09T08:00:00Z', username: 'unknown', method: 'GET', path: '/logout', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'logout' }
]; ];
} }
test('applyFilters: 按操作者筛选', () => { test('applyFilters: 操作者 / 资源类型 / 动作 / 语义动作', () => {
const out = AuditCore.applyFilters(fixture(), { operator: 'guichumo', now: NOW }); assert.deepEqual(C.applyFilters(fixture(), { operator: 'guichumo' }).map(l => l.id), ['a4', 'a1']);
assert.deepEqual(out.map(l => l.id), ['a1', 'a3']); assert.deepEqual(C.applyFilters(fixture(), { resourceType: 'posts' }).map(l => l.id), ['a1', 'a2']);
assert.deepEqual(C.applyFilters(fixture(), { method: 'post' }).map(l => l.id), ['a4', 'a2']);
assert.deepEqual(C.applyFilters(fixture(), { action: 'login-failure' }).map(l => l.id), ['a3']);
}); });
test('applyFilters: 按资源类型筛选', () => { test('applyFilters: 语义动作筛「登录/登出」不混入登录页访问记录(它们展示为「访问登录页/登出页」)', () => {
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', now: NOW }); assert.deepEqual(C.applyFilters(fixture(), { action: 'login' }).map(l => l.id), ['a4']);
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']); assert.deepEqual(C.applyFilters(fixture(), { action: 'logout' }).map(l => l.id), []);
}); });
test('applyFilters: 按动作筛选(方法名大小写不敏感)', () => { test('applyFilters: 结果语义(登录失败 200 计失败;登录成功 302 计成功;页面访问不计成败)', () => {
const post = AuditCore.applyFilters(fixture(), { method: 'POST', now: NOW }); const success = C.applyFilters(fixture(), { result: 'success' }).map(l => l.id);
assert.deepEqual(post.map(l => l.id), ['a2', 'a3']); assert.deepEqual(success, ['a4', 'a1']);
const put = AuditCore.applyFilters(fixture(), { method: 'put', now: NOW }); const failure = C.applyFilters(fixture(), { result: 'failure' }).map(l => l.id);
assert.deepEqual(put.map(l => l.id), ['a1', 'a4']); assert.deepEqual(failure, ['a2', 'a3', 'a5']);
});
test('applyFilters: 动作 + 结果组合', () => {
const out = AuditCore.applyFilters(fixture(), { method: 'POST', result: 'failure', now: NOW });
assert.deepEqual(out.map(l => l.id), ['a2', 'a3']);
});
test('applyFilters: 按结果筛选(成功/失败)', () => {
const ok = AuditCore.applyFilters(fixture(), { result: 'success', now: NOW });
assert.deepEqual(ok.map(l => l.id), ['a1', 'a4']);
const bad = AuditCore.applyFilters(fixture(), { result: 'failure', now: NOW });
assert.deepEqual(bad.map(l => l.id), ['a2', 'a3']);
});
test('applyFilters: 时间范围(24h 只含今天、30d 含上周)', () => {
const day = AuditCore.applyFilters(fixture(), { timeRange: '24h', now: NOW });
assert.deepEqual(day.map(l => l.id), ['a1', 'a2']);
const month = AuditCore.applyFilters(fixture(), { timeRange: '30d', now: NOW });
assert.deepEqual(month.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
}); });
test('applyFilters: 关键字匹配资源名称与路径', () => { test('applyFilters: 关键字匹配资源名称与路径', () => {
const out = AuditCore.applyFilters(fixture(), { keyword: 'hello', now: NOW }); assert.deepEqual(C.applyFilters(fixture(), { keyword: 'hello' }).map(l => l.id), ['a1', 'a2']);
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']); assert.deepEqual(C.applyFilters(fixture(), { keyword: 'configmaps' }).map(l => l.id), ['a5']);
const byPath = AuditCore.applyFilters(fixture(), { keyword: 'configmaps', now: NOW }); assert.deepEqual(C.applyFilters(fixture(), { keyword: 'LOGIN' }).map(l => l.id), ['a4', 'a3', 'a6']);
assert.deepEqual(byPath.map(l => l.id), ['a4']);
}); });
test('applyFilters: 组合条件', () => { test('applyFilters: 起止时间闭区间', () => {
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', result: 'failure', now: NOW }); const out = C.applyFilters(fixture(), {
startTime: '2026-11-21T10:00:00Z',
endTime: '2026-11-21T11:30:00Z'
});
assert.deepEqual(out.map(l => l.id), ['a4', 'a1']);
});
test('applyFilters: 组合条件、时间倒序、不修改入参', () => {
const out = C.applyFilters(fixture(), { resourceType: 'posts', result: 'failure' });
assert.deepEqual(out.map(l => l.id), ['a2']); assert.deepEqual(out.map(l => l.id), ['a2']);
});
test('applyFilters: 结果按时间倒序排列', () => {
const out = AuditCore.applyFilters(fixture(), { now: NOW });
assert.deepEqual(out.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
});
test('applyFilters: 不修改入参数组', () => {
const logs = fixture(); const logs = fixture();
AuditCore.applyFilters(logs, { now: NOW }); C.applyFilters(logs, {});
assert.equal(logs.length, 4); assert.equal(logs.length, 7);
assert.deepEqual(C.applyFilters(fixture(), {}).map(l => l.id), ['a4', 'a1', 'a2', 'a3', 'a6', 'a5', 'a7']);
}); });
// ---------------- paginate ---------------- // ---------------- paginate / countExpired ----------------
test('paginate: 基础分页与元信息', () => { test('paginate: 分页与越界收敛', () => {
const items = Array.from({ length: 25 }, (_, i) => i); const items = Array.from({ length: 25 }, (_, i) => i);
const p = AuditCore.paginate(items, 2, 10); const p = C.paginate(items, 2, 10);
assert.equal(p.total, 25); assert.equal(p.total, 25);
assert.equal(p.pages, 3); assert.equal(p.pages, 3);
assert.equal(p.page, 2); assert.equal(p.page, 2);
assert.deepEqual(p.items, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); assert.deepEqual(p.items, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
assert.equal(C.paginate(items, 99, 10).page, 3);
assert.equal(C.paginate(items, 0, 10).page, 1);
assert.deepEqual(C.paginate([], 1, 20), { items: [], total: 0, pages: 1, page: 1 });
}); });
test('paginate: 页码越界自动收敛', () => {
const items = Array.from({ length: 15 }, (_, i) => i);
assert.equal(AuditCore.paginate(items, 99, 10).page, 2);
assert.equal(AuditCore.paginate(items, 0, 10).page, 1);
});
test('paginate: 空结果时仍返回 1 页', () => {
const p = AuditCore.paginate([], 1, 10);
assert.deepEqual({ total: p.total, pages: p.pages, items: p.items }, { total: 0, pages: 1, items: [] });
});
// ---------------- countExpired(D5 保留期清理) ----------------
test('countExpired: 统计超过保留期的记录', () => { test('countExpired: 统计超过保留期的记录', () => {
const logs = fixture(); // NOW 为 2026-11-21,a4 是 11-10 assert.equal(C.countExpired(fixture(), 5, NOW), 2);
assert.equal(AuditCore.countExpired(logs, 5, NOW), 1); // a4 过期 assert.equal(C.countExpired(fixture(), 90, NOW), 0);
assert.equal(AuditCore.countExpired(logs, 90, NOW), 0); // 全部在保留期内 });
// ---------------- CSV 导出 ----------------
test('toCsv: UTF-8 BOM + CRLF + 表头列顺序', () => {
const csv = C.toCsv([fixture()[0]]);
assert.ok(csv.startsWith('\uFEFF操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent\r\n'));
assert.ok(csv.endsWith('\r\n'));
});
test('toCsv: 记录按时间升序输出,结果/描述/变更列与界面一致', () => {
const logs = [
{ id: 'b', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/x/v1alpha1/posts/b', resourceType: 'posts', resourceName: 'b', statusCode: 200, action: 'publish', attemptedUsername: null, remoteIp: '1.1.1.1', userAgent: 'UA' },
{ id: 'a', timestamp: '2026-11-20T10:00:00Z', username: 'unknown', method: 'GET', path: '/login?error=x', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login-failure', attemptedUsername: 'admin', remoteIp: '2.2.2.2', userAgent: 'bot' },
{ id: 'c', timestamp: '2026-11-22T10:00:00Z', username: 'unknown', method: 'POST', path: '/login', resourceType: 'auth', resourceName: null, statusCode: 302, action: 'login', attemptedUsername: 'guichumo', remoteIp: '3.3.3.3', userAgent: 'chrome' },
// 升级前落库的登录页访问记录:原先导出为「登录,成功」,看起来像未知用户登录成功
{ id: 'd', timestamp: '2026-11-19T10:00:00Z', username: 'unknown', method: 'GET', path: '/login?authentication_required', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login', attemptedUsername: null, remoteIp: '43.228.157.244', userAgent: 'bot' }
];
const lines = C.toCsv(logs).split('\r\n');
assert.equal(lines.length, 6, '表头 + 4 行 + 末尾空行');
assert.match(lines[1], /^2026-11-19 18:00:00,未知用户,,GET,auth,,\/login\?authentication_required,访问登录页,,页面访问,200,43\.228\.157\.244,bot$/);
assert.match(lines[2], /^2026-11-20 18:00:00,未知用户,admin,GET,auth,,/);
assert.match(lines[2], /登录失败,.*失败,200,2\.2\.2\.2,bot$/);
assert.match(lines[3], /发布文章,.*成功,200,1\.1\.1\.1,UA$/);
assert.match(lines[4], /登录,,成功,302,3\.3\.3\.3,chrome$/);
});
test('toCsv: 引号/逗号/换行转义与公式注入防护', () => {
assert.equal(C.csvEscape('a,b'), '"a,b"');
assert.equal(C.csvEscape('say "hi"'), '"say ""hi"""');
assert.equal(C.csvEscape('line1\nline2'), '"line1\nline2"');
assert.equal(C.csvEscape('=SUM(A1)'), "'=SUM(A1)");
assert.equal(C.csvEscape('+1'), "'+1");
assert.equal(C.csvEscape('@cmd'), "'@cmd");
assert.equal(C.csvEscape(null), '');
});
// ---------------- 登录失败告警窗口 ----------------
test('createLoginFailureTracker: 未开启时只维护清零语义,不产生负载', () => {
const tracker = C.createLoginFailureTracker({ enabled: false, thresholdCount: 2, windowMinutes: 5 });
assert.equal(tracker.record({ success: false, time: NOW }), null);
assert.equal(tracker.record({ success: false, time: NOW + 1000 }), null);
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: null });
});
test('createLoginFailureTracker: 达到阈值触发一次告警,之后窗口重开', () => {
const tracker = C.createLoginFailureTracker({ enabled: true, thresholdCount: 3, windowMinutes: 5 });
assert.equal(tracker.record({ success: false, time: NOW, remoteIp: '1.2.3.4', attemptedUsername: 'admin' }), null);
assert.equal(tracker.record({ success: false, time: NOW + 1000 }), null);
const alert = tracker.record({ success: false, time: NOW + 2000, remoteIp: '1.2.3.4', userAgent: 'bot', attemptedUsername: 'admin' });
assert.ok(alert);
assert.equal(alert.failures, 3);
assert.equal(alert.windowMinutes, 5);
assert.equal(alert.remoteIp, '1.2.3.4');
assert.equal(alert.attemptedUsername, 'admin');
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: NOW + 2000 });
// 告警后需重新累计到阈值
assert.equal(tracker.record({ success: false, time: NOW + 3000 }), null);
});
test('createLoginFailureTracker: 登录成功清零、窗口过期重新计数', () => {
const tracker = C.createLoginFailureTracker({ enabled: true, thresholdCount: 3, windowMinutes: 5 });
tracker.record({ success: false, time: NOW });
tracker.record({ success: false, time: NOW + 1000 });
assert.equal(tracker.record({ success: true, time: NOW + 2000 }), null);
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: null });
tracker.record({ success: false, time: NOW + 3000 });
tracker.record({ success: false, time: NOW + 4000 });
assert.equal(tracker.record({ success: false, time: NOW + 5 * 60000 + 4000 }), null, '超过窗口后重新计数,不应触发');
assert.equal(tracker.snapshot().count, 1);
});
test('alertPayload: 通用 JSON 结构与测试消息', () => {
const real = C.alertPayload({
failures: 5,
windowMinutes: 5,
remoteIp: '1.2.3.4',
userAgent: 'Mozilla/5.0',
attemptedUsername: 'admin',
timestamp: '2026-11-21T12:34:56Z'
});
assert.equal(real.type, 'login-failure');
assert.match(real.title, /登录失败/);
assert.match(real.content, /5 分钟内出现 5 次登录失败/);
assert.match(real.content, /admin/);
assert.deepEqual(real.data, {
failures: 5,
windowMinutes: 5,
remoteIp: '1.2.3.4',
userAgent: 'Mozilla/5.0',
attemptedUsername: 'admin'
});
const testPayload = C.alertPayload({ timestamp: '2026-11-21T12:34:56Z' }, 'test');
assert.equal(testPayload.type, 'test');
assert.match(testPayload.title, /测试/);
assert.match(testPayload.content, /测试告警/);
}); });
// ---------------- MockData 模拟数据 ---------------- // ---------------- MockData 模拟数据 ----------------
const FIXED_NOW = new Date('2026-11-21T12:00:00Z').getTime(); const FIXED_NOW = new Date('2026-11-21T12:00:00Z').getTime();
const REQUIRED_FIELDS = ['id', 'timestamp', 'username', 'method', 'path', 'resourceType', 'resourceName', 'statusCode', 'remoteIp', 'userAgent']; const REQUIRED_FIELDS = [
'id', 'timestamp', 'username', 'attemptedUsername', 'method', 'action',
'resourceType', 'resourceName', 'path', 'statusCode', 'remoteIp', 'userAgent', 'changes'
];
test('MockData.generateLogs: 同一种子两次生成结果完全一致(确定性)', () => { test('MockData.generateLogs: 同一种子两次生成结果完全一致(确定性)', () => {
const a = MockData.generateLogs(FIXED_NOW); const a = MockData.generateLogs(FIXED_NOW);
@@ -207,44 +711,106 @@ test('MockData.generateLogs: 记录数量充足且字段完整', () => {
assert.ok(logs.length >= 120, '应有 120+ 条记录,实际 ' + logs.length); assert.ok(logs.length >= 120, '应有 120+ 条记录,实际 ' + logs.length);
for (const log of logs) { for (const log of logs) {
for (const field of REQUIRED_FIELDS) { for (const field of REQUIRED_FIELDS) {
assert.ok(log[field] !== undefined && log[field] !== null, `记录 ${log.id} 缺少字段 ${field}`); assert.ok(Object.prototype.hasOwnProperty.call(log, field), `记录 ${log.id} 缺少字段 ${field}`);
} }
} }
}); });
test('MockData.generateLogs: 按时间倒序且 id 唯一', () => { test('MockData.generateLogs: 按时间倒序且 id 唯一', () => {
const logs = MockData.generateLogs(FIXED_NOW); const logs = MockData.generateLogs(FIXED_NOW);
const ids = new Set(logs.map(l => l.id)); assert.equal(new Set(logs.map(l => l.id)).size, logs.length, 'id 应唯一');
assert.equal(ids.size, logs.length, 'id 应唯一');
for (let i = 1; i < logs.length; i++) { for (let i = 1; i < logs.length; i++) {
const prev = new Date(logs[i - 1].timestamp).getTime(); assert.ok(new Date(logs[i - 1].timestamp).getTime() >= new Date(logs[i].timestamp).getTime());
const curr = new Date(logs[i].timestamp).getTime();
assert.ok(prev >= curr, `第 ${i} 条时间应不晚于下一条`);
} }
}); });
test('MockData.generateLogs: 包含登录审计与"未知用户"记录(产品设计 4.1)', () => { test('MockData.generateLogs: 资源解析与语义动作与捕获管线一致', () => {
const logs = MockData.generateLogs(FIXED_NOW);
assert.ok(logs.some(l => l.resourceType === 'auth' && l.statusCode === 200), '应有登录成功记录');
assert.ok(logs.some(l => l.resourceType === 'auth' && l.username === '未知用户'), '应有登录失败记"未知用户"的记录');
});
test('MockData.generateLogs: 资源解析结果与 resolveResource 规则一致(模拟真实管线)', () => {
const logs = MockData.generateLogs(FIXED_NOW); const logs = MockData.generateLogs(FIXED_NOW);
for (const log of logs) { for (const log of logs) {
const expect = AuditCore.resolveResource(log.path); const resolved = C.resolveResource(log.path);
assert.equal(log.resourceType, expect.resourceType, log.path); assert.equal(log.resourceType, resolved.resourceType, log.path);
assert.equal(log.resourceName, expect.resourceName, log.path); assert.equal(log.resourceName, resolved.resourceName, log.path);
if (log.action) {
assert.equal(typeof log.action, 'string');
}
if (log.changes) {
for (const change of log.changes) {
assert.ok(change.field, '变更条目应含 field');
assert.ok(['ADDED', 'UPDATED', 'REMOVED'].includes(change.changeType));
}
}
} }
}); });
test('MockData.generateLogs: 覆盖全部捕获方法与失败场景', () => { test('MockData.generateLogs: 覆盖登录失败(302)、登录成功与升级前的登录页访问记录', () => {
const logs = MockData.generateLogs(FIXED_NOW); const logs = MockData.generateLogs(FIXED_NOW);
const methods = new Set(logs.map(l => l.method)); assert.ok(logs.some(l => l.action === 'login-failure' && l.method === 'POST' && l.statusCode === 302));
for (const m of ['POST', 'PUT', 'DELETE']) { assert.ok(logs.some(l => l.action === 'login' && l.method === 'POST' && l.statusCode === 302));
assert.ok(methods.has(m), '应包含 ' + m + ' 操作'); assert.ok(logs.some(l => l.method === 'POST' && l.path === '/login' && l.username === 'unknown'));
assert.ok(logs.some(l => l.attemptedUsername === 'admin'));
// 模拟数据不产生「登录页 GET 访问」的新记录:除升级前落库的历史记录外,
// 认证端点只有 POST
const visits = logs.filter(l => l.method !== 'POST' && ['/login', '/logout'].includes(C.pathWithoutQuery(l.path)));
assert.ok(visits.length >= 2, '应含升级前的登录页/登出页访问记录');
for (const visit of visits) {
if (C.isLoginFailure(visit)) {
// 升级前落库的失败回显页:当时标注 login-failure,仍按登录失败展示
assert.equal(C.resultOutcome(visit), 'failure');
assert.equal(C.describeOperation(visit), '登录失败');
} else {
assert.equal(C.resultOutcome(visit), 'page-visit');
assert.match(C.describeOperation(visit), /^访问(登录|登出)页$/);
}
}
});
test('MockData.generateLogs: 覆盖系统内部变更(执行者「系统」、无 IP/UA)', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const systemLogs = logs.filter(l => l.username === 'system');
assert.ok(systemLogs.length >= 2);
for (const log of systemLogs) {
assert.equal(log.statusCode, 200);
assert.equal(log.remoteIp, null);
assert.equal(log.userAgent, null);
assert.ok(['update', 'delete'].includes(log.action));
assert.ok(log.changes && log.changes.length > 0);
}
});
test('MockData.generateLogs: 故事线「hello-halo 谁改过」可回溯', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const helloEdits = logs.filter(l => l.resourceType === 'posts' && l.resourceName === 'hello-halo' && l.method === 'PUT');
assert.ok(helloEdits.length >= 3);
assert.ok(helloEdits.some(l => l.username === 'editor.zhang'));
assert.ok(helloEdits.some(l => l.username === 'guichumo'));
assert.ok(helloEdits.some(l => l.changes && l.changes.some(c => c.field === 'spec.title')));
});
test('MockData.generateLogs: 覆盖插件生命周期、越权与误删', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const actions = new Set(logs.map(l => l.action));
assert.ok(actions.has('upgrade'));
assert.ok(actions.has('enable'));
assert.ok(actions.has('uninstall'));
assert.ok(logs.some(l => l.statusCode === 403));
assert.ok(logs.some(l => l.statusCode === 404));
assert.ok(logs.some(l => l.statusCode === 500));
const deleted = logs.find(l => l.method === 'DELETE' && l.resourceName === 'weekly-2026-w45');
assert.ok(deleted);
assert.ok(deleted.changes && deleted.changes.length > 0, '误删文章应带字段快照');
});
test('MockData.generateLogs: 字段变更覆盖新增/修改/删除且敏感字段已脱敏', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const allChanges = logs.flatMap(l => l.changes || []);
const types = new Set(allChanges.map(c => c.changeType));
assert.ok(types.has('ADDED'));
assert.ok(types.has('UPDATED'));
assert.ok(types.has('REMOVED'));
for (const change of allChanges) {
if (C.isSensitiveField(change.field)) {
assert.ok([change.oldValue, change.newValue].every(v => v == null || v === '******'),
'敏感字段不得落库明文:' + change.field);
}
} }
assert.ok(logs.some(l => !AuditCore.isSuccess(l.statusCode)), '应包含失败操作记录');
assert.ok(logs.some(l => l.statusCode === 403), '应包含越权 403 记录');
assert.ok(logs.some(l => l.statusCode === 500), '应包含服务端 500 记录');
}); });
+82
View File
@@ -0,0 +1,82 @@
# AI 辅助
为了帮助 AI 更全面地了解 Halo 插件的结构、开发流程与最佳实践,从而在插件开发和问题排查过程中提供更准确的帮助,可以向 AI 提供 Halo 开发文档,或安装面向插件开发的 Agent Skill。
## 提供文档上下文
如果 AI 工具支持读取网页,应根据所需上下文范围选择地址:
```text title='文档索引:先查找与任务相关的页面'
https://docs.halo.run/llms.txt
```
```text title='完整文档:仅在需要全站上下文时使用'
https://docs.halo.run/llms-full.txt
```
`llms.txt` 只包含页面标题、描述和链接,不包含每一页的正文。根据索引找到所需页面后,可以把页面地址的后缀改为 `.md`,向 AI 提供该页面的 Markdown 内容,例如:
```text
https://docs.halo.run/developer-guide/plugin/basics/manifest.md
```
`/developer-guide/plugin/index.md` 是插件文档的入口页,不是全部插件开发文档的聚合内容。
:::tip 以线上页面为准
如果让 AI 直接阅读文档仓库源码,需要注意仓库中 `_` 前缀的 Markdown 文件(如 `vo/_ThemeVo.md`、`interface/_OperationItem.md`)是被其他页面引用的片段,单独阅读会缺少上下文。应以上述线上 `.md` 页面为准,它们已包含拼接后的完整内容。
:::
## 核对版本与源码
Halo 插件 API 会随版本演进。使用 AI 生成或修改代码前,应依次确认:
1. 插件 `spec.requires`、Halo BOM 或现有依赖所对应的目标版本。
2. [插件 API 变更](https://docs.halo.run/developer-guide/plugin/api-changelog.md)以及与任务直接相关的文档页面。
3. 文档没有覆盖的签名和行为,以目标版本的 Halo 源码及插件实际依赖类型为准。
向 AI 描述重要契约时,应同时给出引入版本或最低 `spec.requires`、权限、输入与返回值、阻塞或响应式要求、失败语义、生命周期行为及固定提交的源码链接。不要只复制类型名称或方法签名。
## 生成前检查清单
让 AI 编写插件前,至少要求它遵守以下规则:
1. 新插件从官方 `pnpm create halo-plugin` 脚手架开始,现有插件保留自身包管理器、Gradle 和 UI 构建方式。
2. 自定义模型和使用 `SpringdocRouteBuilder` 描述的接口通过 `generateApiClient` 生成 TypeScript 类型与请求方法;不手写可生成的资源类型、参数和 API 路径,具体参考 [API 请求](https://docs.halo.run/developer-guide/plugin/api-reference/ui/api-request.md)。
3. 普通插件设置使用 Setting YAML;页面和弹窗表单使用 Halo 已注册的 FormKit,列表与交互复用 `@halo-dev/components`,具体参考[插件设置与表单组件](https://docs.halo.run/developer-guide/plugin/basics/ui/forms.md)。
4. 密码、Token、API Key 和私钥使用 Halo `Secret`,不存入 ConfigMap 或自定义模型;用户可配置的出站地址必须防范 SSRF 和凭据泄漏,具体参考[敏感数据与出站请求](https://docs.halo.run/developer-guide/plugin/security/outbound-http.md)。
5. UI 路由、操作权限、RoleTemplate 和后端鉴权保持一致;公开 API 和安全开关在配置缺失或读取失败时采用 fail closed。
6. WebFlux 请求链路使用响应式 API,不调用阻塞客户端;修改 API 契约后运行生成任务,不手动修改生成结果。
:::warning 不要手动修改生成文件
不要让 AI 手动修改 OpenAPI 生成的 `api-client`、`api-docs`、构建目录或锁文件。应修改源文件,再运行项目已有的生成器、构建命令或包管理器更新这些文件。
:::
## Agent Skill
Agent Skill 是可安装到 AI 开发工具中的领域知识包,能够让 AI 在特定场景下更准确地给出建议或执行操作。
[halo-dev/dev-skills](https://github.com/halo-dev/dev-skills) 仓库提供了 `halo-plugin-dev` Skill,包含以下内容:
- 插件目录结构与 `plugin.yaml` 配置
- Java 后端、扩展点与自定义 API 开发
- RBAC 权限管理
- Vue 3 前端与 Console、用户中心路由开发
- DevTools 开发流程与 OpenAPI 客户端生成
### 安装
在 Cursor、Claude Code、Codex 等支持 Agent Skills 的 AI 开发工具中,可以通过 [Skills CLI](https://skills.sh/) 安装:
```bash
# 全局安装,可在所有项目中使用
npx skills add halo-dev/dev-skills@halo-plugin-dev -g
# 或仅安装到当前项目
npx skills add halo-dev/dev-skills@halo-plugin-dev
```
### 使用
安装完成后,通常在开发 Halo 插件时,Agent 会根据当前项目和任务自动识别并调用 `halo-plugin-dev` Skill,无需在提示词中显式指定。如果 Agent 未自动调用,可以在提示词中明确要求使用该 Skill。
AI 生成的代码仍需经过代码审查,并按照[插件测试](https://docs.halo.run/developer-guide/plugin/testing.md)和[插件发布验收清单](https://docs.halo.run/developer-guide/plugin/release-checklist.md)完成自动化检查、构建及安装/启停验证后再用于生产环境。
Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

+6 -5
View File
@@ -31,7 +31,7 @@ Halo 博客后台缺少操作追溯能力:文章被改、设置被动、评论
### 4.1 操作记录(核心) ### 4.1 操作记录(核心)
- **捕获范围**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH)。一条通用规则天然覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作,Halo 新增资源类型也自动纳入。匿名访客请求不记录。 - **捕获范围**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH)。一条通用规则天然覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作,Halo 新增资源类型也自动纳入。匿名访客请求不记录。
> 注:登录端点不在 `/apis/**` 下,捕获规则将其作为唯一必要例外精确匹配 `/login`、`/logout`(技术方案 D1)。 > 注:登录端点不在 `/apis/**` 下,且表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),由独立的认证端点过滤器在 Security 过滤链**之前**精确匹配捕获(技术方案 D1)。只记录认证操作 `POST /login`(登录尝试)与 `POST /logout`(登出);登录/登出页面的 GET 访问(打开登录页、匿名访问被弹回登录页 `/login?authentication_required`、失败回显、登出确认页)不是操作,不记录——否则每次页面访问都会落一条「未知用户 · 登录 200」,看起来像登录成功,真正的登录成败反而被淹没。
- **系统内部变更(V2)**:定时发布等非页面操作触发的资源变更不经过 HTTP,由扩展模型 Watcher 通道补记(技术方案 D8):仅记录用户可写面有实际变化的更新/删除;设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物不重复记录;插件自身配置写入排除。 - **系统内部变更(V2)**:定时发布等非页面操作触发的资源变更不经过 HTTP,由扩展模型 Watcher 通道补记(技术方案 D8):仅记录用户可写面有实际变化的更新/删除;设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物不重复记录;插件自身配置写入排除。
- 每条记录字段: - 每条记录字段:
@@ -79,22 +79,23 @@ Console 左侧菜单新增"操作审计"页:
| 功能 | 说明 | 阶段 | | 功能 | 说明 | 阶段 |
|---|---|---| |---|---|---|
| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 | | 语义动作标注 | 区分"发布/编辑/恢复/登录失败"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 |
| 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 | | 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 |
| 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 | | 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 |
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 | | 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
| 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 | | 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 |
| 登录成败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成功与失败均为 302 重定向,以重定向目标是否跳回登录页区分,见 `LoginOutcome`;只有响应明确确认才算成功):失败的登录尝试(`POST /login`)在列表/详情/CSV 中显示红色「失败」,成功显示「成功」,而非被 302/页面渲染的绿色 HTTP 200 掩盖;HTTP 状态码仍如实记录。升级前落库的登录页访问记录(`GET /login`、`GET /logout`)纠正为灰色「—」的「访问登录页/登出页」,不计成败 | V2+ 已实现 |
| 操作回滚 | 不在产品范围内 | 不做 | | 操作回滚 | 不在产品范围内 | 不做 |
## 7. 已知局限 ## 7. 已知局限
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2)
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)不记录(几乎均伴随页面/API 操作,已被 HTTP 通道捕获);操作描述由事件类型推导(更新/删除),具体语义以字段级 diff 为准 - 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)不记录(几乎均伴随页面/API 操作,已被 HTTP 通道捕获);操作描述由事件类型推导(更新/删除),具体语义以字段级 diff 为准
- 系统内部变更的归属降噪为通用规则:设置类资源(ConfigMap/Secret)在写请求活动宽限窗内的变更视为 HTTP 副产物跳过;极少数"路径与实际写入资源不一致"的非设置类端点,其副产物可能记为 system(已知取舍,完整性优先) - 系统内部变更的归属降噪为通用规则:设置类资源(ConfigMap/Secret)在写请求活动宽限窗内的变更视为 HTTP 副产物跳过;极少数"路径与实际写入资源不一致"的非设置类端点,其副产物可能记为 system(已知取舍,完整性优先)
- reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见) - reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见)
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中 - 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中
- 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更 - 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更
- 登录失败告警仅覆盖 POST /login 的失败结果(非 2xx),不含尝试的用户名(与登录记录同一局限);告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志 - 登录成败判定依赖 Halo 登录端点契约(表单登录成败均为 302 重定向):2xx 或重定向到登录页以外(`/uc`、已保存的原请求、两步验证页)才算成功,跳回登录页(含 `error` 参数或路径即 `/login`)、缺失 Location、4xx/5xx 一律判失败——Halo 若调整登录端点契约,需同步调整 `LoginOutcome`;告警仅覆盖 POST /login,登出不算尝试;告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
- 升级前落库的登录页访问记录(当时 GET 也被记成「登录/登出」,标注 `login`/`logout`)不改写标注(审计自身不可篡改):展示与导出按方法纠正为「访问登录页/登出页」且结果不计成败,结果筛选与「登录/登出」语义动作筛选均已排除它们;带 `login-failure` 标注的失败回显页(`GET /login?error=...`)仍按登录失败展示
- 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******` - 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******`
- 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中 - 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口) - 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口)
@@ -103,7 +104,7 @@ Console 左侧菜单新增"操作审计"页:
## 8. 技术要点(均已在 v2.26.1 源码级验证) ## 8. 技术要点(均已在 v2.26.1 源码级验证)
- 运行环境:Halo 2.26.1(Spring Boot 4);插件 JDK 21,Gradle 插件 `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0 - 运行环境:Halo 2.26.1(Spring Boot 4);插件 JDK 21,Gradle 插件 `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0
- 捕获通道:`AfterSecurityWebFilter` 扩展点——位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码 - 捕获通道:双过滤器分治——`/apis/**` 写操作由 `AfterSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码);认证端点 `/login`、`/logout` 由 `BeforeSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最前,先于表单登录/登出终止过滤器,操作者记"未知用户")。P0 缺陷实证:链尾过滤器永远看不到表单登录/登出请求(命中即 302 终止,不向下游传递),认证端点必须在链首承接
- 为何走 HTTP 层:AOP 拦截核心 API、资源元数据自带操作者两条路在 2.26.1 上均被源码验证不可行 - 为何走 HTTP 层:AOP 拦截核心 API、资源元数据自带操作者两条路在 2.26.1 上均被源码验证不可行
- 存储:自定义 Extension + 索引查询 - 存储:自定义 Extension + 索引查询
- 参考项目:[halo-plugin-sso](https://github.com/liuyiwuqing/halo-plugin-sso)(审计闭环范本)、[plugin-comment-widget](https://github.com/halo-dev/plugin-comment-widget)(`AfterSecurityWebFilter` 实战)、[notify-hub](https://github.com/shirainbown/notify-hub)(事件监听与稳定性模式) - 参考项目:[halo-plugin-sso](https://github.com/liuyiwuqing/halo-plugin-sso)(审计闭环范本)、[plugin-comment-widget](https://github.com/halo-dev/plugin-comment-widget)(`AfterSecurityWebFilter` 实战)、[notify-hub](https://github.com/shirainbown/notify-hub)(事件监听与稳定性模式)
+125
View File
@@ -0,0 +1,125 @@
# Halo 操作审计插件 · 官方开发规范符合性评审
> 版本:v0.1 · 日期:2026-11-22
> 关联文档:[operation-audit-design.md](./operation-audit-design.md)(产品设计)·
> [operation-audit-tech-design.md](./operation-audit-tech-design.md)(技术方案)·
> [operation-audit-roadmap.md](./operation-audit-roadmap.md)(功能增减评审)
> 插件标识:`operation-audit`(工作目录 `plugin-operation-audit/`)
> 评审依据:Halo 官方文档「AI 辅助」页的生成前检查清单六条要求
> (https://docs.halo.run/llms.txt 索引下 `developer-guide/plugin/security/outbound-http.md` 等)。
## 1. 总体结论
**基本符合,2 项明确不符合。** 六条清单中,脚手架与构建方式(第 1 条)、设置表单与组件
(第 3 条)、RBAC 一致性(第 5 条)、WebFlux 响应式(第 6 条)符合;
**第 2 条(generateApiClient 生成 API 客户端)与第 4 条(Secret 凭据存储 / SSRF 防护)不符合**。
项目健康度:后端 `./gradlew test`(JDK 21,219 用例)通过;Console UI vitest 54 用例全通过。
本文为评审记录,不涉及代码改动。
## 2. 逐条对照总览
| # | 要求 | 结论 | 关键证据 |
|---|---|---|---|
| 1 | 官方脚手架结构;保留自身包管理器 | ✅ 符合 | devtools + ui-plugin-bundler-kit;npm + `.npmrc` 有书面理由 |
| 2 | 自定义模型与 Springdoc 端点经 `generateApiClient` 生成,不手写 | ❌ 不符合 | 无任何生成产物;UI 手写类型/路径/请求 |
| 3 | Setting YAML + FormKit + `@halo-dev/components` | ✅ 符合 | settings.yaml;自定义 FormKit 输入;V* 组件 |
| 4 | 凭据存 Halo `Secret`;出站地址防 SSRF | ❌ 不符合 | URL 仅校验 http(s) 前缀;Webhook URL 存 ConfigMap |
| 5 | UI 路由 / RoleTemplate / 后端鉴权一致;fail closed | ✅ 符合 | 三处权限标识一致;告警开关 fail closed |
| 6 | WebFlux 全程响应式,不调用阻塞客户端 | ✅ 符合 | 无 `.block()`/RestTemplate;WebClient + Reactor 调度 |
## 3. 符合项详情
### 3.1 脚手架与构建方式(第 1 条)
- Gradle 结构与官方脚手架一致:`run.halo.plugin.devtools` 0.8.0、
`@halo-dev/ui-plugin-bundler-kit` 负责前端外部化与产物输出,
`plugin.yaml` / `extensions/` / `ui/` 布局标准(`build.gradle`、`ui/vite.config.ts`)。
- 保留自身包管理器 npm,`ui/.npmrc` 中 `legacy-peer-deps` 附有理由注释,符合
"现有插件保留自身包管理器"约定。
- 版本对齐:`spec.requires >=2.26.0`、platform 2.26.0、devtools halo 2.26.1 一致。
### 3.2 设置与表单组件(第 3 条)
- 插件设置全部经 Setting YAML(`src/main/resources/extensions/settings.yaml`)。
- 「发送测试告警」按钮按 Halo 2.25+ 契约注册自定义 FormKit 输入
(`ui/src/index.ts` 的 `formkit.inputs`),`ignore: true` 不落配置值。
- 列表与交互复用 `@halo-dev/components`(VButton/VCard/VEmpty/VEntity/VPagination 等)。
### 3.3 RBAC 一致性与 fail closed(第 5 条)
- UI 权限标识 `plugin:operation-audit:view` 在 role-template `ui-permissions`、
路由 `meta.permissions`、菜单过滤三处一致。
- RBAC 资源组合与端点严格对应:`auditlogs` + `auditlogs/query` + `auditlogs/export`
仅 `get/list`(只读设计,被授权角色技术上无法删改审计记录);测试告警端点
(`alerts/test`,create 动词)刻意不授权给只读模板,仅管理角色可用,语义自洽。
- fail closed:告警开关读取失败回退默认**关闭**(`AlertSettingProvider`)。
- 备注:审计开关读取失败回退**开启**属于审计完整性的合理取舍,不属于清单所指
"公开 API / 安全开关"范畴,可接受。
### 3.4 WebFlux 响应式(第 6 条)
- 全链路响应式:`AfterSecurityWebFilter`/`BeforeSecurityWebFilter` 扩展点、
`ReactiveExtensionClient`、出站用 `WebClient`、定时清理用 Reactor 调度(未用 `@Scheduled`)。
- 未发现 `.block()` / `RestTemplate` / 阻塞 IO;仅有的 `synchronized`
(`LoginFailureAlertService` 窗口计数)为内存短临界区,非阻塞客户端。
## 4. 不符合项详情
### 4.1 generateApiClient 未启用(第 2 条)
后端恰好落在该条覆盖的两种情形:自定义模型 `AuditLog`(`@GVK`)+
`SpringdocRouteBuilder` 描述的三个端点(query / export / test),但:
- 项目没有任何生成产物;devtools 的 `generateApiClient` /
`watchAndGenerateApiClient` 任务未配置;
- UI 手写了全部可生成内容:
- 类型:`ui/src/utils/audit.ts` 的 `AuditLog` / `AuditLogSpec` / `ListResult`(复刻后端模型);
- API 路径:`AuditLogList.vue`(QUERY_ENDPOINT / EXPORT_ENDPOINT)与
`TestAlertButton.vue`(TEST_ALERT_ENDPOINT)硬编码,靠注释提醒"与后端保持一致";
- 请求方式:裸 `fetch`,而非生成的请求方法;
- `@halo-dev/api-client` 2.26.0 声明在 `ui/package.json` 却从未 import——死依赖,
恰是"本该用生成客户端"的痕迹。
### 4.2 Secret 与 SSRF(第 4 条)
1. **SSRF 防护缺失**(最实质的安全缺口)。Webhook 地址是用户可配置的出站地址,
但校验仅为"非空 + http(s) 前缀"(`AlertSettings.webhookUrlOrDefault`),
发送前未解析并拒绝 localhost / 环回 / 私网 / 链路本地 / 云元数据地址
(如 `169.254.169.254`),也无域名白名单。已符合的仅两点:10 秒超时、
WebClient 默认不跟随重定向。参考
`developer-guide/plugin/security/outbound-http.md`:需解析全部 IPv4/IPv6
地址并拒绝环回、私网、链路本地、组播、未指定地址与云元数据地址。
(缓解因素:仅管理角色可配置并触发测试,攻击前提是已持有管理权限;
但文档要求对用户可配置出站地址一律防护。)
2. **凭据存储**。Webhook URL 存于插件 ConfigMap。常见 Webhook(钉钉/飞书等)
URL 内嵌 `access_token`,按文档要求 Token 应存 Halo `Secret`、Setting 只存
Secret 名称,并使用 `secret` 类型表单输入——当前未做。若有意仅支持
"不含凭据的中转地址",也应将该取舍写入文档(README 现无说明)。
## 5. 修复建议(未实施)
1. **API 客户端生成**:在 devtools 配置中启用 `generateApiClient`
(或开发期 `watchAndGenerateApiClient`),为 `AuditLog` 模型与三个 Springdoc
端点生成 TS 类型与请求方法;UI 改用生成客户端替换手写类型与 `fetch`;
移除死依赖 `@halo-dev/api-client`。此后修改 API 契约一律走生成任务。
2. **SSRF 校验**:`AlertWebhookSender` 发送前增加校验——`URI` 解析 + 白名单式
scheme/host/port 校验(禁用户名密码形态)+ 解析全部 A/AAAA 记录并拒绝
环回 / 私网 / 链路本地 / 保留地址(含 DNS rebinding 考量);
校验失败归一为现有 `AlertSendResult.failure`,fire-and-forget 语义不变。
3. **凭据迁移(可选)**:如需支持含 token 的 Webhook,将 URL 迁移到 Halo
`Secret`(Setting 改用 `secret` 输入存引用,服务端经
`ReactiveExtensionClient` 读取);否则在 README 明确"仅支持不含凭据的地址"。
## 6. 验证状态
- 后端:`JAVA_HOME=jdk-21 ./gradlew test` BUILD SUCCESSFUL
(test 任务 UP-TO-DATE,即上次全量执行通过,Gradle 缓存判定无需重跑)。
- 前端:`cd ui && npm test` — 8 个测试文件 54 用例全部通过。
- 本文档为纯评审记录,未改动任何代码与测试。
## 7. 备注
- 本机 `JAVA_HOME` 默认指向 `jre7`,`./gradlew` 直接运行会报
"Gradle 8.12 requires Java 1.8 or later";评审时以
`JAVA_HOME="C:/Program Files/Java/jdk-21.0.10"` 运行。构建该插件需 JDK 21。
@@ -0,0 +1,256 @@
# 操作审计插件发布验收清单确认报告
> 依据 [plugin-release-checklist.md](./plugin-release-checklist.md) 对本插件做发布前逐项确认。
>
> - 确认日期:2026-11-22(首轮确认 + 同日待办补齐复测);2026-12-05(第六轮复核)
> - 被测制品:**正式版干净构建产物**
> `plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar`
> - 源码基线:commit `00c8d3f`(master,工作区干净)——第六轮复核;此前各轮的基线是 `81693e4`
> - 结论速览:**暂不可发布**。第六轮对当前 HEAD 的正式版制品重做了整份清单:制品本身在 Halo
> 2.26.0 / 2.26.1 / 2.27.4 上的安装、启停、重启、升级、卸载、权限、SSRF 与 Console 页面
> 全部通过;但有 **2 个必须先修复的代码问题**(敏感字段脱敏缺口、API 客户端不是生成器
> 产物)和 **5 项发布流程 / 上架资料阻断**,见
> [六、第六轮复核](#六第六轮复核2026-12-05commit-00c8d3f--结论暂不可发布)。
> - 第一~五节与「结论与待办」是 2026-11-22 的历史确认,针对 `81693e4` 的制品,当时的
> 「发布就绪」结论**已被第六轮取代**;其中与第六轮事实不符的条目已就地标注「第六轮更正」。
## 一、构建发布制品 — ✅ 通过(1 项前提)
| 检查项 | 结果 | 证据 |
| --- | --- | --- |
| `clean build` 成功并运行所有接入 `check` 的检查 | ✅ | BUILD SUCCESSFUL;后端 26 类 270 测试、UI 9 spec 69 测试全部通过 |
| JAR 文件名 = Gradle 项目版本 = `spec.version` | ✅ | 三处均为 `0.1.0-SNAPSHOT`(devtools 自动注入 JAR 内 plugin.yaml) |
| `git status --short` 只有预期变化 | ✅ | 干净,`build/` 已忽略 |
| 多模块只发布插件 JAR | ✅ | `build/libs` 仅 1 个 JAR;`ui` 子项目只产出前端资源,无多余制品 |
> 环境注意:本机 `JAVA_HOME` 指向 jre7,Gradle 调用需临时覆盖为 JDK 21
> (`JAVA_HOME="C:/Program Files/Java/jdk-21.0.10" ./gradlew ...`),与测试报告记录一致。
✅ **正式版补构建(P0 完成)**:已以 `clean build -Pversion=0.1.0` 完成干净构建,
三处一致复查通过——JAR 文件名 `plugin-operation-audit-0.1.0.jar`、JAR 内
`plugin.yaml` 的 `spec.version: 0.1.0`(devtools 注入)、Manifest
`Implementation-Version: 0.1.0` 全部一致;制品 SHA-256 见[发布证据块](#五记录发布证据--✅-就绪本轮补齐)。
## 二、检查 JAR 内容 — ✅ 基本通过(2 项缺口)
| 检查项 | 结果 | 证据 |
| --- | --- | --- |
| `plugin.yaml` 在 JAR 根目录,name/version/requires/许可证正确 | ✅ | `operation-audit`、`>=2.26.0`、`GPL-3.0` 均正确;无插件依赖声明(本插件无依赖,N/A) |
| Logo、主页、问题反馈地址 | ❌ 缺失 | `spec.logo`、`spec.homepage`、`spec.repo`、`spec.issues` 均未声明(对照官方 manifest 文档均为有效字段;上架应用市场必需) |
| Manifest 的 `Plugin-Main-Class` 和 `Implementation-Version` | ✅ | `run.halo.app.plugin.BasePlugin` 正确——已对照 Halo 2.26.1 源码:`YamlPluginDescriptorFinder` 对所有插件硬编码使用 `BasePlugin`,devtools 写入值与运行时一致;`Implementation-Version: 0.1.0-SNAPSHOT` 一致 |
| 后端类、extensions、运行时资源完整 | ✅ | 40+ 类、`extensions/role-template.yaml`、`extensions/settings.yaml`、`META-INF/plugin-components.idx` 齐全 |
| UI 打包完整、清单声明的资源均存在 | ✅ | `ui-plugin.json`(ESM)声明的入口与样式均在 JAR 内;**已从 `console/` 迁移到官方规范的 `ui/` 目录(P2 完成,commit `81693e4`)**——`processUiResources` 输出到 `resources/main/ui` 并清理旧构建残留的 `console/`;正式版 JAR 复核 `ui/ui-plugin.json` + 入口/样式齐备 |
| 已运行 `generateApiClient`,无手写重复 | ⚠️ 第六轮更正 | 当时按「产物入库、无手写同资源类型」判为通过。第六轮用运行实例真实再生成后证实:入库的 `ui/src/api/generated` 是手工对齐的契约,不是生成器输出,且再生成产物会让 UI 类型检查失败(见第六轮 6.2 的 B5) |
| JAR 不含凭据、`.env`、测试数据等敏感文件 | ✅ | 条目清单干净:仅类、extensions、console 资源、plugin.yaml、MANIFEST |
### Plugin-Main-Class 专项考证
本插件 JAR 的 Manifest 值为基类 `run.halo.app.plugin.BasePlugin` 而非具体类
`run.halo.operationaudit.OperationAuditPlugin`。经查证属**预期行为**:
- Halo 2.26.1 的 `YamlPluginDescriptorFinder#convert` 将插件类硬编码为
`run.halo.app.plugin.BasePlugin`,不读取 Manifest 的 `Plugin-Main-Class`;
- devtools 0.8.0 的 `PluginJarManifestCustomizer` 默认即写入该值(内部含
`ResolvePluginMainClassName` 解析任务与 `DEFAULT_MAIN_CLASS` 兜底)。
写入值与运行时行为一致,清单该项判定通过。
## 三、验证安装和升级 — ✅ 大部分通过(引用三轮真实 Halo 联调)
[测试报告](./operation-audit-test-report.md)已覆盖:
- 默认 `deployment` 模式上传安装、启用 ✅;
- 插件信息、默认配置、权限、Console 入口及主要功能(浏览器级逐项人工检查)✅;
- 重启 Halo 后插件启动、配置与持久化数据 ✅;
- 禁用→重新启用,运行时资源释放恢复 ✅;
- 同实例换 JAR 升级 ✅(Windows 文件锁注意事项已记录);
- 权限矩阵(admin + 仅授予 `role-template-audit-view` 的只读用户,含匿名拒绝路径)✅;
- 无依赖插件,"依赖缺失/停用/版本不满足"状态 N/A ✅;
- FormKit 设置表单、凭据入 Secret、出站环回地址 SSRF 拦截实测 ✅。
**未覆盖项**(清单明确要求、测试报告已自认):
- ✅ **卸载(uninstall)测试**已于第四轮补测通过(见下);
- ✅ **`requires` 最低版本 2.26.0 下探实测**已完成(见下);
- ⚠️ Webhook 公网投递链路未验证(避免向外部服务发送数据,合理限制,保留)。
**第四轮补测(2026-11-22,commit `81693e4`,详见测试报告)**:
- **卸载生命周期** ✅:对齐 Console「卸载并删除配置」路径实测——CR/JAR/Setting/
ConfigMap/RoleTemplate 全部清理,审计数据保留(重装后 169→172 条回归),
pf4j `disabled.txt` 停用残留被 Halo 重装启动时自动清除;唯一残留为宿主侧
RoleBinding 孤儿绑定(Halo 平台行为,RoleTemplate 已删、无授权效果,已记录);
- **2.26.0 最低版本下探** ✅:官方 2.26.0 实例全新安装 0.1.0,安装/启用/审计捕获/
查询导出/权限拒绝路径全部正常(详见测试报告第四轮 2.26.0 下探记录)。
## 四、核对 CI/CD — ⚠️ 已配置但从未运行(第六轮更正)
> 第六轮事实(2026-12-05):工作流文件自 `44eca75` 提交以来在托管平台(Gitea Actions)
> 上**一次也没有运行过**,提交状态为空;两个 `gradlew` 在 Git 中的模式都是 `100644`
> (无执行位);远端 tag `v0.1.0` 指向修复前的提交 `5d05d63`。清单要求的「发布 commit 的
> CI 已通过」因此不成立,详见第六轮 6.2 的 B2~B4。以下为当时的配置说明,仅备查。
[.github/workflows/ci.yml](../.github/workflows/ci.yml) / [cd.yml](../.github/workflows/cd.yml)
复用官方 `halo-sigs/reusable-workflows`(`plugin-ci.yaml@v5` / `plugin-cd.yaml@v5`):
- CI:push/PR 触发 `./gradlew clean build`(全部后端测试 + UI 检查,不可跳过);
- CD:Release published 触发,工作流自动执行
`./gradlew clean build -x check -Pversion=${tag 去 v 前缀}`,
由构建保证 Release tag(如 `v0.1.0`)↔ JAR 文件名 ↔ `spec.version` 一致
(`-Pversion=0.1.0` 三处一致已实测验证,见章节一);
- `artifacts-path: plugin-operation-audit/build/libs` 仅匹配插件 JAR(仓库唯一制品目录);
- `skip-appstore-release: true`:首次上架审核通过前只上传 Release 资产,不自动同步应用市场;
- 仓库 Gradle 根在 `plugin-operation-audit/` 子目录,官方工作流从仓库根执行 `./gradlew`——
根目录 `gradlew`/`gradlew.bat` 为转发脚本,`build-args: "-p plugin-operation-audit"` 指定项目目录;
UI 子项目使用 npm(无 pnpm-lock.yaml),故 `skip-node-setup: true`,由 runner 预装
Node/npm 配合 node-gradle 插件完成前端构建。
## 五、记录发布证据 — ✅ 就绪(本轮补齐;仅对应 `81693e4` 的制品)
> 本节证据块对应 commit `81693e4` 构建的制品(SHA-256 `3d2a2ad4…`),**不是当前 HEAD 的
> 制品**。当前制品的证据块见第六轮 6.4。
发布证据块(正式版制品,构建于 commit `81693e4`,工作流/文档提交不影响制品内容):
```text
Commit and tag: 81693e4(tag v0.1.0,见下方说明)
Plugin version: 0.1.0
Halo versions tested: 2.26.1(烟测实例,H2);2.26.0(最低版本下探,见章节三补充)
Clean install: pass(install API → enable → STARTED,见第四轮测试记录)
Upgrade from: 0.1.0-SNAPSHOT → 0.1.0,pass(upgrade API,169 条历史数据保留)
Commands run: ./gradlew clean build -Pversion=0.1.0(JDK 21);
联调:upgrade/install/uninstall/enable API、登录/登出审计、
query/export、匿名与只读角色路径(详见测试报告第四轮)
Roles and dependency states: admin 与 auditor3(仅 role-template-audit-view)实测;
无插件依赖,N/A
Known limitations: Windows 升级 JAR 文件锁环境限制(本轮 upgrade API 实测正常);
Webhook 公网投递未验证(避免向外部服务发送数据)
Artifact path and SHA-256:
plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar
SHA-256: 3d2a2ad4ea8ea53af169806be95fe348d2da2fa263f8d681fee38abea47db563
```
**Release tag 说明**:发布流程为——推送 master 后在代码托管平台创建 tag `v0.1.0`
并发布 Release;CD 工作流将以 tag 版本号(`v0.1.0` → `-Pversion=0.1.0`)构建并
把 JAR 作为 Release 资产上传。本地已按此版本号完成干净构建与验收(章节一、三),
**发布前仍需在 CI 上通过一次完整构建**(CD 带 `-x check`,不能替代 CI 与测试)。
## 结论与待办(2026-11-22 的历史结论,已被第六轮取代)
> **第六轮更正**:下表 6 项待办的「完成」只说明当时补齐了对应文件或测试,不代表现在可以
> 发布——其中「补 CI/CD 工作流」从未在平台上运行,「生成客户端」一项的判定有误。当前结论
> 以[第六轮复核](#六第六轮复核2026-12-05commit-00c8d3f--结论暂不可发布)为准。
**发布就绪**:原 6 项待办(2×P0、2×P1、2×P2)已全部完成——
| 优先级 | 待办 | 状态 | 对应章节 |
| --- | --- | --- | --- |
| P0 | 以正式版本号(非 SNAPSHOT)重新干净构建,并复查版本三处一致 | ✅ `clean build -Pversion=0.1.0` 全绿,JAR 名 / `spec.version` / Manifest 一致(0.1.0) | 一 |
| P0 | 补 CI/CD 工作流(可复用 CI 跑 `clean build` + 基于 Release tag 的 CD) | ✅ `plugin-ci/cd.yaml@v5` 已配置(44eca75),artifacts-path 限定制品目录、首上架不自动同步应用市场 | 四 |
| P1 | 补卸载(uninstall)测试与 2.26.0 最低版本下探实测 | ✅ 卸载生命周期实测通过(753de51);2.26.0 下探见章节三补充 | 三 |
| P1 | 生成发布版制品的 SHA-256 并补全发布证据块(含 Release tag) | ✅ 0.1.0 制品 SHA-256 已记录于发布证据块 | 五 |
| P2 | 补 `plugin.yaml` 的 `spec.logo` / `spec.homepage` / `spec.repo` / `spec.issues` | ✅ logo.svg 内置 + homepage/repo/issues/author.website/license.url 已补(81693e4) | 二 |
| P2 | UI 输出目录从 `console/` 迁移到 `ui/`(官方当前规范位置) | ✅ `processUiResources` 迁至 `ui/`,JAR 内 `ui/ui-plugin.json` 入口/样式齐备(81693e4) | 二 |
**剩余发布动作**(非验收缺口,属发布操作):
推送 master → 创建 tag `v0.1.0` 并发布 GitHub Release → CI 绿 → CD 产出 Release
资产 → (审核通过后)配置应用市场同步。
## 六、第六轮复核(2026-12-05,commit `00c8d3f`)—— 结论:暂不可发布
本轮对**当前 HEAD 的正式版制品**重做了整份清单(不再沿用第一~五节针对 `81693e4` 的结论),
并对照《应用市场审核指南》(`review-guidelines-v2026.09.07`)做了上架前自查。测试细节与
证据见[测试报告第六轮](./operation-audit-test-report.md#复测记录2026-12-05-第六轮发布制品复核commit-00c8d3f)。
### 6.1 逐节结论(当前制品)
| 清单章节 | 结论 | 依据 |
| --- | --- | --- |
| 一、构建发布制品 | ✅ | `clean build -Pversion=0.1.0` 成功,`check` 内后端 286/286、UI 74/74、类型检查全部执行;版本三处一致;工作区干净;仅 1 个插件 JAR |
| 二、检查 JAR 内容 | ❌ 1 项 | `plugin.yaml`、Manifest、运行时资源、`ui/` 清单与敏感文件均通过;**「已运行 `generateApiClient`、无手写类型」不成立**(B5) |
| 三、验证安装和升级 | ✅ | 5 个一次性实例覆盖 2.26.0 / 2.26.1 / 2.27.4:默认模式安装、启用、重启、停用/启用往返、旧版升级、卸载及卸载后重启全部通过;设置表单、凭据入 Secret、SSRF 拦截实测;**但脱敏覆盖面不足**(B1) |
| 四、核对 CI/CD | ⚠️ 部分 | `gradlew` 执行位已修复(B3);工作流从未在平台上运行、且复用 GitHub 专用工作流(B4) |
| 五、记录发布证据 | ✅ | 见 6.4;对照指南的自查另查出上架资料缺口(B6) |
清单的停止发布条件中,「检查或构建失败、JAR 无法安装或启用、版本信息不一致、主要功能或
权限失效、升级导致数据损坏、制品包含敏感文件」六项本轮**均未触发**。判定「暂不可发布」
的依据是:清单第四节不满足、清单第二节的生成客户端项不成立,以及审核指南 4.3.2 对明文
密钥与卸载清理说明的硬性要求。
### 6.2 发布阻断项
> 2026-12-05 晚更新:仓库推送地址迁到 `https://gitea.guichumo.com/836061373/halo-ops-audit.git`
> 后,B7 已完成修复并复验;`gradlew` 执行位(B3)也已修复。当前仍有 **5 项**阻断:
> B1、B2、B4、B5、B6。
| 编号 | 级别 | 问题 | 证据 | 修复方向 |
| --- | --- | --- | --- | --- |
| B1 | P0 | **敏感字段脱敏只按字段名匹配 `password\|passwd\|secret\|token\|credential`**。插件记录全后台 `/apis/**` 写操作的字段级 diff,第三方插件资源常见的 `apiKey` / `accessKey` / `accessKeyId` / `privateKey` / `authHeader` 会被**明文**写入审计库,并在详情抽屉与 CSV 中可见 | 实测(2.26.1,真实 diff 路径):`password`、`clientSecret`、`api_token` 显示 `******`,其余 5 个字段明文入库;审核指南 4.3.2「存储明文密码、密钥、令牌」「在日志中泄露敏感信息」将被拒绝 | 扩展为键名(`api[-_]?key`、`access[-_]?key`、`private[-_]?key`、`keyId`、`authorization` 等)+ 值特征(JWT、长 base64/hex)双重判定;补单测;同步修正 README「敏感字段自动脱敏」的表述 |
| B2 | P0 | **远端 tag `v0.1.0` 指向修复前的提交 `5d05d63`**(早于 `fc79842`「登录页访问不再记成登录成功」)。按 CD 流程发布 Release 会从该提交构建出同样名为 `0.1.0`、带已知缺陷的 JAR | 新远端 `https://gitea.guichumo.com/836061373/halo-ops-audit.git`:`master` 已推进到 `23d8846`,但 `refs/tags/v0.1.0^{}` 仍是 `5d05d63` | 修复完成后删除远端 tag 并在新的发布提交上重打(需你确认后执行) |
| B3 | ✅ 已修复(2026-12-05) | ~~`gradlew` 无执行位(两处均 `100644`,Linux runner 上 `./gradlew` 会直接失败)~~。两处 `gradlew` 已 `git update-index --chmod=+x` 改为 `100755` | `git ls-files -s gradlew plugin-operation-audit/gradlew` → `100755` | 已完成;CI 是否真正跑绿仍取决于 B4 |
| B4 | P0 | **CI 从未运行**:托管平台 Gitea Actions 显示 `0 workflow runs`,提交状态为空;而两个工作流复用的是 GitHub 专用的 `halo-sigs/reusable-workflows`(CD 还依赖 `gh release upload`)。清单要求「发布 commit 的 CI 已通过,没有被跳过」 | 平台页面「0 workflow runs」;**2026-12-05 把 `23d8846` 推送到 master 后再次核对:Actions 列表里能看到 CI、CD 两个工作流,但推送仍未产生任何运行(仍为 0)** | 在 Gitea 上改为自建的 `./gradlew clean build` 步骤(或迁移到 GitHub),让发布提交的 CI 实际跑绿 |
| B5 | P1 | **入库的 API 客户端不是生成器产物**。用运行实例真实再生成后:请求层契约一致,但模型字段全为可选,`vue-tsc` 报错;README 记载的再生成步骤照做会失败(`-P` 参数不被 devtools 0.8.0 识别、无 Docker 时任务仍拉镜像、正式实例默认关闭 springdoc) | 第六轮实测,见测试报告「API 客户端不是生成器产物」 | 后端模型补 `@Schema(requiredMode = REQUIRED)` 与描述 → 真实再生成并入库(或按再生成产物调整视图);更正 README 的再生成说明 |
| B6 | P1 | **上架资料缺失**:仓库没有 LICENSE 文件(`plugin.yaml` 声明 `GPL-3.0`);README 没有隐私说明(插件记录用户名、尝试用户名、IP、UA,并可向 Webhook 外发)、卸载与数据清理说明、升级说明 | 审核指南 5.1(隐私)、5.2 与提交前检查(许可证)、4.3.2(卸载后的清理说明)、2.1(升级说明) | 补 `LICENSE`(GPL-3.0 全文)与 README 的「隐私与数据」「升级」「卸载」三节 |
| B7 | ✅ 已修复(2026-12-05) | ~~`plugin.yaml` 的主页 / 仓库 / 问题反馈 / 作者链接是裸 IP + HTTP + 3000 端口~~。仓库已迁至 `https://gitea.guichumo.com/836061373/halo-ops-audit`(HTTPS 200,HTTP 301 → HTTPS,`/issues` 200);四处链接已改为该域名,重新构建后在全新 2.26.1 实例上安装,Plugin CR 的 homepage / repo / issues / author.website 均为新链接 | 新制品 SHA-256 `b26623e9…`;与上一制品的差异只有 `plugin.yaml` 一个条目(56 个条目逐字节相同) | 已完成 |
### 6.3 非阻断观察
- 插件自己的 `POST /apis/audit.guichumo.com/v1alpha1/alerts/-/test` 被审计为「新建alerts」
(资源类型无中文名、动作按 POST 推导),纯文案问题。
- Webhook 公网投递未验证(SSRF 守卫按设计拒绝环回地址,本轮未向外部服务发送数据);
成功投递只有单测覆盖。
- 保留期清理只有单测覆盖:Halo 在创建时覆盖客户端给的 `creationTimestamp`,无法在验收
窗口内构造过期数据。
- 停用插件后 Halo 仍以 200 下发插件的静态 JS/CSS(所有插件一致的平台行为),数据端点
此时为 404;README 可顺带说明。
- 卸载后宿主侧留下 1 条孤儿 RoleBinding(Halo 平台行为,角色已删、无授权效果)。
- 第五轮遗留的「未在 2.26.0 重测」本轮已补齐(实例 C 全量 111/111)。
### 6.4 第六轮发布证据块
```text
Commit and tag: 00c8d3f(master,工作区干净)+ 链接迁移的未提交改动(见下方制品说明);
尚无指向该提交的 tag。远端 tag v0.1.0 指向修复前的 5d05d63,不可用于发布
Plugin version: 0.1.0
Halo versions tested: 2.26.0(requires 下限)、2.26.1(目标版本)、2.27.4(当前最新)
Clean install: pass(默认 deployment 模式,一次性全新实例,install API → enable → STARTED)
Upgrade from: 0.1.0-SNAPSHOT(tag v0.1.0 构建)→ 0.1.0,pass(设置与全部历史记录保留,
旧页面访问记录不改写且不再计入成功)
Commands run: ./gradlew clean build -Pversion=0.1.0(仓库根入口,JDK 21);
node --test demo/test/audit-core.test.mjs;
install / upgrade / uninstall API、启停、重启、登录登出、query / export /
alerts test、角色矩阵、设置生效、SSRF;generateOpenApiDocs + generateApiClient
(指向运行实例);应用内浏览器冒烟
Roles and dependency states checked:
admin(超级管理员)、auditor(仅 role-template-audit-view)、无角色普通用户、
匿名;无插件依赖(依赖缺失 / 停用 / 版本不满足 N/A)
Known limitations: 见 6.2 的 B1、B5 与 6.3
Artifact path and SHA-256:
plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar
8391674adcd894b82497f1684ae2382b0d5be44192065014c5b52a8fcf185a83
—— 通过上述 5 实例完整矩阵的制品(plugin.yaml 链接仍为旧裸 IP)
b26623e9fbbe39e8f57072f554d9c018c1fa603bdcc5d8810f220d09e3b2eaa0
—— 仅把 plugin.yaml 四处链接换成 https://gitea.guichumo.com/… 后重新 clean build 的制品;
与上一制品逐条目对比只有 plugin.yaml 变化(其余 56 个条目逐字节相同);
已在全新 Halo 2.26.1 实例上复验安装与元数据(Plugin CR 四处链接为新域名)
Verdict: 暂不可发布(B1~B6 修复后需重新构建并对本节流程复验)
```
### 6.5 建议的修复顺序
1. B1:扩展脱敏规则并补单测(会改变 JAR 内容)。
2. B5:后端模型补 `required` 声明,真实再生成客户端并入库,更正 README 的再生成说明。
3. B6:补 LICENSE 与 README 三节。
4. B3 / B4:给 `gradlew` 加执行位,让 CI 在托管平台上实际跑绿。
5. 重新 `clean build -Pversion=0.1.0`,用本轮的一次性实例流程对新制品复验(脚本可复跑)。
6. B2:删除远端 tag `v0.1.0`,在通过复验的提交上重打,再走 Release 流程。
## 参考链接
- [发布验收待办完成记录](./operation-audit-release-todos-completion.md)
- [Halo 应用市场审核指南](https://docs.halo.run/developer-guide/app-store/app-review-guidelines.md)(`review-guidelines-v2026.09.07`)
- [插件发布验收清单(本地存档)](./plugin-release-checklist.md)
- [Halo 官方插件清单文档](https://docs.halo.run/developer-guide/plugin/basics/manifest.md)
- [Halo 官方 UI 构建输出格式](https://docs.halo.run/developer-guide/plugin/basics/ui/build.md)
- [Halo v2.26.1 YamlPluginDescriptorFinder 源码](https://github.com/halo-dev/halo/blob/v2.26.1/application/src/main/java/run/halo/app/plugin/YamlPluginDescriptorFinder.java)
- [操作审计插件测试报告](./operation-audit-test-report.md)
@@ -0,0 +1,111 @@
# 操作审计插件发布验收待办完成记录
> ⚠️ **已被取代**:本文件记录的是 2026-11-22 针对 commit `81693e4` 制品的待办完成情况。
> 2026-12-05 的第六轮复核针对当前 HEAD(`00c8d3f`)重做了整份清单,结论改为
> **暂不可发布**(2 个代码问题 + 5 项发布流程 / 上架资料阻断),见
> [发布验收清单确认报告 · 六、第六轮复核](./operation-audit-release-checklist-review.md#六第六轮复核2026-12-05commit-00c8d3f--结论暂不可发布)。
> 本文件中的「发布就绪」「CI/CD 已配置」等表述仅代表当时状态,请勿据此发布。
> 对 [验收清单确认报告](./operation-audit-release-checklist-review.md)(首轮确认)列出的
> 6 项待办的执行总结。逐项实测证据的完整记录见
> [测试报告第四轮](./operation-audit-test-report.md)。
>
> - 完成日期:2026-11-22
> - 制品基线:`plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar`
> (commit `81693e4` 干净构建)
> - 当时状态:发布就绪,tag `v0.1.0`(本地,指向 commit `5d05d63`;第六轮查明远端同名 tag
> 也指向该修复前提交,已列为阻断项 B2)
## 一、待办完成总览
首轮确认报告的 6 项待办(2×P0、2×P1、2×P2)全部补齐并复测通过:
| 优先级 | 待办 | 完成方式与结果 | Commit |
| --- | --- | --- | --- |
| P0 | 以正式版本号(非 SNAPSHOT)重新干净构建,复查三处一致 | `clean build -Pversion=0.1.0` 全绿;JAR 文件名 / JAR 内 `plugin.yaml` `spec.version` / Manifest `Implementation-Version` 三处均为 0.1.0 | `81693e4` |
| P0 | 补 CI/CD 工作流 | `.github/workflows/ci.yml` + `cd.yml` 复用官方 `halo-sigs/reusable-workflows@v5` | `44eca75` |
| P1 | 补卸载(uninstall)测试 | 对齐 Console「卸载并删除配置」真实流程实测通过(详见[测试报告](./operation-audit-test-report.md)第四轮) | `753de51` |
| P1 | 2.26.0 最低版本下探实测 | 官方 2.26.0 发布 JAR 全新实例关键路径全部通过(详见[测试报告](./operation-audit-test-report.md)) | `5d05d63` |
| P1 | 发布制品 SHA-256 与发布证据块 | SHA-256 已记录于确认报告[发布证据块](./operation-audit-release-checklist-review.md) | `5d05d63` |
| P2 | 补 `plugin.yaml` 元数据 | `logo.svg` 内置 + `homepage` / `repo` / `issues` / `author.website` / `license.url`(URL 逐一可达性验证) | `81693e4` |
| P2 | UI 输出目录迁移 `ui/` | `processUiResources` 输出至 `resources/main/ui`,JAR 内 `ui/ui-plugin.json` 入口/样式齐备 | `81693e4` |
## 二、关键执行细节
### 1. 正式版本构建与三处一致复查
- `JAVA_HOME="C:/Program Files/Java/jdk-21.0.10" ./gradlew clean build -Pversion=0.1.0`
全绿(后端 + UI 全部检查);
- 复查:`plugin-operation-audit-0.1.0.jar` ↔ `unzip -p … plugin.yaml` 中
`spec.version: "0.1.0"` ↔ Manifest `Implementation-Version: 0.1.0` 一致;
- 制品 SHA-256:`3d2a2ad4…db563`(完整值见确认报告发布证据块)。
### 2. CI/CD 工作流
- CI(push/PR → master):官方可复用工作流 `plugin-ci.yaml@v5`,执行
`./gradlew clean build`(全部测试,不可跳过);
- CD(GitHub Release published):`plugin-cd.yaml@v5`,自动
`./gradlew clean build -x check -Pversion=${tag 去 v 前缀}`,保证 tag ↔ JAR 名 ↔
`spec.version` 一致;`artifacts-path` 限定 `plugin-operation-audit/build/libs`;
`skip-appstore-release: true`(首次上架审核通过前不同步应用市场);
- 适配本仓库布局:官方工作流从仓库根执行 `./gradlew`,而 Gradle 构建根在
`plugin-operation-audit/` 子目录——根目录 `gradlew` / `gradlew.bat` 为转发脚本,
经 `build-args: "-p plugin-operation-audit"` 指定项目目录(委托链路已本地验证);
UI 子项目使用 npm(无 pnpm-lock.yaml),故 `skip-node-setup: true`。
### 3. 卸载(uninstall)生命周期实测(Halo 2.26.1 烟测实例)
- 流程对齐 Console「卸载并删除配置」分支(先经 Halo 2.26.1 源码考证
`use-plugin.ts` 与 `PluginReconciler#cleanupResources`):
停用 → `DELETE` Plugin CR(finalizer 约 24s 清理)→ 删 Setting → 删 ConfigMap;
- 核对结果:CR / JAR / Setting / ConfigMap / RoleTemplate 全部清理;
审计数据保留(重装后 169 → 172 条回归);停用期间 pf4j `disabled.txt`
写入的残留被 Halo 重装启动时自动清除;
- 唯一残留:宿主侧 RoleBinding 孤儿绑定(Halo 平台行为,RoleTemplate 已删、
无授权效果,记录备查)。
### 4. 2.26.0 最低版本下探实测
- 实例:官方 2.26.0 发布 JAR(下载件 sha256 与官方 `.sha256` 逐字符一致),
一次性全新数据目录,测试后停用丢弃;
- 关键路径全部通过:setup / admin 登录(RSA + CSRF 契约)/ install / enable
(STARTED)/ 审计捕获 / query / export / 匿名拒绝 / `ui/` ESM bundle 下发 /
实例日志 0 ERROR;
- 行为差异实测记录:2.26.0 的登录失败返回 **401 JSON**(2.26.1 为
302 → `?error=` 参数),插件认证端点过滤器在两种形态下均正确标注
`login-failure` 语义动作;
- 至此 `spec.requires >=2.26.0` 的实测验证完成(2.26.1 为当前版本复验)。
### 5. manifest 元数据与 ui/ 迁移
- `logo.svg` 置于 `src/main/resources/`(官方插件同款相对路径引用方式);
- `homepage` / `repo` / `issues` 指向仓库托管地址(逐一 curl 验证 200);
- `ui/` 目录为 Halo ≥2.25.0 官方规范输出位置(`console/` 为旧项目兼容回退);
迁移同时清理旧构建残留的 `console/` 目录,防止过期产物入 JAR。
## 三、提交记录
```
5d05d63 docs: 发布验收全部待办完成——2.26.0 下探通过,验收报告更新为发布就绪
753de51 docs: 测试报告补卸载(uninstall)生命周期实测记录
44eca75 ci: 发布验收 P0 项——补齐 CI/CD 工作流
81693e4 chore: 发布验收 P2 项——UI 产物迁至 ui/,补齐 manifest 元数据
tag: v0.1.0 → 5d05d63(本地 annotated tag)
```
## 四、剩余发布动作(发布操作,非验收缺口)
1. 推送 master 与 tag `v0.1.0`;
2. 在代码托管平台创建 GitHub Release(tag `v0.1.0`)——CD 工作流自动构建并
把 JAR 上传为 Release 资产;
3. 发布 commit 的 CI 必须绿色(CD 带 `-x check`,不能替代 CI 与测试);
4. 应用市场首次审核通过后,再按官方发布文档配置 `app-id` 与最小权限的
`HALO_PAT` 令牌开启自动同步。
## 五、环境备注
- Docker Hub 在本机不可达(registry 连接超时),2.26.0 实例改用官方独立 JAR
(经 GitHub release 镜像加速下载,官方 SHA-256 校验通过);
- 本机 `JAVA_HOME` 指向 jre7,所有 Gradle 调用需临时覆盖为 JDK 21;
- 全部测试实例均为一次性数据目录(`workdir` / `workdir-260`),与生产数据无任何
关联,测试完成后停用。
+101
View File
@@ -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 节(已知局限,落地后需同步更新)
+17 -9
View File
@@ -10,7 +10,7 @@
| # | 决策 | 结论 | 理由 | | # | 决策 | 结论 | 理由 |
|---|---|---|---| |---|---|---|---|
| D1 | 捕获通道 | 单一 `AfterSecurityWebFilter`,路径规则为 `/apis/**` 写操作 + `/login` + `/logout` | 登录端点不在 `/apis/**` 下,扩路径匹配而非引入第二套机制 | | D1 | 捕获通道 | 双过滤器分治:`/apis/**` 写操作走 `AfterSecurityWebFilter`;认证操作 `POST /login`、`POST /logout` 走 `BeforeSecurityWebFilter`(Security 链之前) | 表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),链尾过滤器永远看不到认证操作请求,必须在链首承接 |
| D2 | 审计写入方式 | 响应式直写(fire-and-forget),失败静默降级 | WebFlux event loop 上不得阻塞主流程;自用量级无需队列 | | D2 | 审计写入方式 | 响应式直写(fire-and-forget),失败静默降级 | WebFlux event loop 上不得阻塞主流程;自用量级无需队列 |
| D3 | 列表查询 | 优先 Halo 原生列表 API + 索引;时间区间不支持时再开自有查询端点 | 避免内存分页,符合产品设计第 5 节 | | D3 | 列表查询 | 优先 Halo 原生列表 API + 索引;时间区间不支持时再开自有查询端点 | 避免内存分页,符合产品设计第 5 节 |
@@ -21,7 +21,7 @@
| 服务端 | Java 21 + Spring WebFlux(与 Halo 同构) | 由平台 BOM 锁定;保持 Java,与参考插件生态一致 | | 服务端 | Java 21 + Spring WebFlux(与 Halo 同构) | 由平台 BOM 锁定;保持 Java,与参考插件生态一致 |
| 构建 | Gradle(Groovy DSL,跟随官方 starter)+ `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0 | 以 `plugin-starter` 模板初始化 | | 构建 | Gradle(Groovy DSL,跟随官方 starter)+ `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0 | 以 `plugin-starter` 模板初始化 |
| 存储 | 自定义 Extension(`AuditLog`)+ 索引查询 | 不接外部数据库,建表/备份/连接池问题全部消失 | | 存储 | 自定义 Extension(`AuditLog`)+ 索引查询 | 不接外部数据库,建表/备份/连接池问题全部消失 |
| 捕获通道 | `AfterSecurityWebFilter` 扩展点(实现 `WebFilter`,注册在 Security 链之后) | 产品文档第 8 节已源码级验证 | | 捕获通道 | `AfterSecurityWebFilter` + `BeforeSecurityWebFilter` 扩展点(实现 `WebFilter`,分别注册在 Security 链最后与最前) | 产品文档第 8 节已源码级验证;P0 缺陷实证双通道必要性 |
| 客户端 | `ReactiveExtensionClient` | 全程非阻塞,符合设计原则 4 | | 客户端 | `ReactiveExtensionClient` | 全程非阻塞,符合设计原则 4 |
| Console UI | Vue 3 + TypeScript + Vite + `@halo-dev/components` | 官方插件前端模板即此;不引入额外状态管理,组件内 `ref` 足够 | | Console UI | Vue 3 + TypeScript + Vite + `@halo-dev/components` | 官方插件前端模板即此;不引入额外状态管理,组件内 `ref` 足够 |
| 设置页 | `settings.yaml` 声明式声明 | Console 自动渲染,零前端代码 | | 设置页 | `settings.yaml` 声明式声明 | Console 自动渲染,零前端代码 |
@@ -51,12 +51,15 @@ plugin-operation-audit/
│ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8) │ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8)
│ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName) │ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName)
│ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试) │ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试)
│ │ │ ├── LoginOutcome.java # 登录成败判定:状态码 + 重定向目标是否跳回登录页(纯函数)
│ │ │ ├── AuditResult.java # 结果语义:成功 / 失败 / 页面访问(筛选与 CSV 共用,纯函数)
│ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数) │ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数)
│ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照 │ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态) │ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级) │ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义) │ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
│ │ │ ├── OperationAuditWebFilter.java │ │ │ ├── AuthEndpointAuditWebFilter.java # 认证操作捕获(BeforeSecurityWebFilter,链首,仅 POST)
│ │ │ ├── OperationAuditWebFilter.java # /apis/** 捕获(AfterSecurityWebFilter,链尾)
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志 │ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
│ │ └── housekeeping/ │ │ └── housekeeping/
│ │ └── RetentionCleaner.java # 定时清理 │ │ └── RetentionCleaner.java # 定时清理
@@ -77,14 +80,17 @@ plugin-operation-audit/
## 4. 核心设计决策 ## 4. 核心设计决策
### D1 捕获通道与路径规则 ### D1 捕获通道与路径规则(P0 修订)
- 实现一个 `WebFilter`,以 `AfterSecurityWebFilter` 扩展点方式注册(位于 Security 过滤链最后、认证之后,`doFinally` 可读最终响应状态码)。 - 双过滤器分治(P0 缺陷实证后修订):
- **`/apis/**` 写操作**:`AfterSecurityWebFilter` 扩展点(位于 Security 过滤链最后、认证之后,可获取当前登录用户,`doFinally` 可读最终响应状态码)。
- **认证操作 `POST /login`、`POST /logout`**:`BeforeSecurityWebFilter` 扩展点(位于 Security 过滤链最前,`SecurityWebFiltersOrder.FIRST`)。P0 根因:表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证操作请求——POST /login、/logout 曾永不产生审计记录,登录失败告警生产路径随之失效。
- 捕获规则(`CaptureRule`,纯函数): - 捕获规则(`CaptureRule`,纯函数):
- `POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/` - `shouldCapture`:`POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`(链尾过滤器消费)
- 或路径精确匹配 `/login`、`/logout` - `isAuthOperation`:`POST /login` 与 `POST /logout`(链首过滤器消费)——两个过滤器按规则分治、互不重叠,不会重复记录。`isAuthEndpoint`(路径精确匹配 `/login`、`/logout`)仅用于路径归类:登录/登出页面的 GET 访问不是操作,原样透传不记录(现场反馈:页面访问落库成「未知用户 · 登录 200」,列表里全是成功、真正的登录成败被淹没)
- 匿名判断**不在请求期做,而在记录时做**:登录请求开始时用户必然匿名,只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致。 - 操作者归属:`/apis/**` 请求从认证上下文解析;认证操作在链首无认证上下文(SecurityContext 由链内更晚位置写入),统一记"未知用户",登录尝试的账号由请求体白名单提取落库 `spec.attemptedUsername`。
- 该规则是产品设计"一条通用规则覆盖全部管理面操作"的唯一必要例外(登录端点不在 `/apis/**` 下),需在产品文档中同步注明。 - 匿名判断**不在请求期做,而在记录时做**(技术方案 D1):只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致;认证操作记录不判匿名。
- 回归防线:真实 Spring Security 过滤链集成测试(`AuditFilterChainIntegrationTest`,按 Halo `SecurityWebFiltersConfigurer` 的组装方式构建),断言 POST /login(成败)、POST /logout 必产生记录,登录/登出页面的 GET 访问全链不记录。
### D2 审计写入:响应式直写 ### D2 审计写入:响应式直写
@@ -211,6 +217,8 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
``` ```
- `operatorOf(ctx)`:从订阅上下文读 `SecurityContext`;主体为匿名且路径非登录端点 → 不记录;登录失败 → 记"未知用户"。 - `operatorOf(ctx)`:从订阅上下文读 `SecurityContext`;主体为匿名且路径非登录端点 → 不记录;登录失败 → 记"未知用户"。
- 登录成败判定(`LoginOutcome`,纯函数):Halo 2.26.1 登录端点**表单提交的成功与失败均为 302 重定向**(`LoginSuccessHandler` → `/uc`、已保存的原请求或 2FA 页;`LoginFailureHandler` → `/login?error=invalid-credential|account-disabled|rate-limit-exceeded&method=...`),仅 XHR/JSON 请求以 200/401 区分成败——不能只看状态码。规则:**只有响应明确确认才算成功**——2xx 成功;3xx 以重定向目标是否跳回登录页判定(路径即 `/login`,或查询串含 `error` 参数;缺失 Location 同样无法确认成功);其余(401、403、状态码缺失)失败。失败的登录尝试(`POST /login`)标注语义动作 `login-failure`(`spec.action`)。告警服务(`LoginFailureAlertService`)按同一判定结果清零/累计。
- 结果语义(`AuditResult`,纯函数;结果筛选 `AuditLogFilters`、CSV 导出与前端 `audit.ts` 共用同一规则):登录失败(标注 `login-failure`)为失败;认证端点的页面访问(非 POST 的 `/login`、`/logout`,仅升级前落库的历史记录)不计成败;其余按状态码 2xx/3xx 判成功。展示:登录失败红色「失败」、登录成功绿色「成功」(表单登录成败同为 302,裸状态码读不出成败)、页面访问灰色「—」并描述为「访问登录页/登出页」(`OperationDescription.semanticAction` 按方法纠正历史记录的 `login`/`logout` 标注,标注本身不改写)。
- 注意 WebFlux 无 ThreadLocal:用户名提取必须经 `transformDeferredContextual` 在订阅上下文完成,不能在 `doFinally` 里直接读 `SecurityContextHolder`。 - 注意 WebFlux 无 ThreadLocal:用户名提取必须经 `transformDeferredContextual` 在订阅上下文完成,不能在 `doFinally` 里直接读 `SecurityContextHolder`。
### 5.2 资源解析规则(通用,不追求语义完美) ### 5.2 资源解析规则(通用,不追求语义完美)
+744
View File
@@ -0,0 +1,744 @@
# 操作审计插件测试报告
> 依据 [plugin-testing.md](./plugin-testing.md) 的分层验证流程执行,覆盖源码级自动化检查、
> 真实 Halo 安装联调与浏览器级 UI 验证。
>
> - 测试日期:2026-11-22
> - 被测插件:`plugin-operation-audit` 0.1.0-SNAPSHOT(commit `34764c7`,master)
> - 结论速览:**自动化检查全部通过;JAR 安装联调发现 1 个 P0 功能缺陷**
> (POST /login、/logout 永不达审计过滤器),详见[缺陷记录](#p0-缺陷post-loginlogout-永不产生审计记录登录失败告警生产路径失效)。
>
> **修复状态(2026-11-22 更新)**:P0 已按本报告修复方向修复(commit `f4d1200`)——
> 认证端点改由 `BeforeSecurityWebFilter` 在 Security 链最前捕获(新增
> `AuthEndpointAuditWebFilter`),并按修复方向补充真实过滤链集成测试。真实 Halo 2.26.1
> 复测:浏览器表单登录(错误密码 302→error、正确密码 302→/uc)与登出均产生审计记录、
> Console 登录失败红色标注正常;回归期间额外发现并修复了首版修复的
> "缓存请求体导致 CSRF 表单参数通道失效(登录页 403)"缺陷(commit `f4d1200` 内),
> 已以"启用 CSRF + 表单参数令牌"的集成测试锁死。
> **复测状态(2026-11-22 第二轮,commit `99bd109`)**:全量自动化检查与真实 Halo
> 联调冒烟再次全部通过,详见[复测记录](#复测记录2026-11-22-第二轮commit-99bd109)。
> **复测状态(2026-11-22 第三轮,commit `fd3ea71`)**:全量自动化检查与真实 Halo
> 联调(含多角色权限矩阵与生命周期往返)再次全部通过,详见
> [复测记录](#复测记录2026-11-22-第三轮commit-fd3ea71)。
> **复测状态(2026-12-05 第五轮,commit `fc79842`)**:针对生产反馈「登录失败也显示成功」
> 的修复——登录页的 GET 访问不再记为登录,登录成败以响应确认为准;自动化检查与真实 Halo
> 2.26.1 升级场景复测通过,详见[复测记录](#复测记录2026-12-05-第五轮commit-fc79842)。
> **复测状态(2026-12-05 第六轮,发布制品复核,commit `00c8d3f`)**:对当前 HEAD 的正式版
> 制品(`0.1.0`)按测试指南与发布验收清单重做一遍验收——Halo 2.26.0 / 2.26.1 / 2.27.4 上的
> 安装、启停、重启、升级、卸载、权限矩阵、SSRF、告警路径与 Console 页面全部通过;同时查出
> **2 个必须先修复的问题**(敏感字段脱敏仅覆盖 `password/secret/token/credential` 命名、
> 入库的 API client 不是生成器产物)与若干发布流程阻断。**结论:暂不可发布**,详见
> [第六轮复测记录](#复测记录2026-12-05-第六轮发布制品复核commit-00c8d3f) 与
> [发布验收清单确认报告](./operation-audit-release-checklist-review.md)。
## 可复核结果
```text
Commit: 34764c7 (master, 测试期间诊断代码已全部回滚,工作区干净)
Halo versions tested: 2.26.1(官方独立 JAR;plugin.yaml 声明 requires >=2.26.0)
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain 自动选定;本机 JAVA_HOME
指向 jre7,每次 Gradle 调用需临时覆盖 JAVA_HOME)、
Node v24.19.0、pnpm 11.22.0(项目 UI 实际使用 npm)
Commands run: ./gradlew test --rerun、./gradlew :ui:testFrontend :ui:buildFrontend、
./gradlew check、./gradlew clean build;
Halo 安装/启用/停用/升级/重启等 API 调用(见下方联调章节)
Automated checks: PASS(后端 265/265,UI 69/69,类型检查与构建通过)
Roles and dependency states: admin(超级管理员全量权限)与 auditor3(仅授予
role-template-audit-view)两个角色实测
Manual paths checked: 安装→启用→审计捕获→查询/导出→停用→升级→重启恢复→
权限矩阵→Console 桌面与 390px 窄屏人工检查
Known limitations: 见文末"未覆盖项"
```
## 一、自动化检查(全部通过)
| 检查项 | 命令 | 结果 |
| --- | --- | --- |
| 后端 JUnit 5 | `./gradlew test --rerun`(强制重跑,避免缓存假绿) | **24 个测试类 / 265 个测试全部通过**,0 skipped / 0 failures / 0 errors |
| UI 单元测试 | `./gradlew :ui:testFrontend`(vitest) | **9 个 spec / 69 个测试全部通过** |
| UI 类型检查与构建 | `./gradlew :ui:buildFrontend`(vue-tsc + vite) | 通过;bundler kit 输出 ESM,共享依赖对齐 Halo 2.26.0 |
| 完整检查生命周期 | `./gradlew check` | 通过(UI build/test 已接入 check) |
| 发布前干净构建 | `./gradlew clean build` | 通过;产物 `build/libs/plugin-operation-audit-0.1.0-SNAPSHOT.jar` |
### JAR 打包内容核验
`unzip -l` 核对产物:
- `plugin.yaml`、`extensions/role-template.yaml`、`extensions/settings.yaml` 齐全;
- `console/main.Bwbl9zw-.js`、`console/assets/index.UH34KxXN.css` 的 hash 与本次
vite 构建输出一致,确认 `processUiResources` 的"先清空再拷贝"策略有效,无历史版本残留;
- `console/ui-plugin.json` 与 `META-INF/plugin-components.idx` 就位。
### 生成 API 客户端差异审查
- 生成产物 20 个文件全部入库(`ui/src/api/generated/`),`git status` 干净,无手改痕迹;
- 生成客户端 3 个端点与后端 `SpringdocRouteBuilder` 声明逐一比对:
`GET auditlogs/-/query`、`GET auditlogs/-/export`、`POST alerts/-/test`;
- 与 `build.gradle` groupingRules 的 `pathsToMatch` 一致;UI 封装层
(`ui/src/api/index.ts`)复用宿主 `axiosInstance`,未自建 Axios 客户端。
## 二、真实 Halo 安装联调
**环境**:Docker 不可用,DevTools `haloServer` 无法运行。改用 Halo 2.26.1 官方独立 JAR
(`java -jar halo-2.26.1.jar --halo.work-dir=<一次性目录> --server.port=8099`,H2 内置库),
等效覆盖"最终 JAR 安装验证"层级。数据目录为一次性测试目录,未使用任何生产数据。
| 生命周期节点 | 操作方式 | 结果 |
| --- | --- | --- |
| 安装 | `POST /apis/api.console.halo.run/v1alpha1/plugins/install`(multipart) | 200,JAR 落至 workdir/plugins |
| 启用 | `PUT plugins/operation-audit` 更新 `spec.enabled` | STARTED;插件自身启用的写操作即被审计捕获 |
| 审计捕获(HTTP 通道) | admin 的 `PUT/POST /apis/**` 写操作 | 正常记录(含 404 失败路径、语义动作、状态码、IP、UA) |
| 审计捕获(内部变更通道) | 系统角色模板 reconcile、通知订阅清理等 | 记录为 `system` 执行者,归属正确 |
| 查询/导出 | `GET auditlogs/-/query`、`/-/export` | 200,数据与筛选正常 |
| 停用/启用 | `PUT spec.enabled=false/true` | 正常;停用期间查询端点随插件下线 |
| 重启恢复 | 杀进程后重启 Halo | 插件自动恢复 STARTED(`spec.enabled=true` 持久化生效),**历史审计数据完整保留** |
| 升级 | 换 JAR 后重启(详见 Windows 限制) | 新 JAR 生效 |
### 权限矩阵(不同角色实测)
预置 `auditor3` 用户,仅授予 `role-template-audit-view`(verbs 仅 get/list):
| 请求 | 期望 | 实测 |
| --- | --- | --- |
| auditor3 `GET auditlogs/-/query` | 200 | **200** ✅ |
| auditor3 `GET auditlogs/-/export` | 200 | **200** ✅ |
| auditor3 `DELETE /apis/audit.guichumo.com/v1alpha1/auditlogs/{name}` | 403 | **403** ✅(只读角色技术上无法删除审计记录) |
| auditor3 `POST alerts/-/test` | 403 | **403** ✅ |
| auditor3 `GET /apis/api.console.halo.run/v1alpha1/users`(越权探测) | 403 | **403** ✅ |
| 匿名 `GET auditlogs/-/query` | 拒绝 | **302 → /login** ✅ |
### 浏览器级 UI 验证(桌面 + 窄屏人工检查)
使用真实浏览器登录 Console 逐项检查,截图存于仓库 `docs/assets/gui-test-screenshots/`:
- 菜单入口:`plugin` 分组下出现「操作审计」,选中态高亮正确(t1);
- 列表页(1280px):筛选区(操作者/资源类型/动作/语义动作/结果/关键字/起止时间)、
动作徽标(DELETE 红 / POST 蓝 / PUT 橙 / GET 灰)、结果徽标(200)、历史链接、
IP 列均正常渲染;真实审计数据即时可见(t1);
- 窄屏(390px):筛选栏单列堆叠(≤480px 断点,符合 34764c7 修订后的设计)、
表格进入横向滚动容器且题头与数据列对齐同步(t3、t4);
- 插件设置页:审计设置/告警通知两组表单正常回显当前 ConfigMap 值;
自定义 FormKit 输入「发送测试告警」按钮注册成功并渲染(t5);Secret 选择器
正确展示已创建的 Secret 及 `包含字段: webhookUrl`;
- 全程无可见页面错误(本浏览器运行时不支持只读 console 采集,以页面可见表现为准)。
### SSRF 防护实测(出站地址校验)
- 配置回环地址 Webhook(`http://127.0.0.1:8199/hook`)后调用测试告警端点:
正确拒绝,返回 `success:false` 与明确中文原因"Webhook 主机解析到受限网络地址
(环回/内网/链路本地/云元数据等),已拒绝"——`OutboundUrlGuard` 端到端生效;
- 完整投递链路(真实送达接收端)需公网 Webhook,为避免向外部服务发送数据而**未执行**。
## P0 缺陷:POST /login、/logout 永不产生审计记录,登录失败告警生产路径失效
### 现象(稳定复现,跨全新数据库、跨重启)
| 请求 | 记录情况 |
| --- | --- |
| `GET /login`(登录页访问) | ✅ 有记录(anonymousUser, action=login) |
| **`POST /login` 成功(302 → /uc)** | ❌ **无记录** |
| **`POST /login` 失败(302 → /login?error=invalid-credential)** | ❌ **无记录** |
| **`POST /logout`(302 → /login?logout)** | ❌ **无记录** |
| `PUT/POST /apis/**`(含 404 失败路径) | ✅ 正常记录 |
| 内部变更通道(reconcile 等) | ✅ 正常记录(system) |
同期验证排除项:登录主流程未被破坏(插件启用后正确密码仍可登录);无任何 WARN/DEBUG
日志(静默失败);告警设置启用且 Secret 已配置时,阈值窗口仍未触发任何告警路径日志。
### 根因(诊断日志实证)
`OperationAuditWebFilter` 经 `AfterSecurityWebFilter` 扩展点注册,位于 Security 过滤链
**内部**、认证环节之后。临时加入 `filter enter` / `doFinally` / `operator` 三处诊断日志并
实测(Halo 2.26.1):
- `GET /login`:`filter enter` → `doFinally` → `operator resolved` 完整链路,记录成功;
- **`POST /login`:过滤器 `filter()` 从未被调用(无 `filter enter` 日志)**——表单登录/
登出过滤器命中请求后直接完成 302 响应,不再向下游传递,审计过滤器永远看不到该请求;
- `POST /logout` 同理。
因此 doFinally 中的审计记录与**登录失败告警回调**(同一入口,`LoginFailureAlertService`
回调)在生产路径上均为死代码。265 个单元测试全绿,是因为组件隔离测试未覆盖过滤器与
安全链的集成(`LoginOutcome`、告警窗口逻辑等单测均直接驱动组件,不经过真实过滤链)。
### 修复方向(建议)
为 `/login`、`/logout` 注册一个独立的普通 `WebFilter`(位于 Security 过滤链之前)承接
认证端点的捕获与记录(操作者解析对匿名/未知场景本就有兜底路径);`/apis/**` 捕获保留
现有 `AfterSecurityWebFilter` 注册以继续获得认证用户上下文。同时补充一条真实过滤链
集成测试(至少断言 POST /login 会产生记录),防止回归。
### 复现命令(脱离本报告可独立复跑)
```bash
# 1. 启动干净实例(一次性数据目录)
java -jar halo-2.26.1.jar --halo.work-dir=<tmp> --server.port=8099
# 2. 初始化系统并安装启用插件(POST /system/setup、POST .../plugins/install、PUT spec.enabled=true)
# 3. 任一次 POST /login(成功或失败均可)
# 4. 对比:GET /apis/audit.guichumo.com/v1alpha1/auditlogs 中只有 GET /login 记录,无 POST 记录
```
## 其他发现(低优先级)
1. **Windows 上插件 JAR 被运行实例锁定**:`upgrade` API 报 500
(`FileSystemException: 另一个程序正在使用此文件`),停用插件后句柄仍不释放,只能停服
换 JAR。属 Halo on Windows 的环境限制,建议在 README 记录 Windows 升级注意事项。
2. `testAlert` 端点对非法地址的失败反馈体验良好(结构化 `success:false` + 原因),可保持。
3. 本机环境注意:`JAVA_HOME` 指向 `jre7`,Gradle 调用需临时覆盖为 JDK 21
(`JAVA_HOME="C:/Program Files/Java/jdk-21.0.10" ./gradlew ...`)。
## 未覆盖项
- Webhook 公网投递链路(需外部接收端,未向外部服务发送数据);
- 卸载(uninstall)测试;
- `spec.requires` 最低版本 2.26.0 的实测(仅测 2.26.1,未按官方建议"不得仅凭编译成功
推断兼容范围"下探到最低版本);
- 其他浏览器/设备兼容性(仅 Chromium 内核桌面与 390px 视口);
- DevTools `haloServer` / `watch` 开发工作流(Docker 不可用)。
## 复测记录(2026-11-22 第二轮,commit `99bd109`)
P0 修复(`f4d1200`)合入后的全量复测。自动化检查逐层执行,真实 Halo 联调在既有
一次性冒烟实例(8099)上完成。
```text
Commit: 99bd109 (master,工作区干净,仅文档)
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8099 冒烟实例,H2 内置库)
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain;本机 JAVA_HOME 指向 jre7,
每次 Gradle 调用临时覆盖 JAVA_HOME)、Node v24.19.0、
npm 11.22.0(UI 子项目实际使用 npm,无 pnpmCheck 任务,
等效检查为 :ui:testFrontend + :ui:buildFrontend,已接入 check)
Commands run: ./gradlew test --rerun、./gradlew :ui:check --rerun、
./gradlew check、./gradlew clean build、
./gradlew haloServer(失败,见 Known limitations);
联调冒烟:真实登录/登出/查询/导出/告警测试端点调用
Automated checks: PASS(后端 270/270,0 失败 0 跳过;UI vitest 69/69;
vue-tsc 类型检查与 vite 构建通过;check 与 clean build 通过)
Roles and dependency states: 本轮仅 admin;无权限路径以匿名会话验证(查询端点 302 拒绝)。
多角色矩阵由上一轮(34764c7/f4d1200 报告)覆盖
Manual paths checked: 插件自重启恢复(实例 18:45 重启后插件自动 STARTED);
失败登录→login-failure 记录(attemptedUsername=admin,302);
成功登录→login 记录;登出→logout 记录(302→/login?logout);
登出后查询会话权限即时回收;无效分页参数(page=-1&size=0)
归一化不 500;导出 CSV 表头与数据完整;告警测试端点对
环回地址返回结构化失败(OutboundUrlGuard 拦截);
服务端日志 0 ERROR
Known limitations: DevTools haloServer/pullHaloImage 因本机无 Docker 失败
(java.nio.file.NoSuchFileException: \\.\pipe\docker_engine),
联调以独立 JAR 实例替代完成;Windows 上升级 API 因 JAR
文件锁仍需停服换 JAR(上轮已记录的环境限制)
```
### 联调冒烟结果明细(对照 plugin-testing.md 检查清单)
| 检查项 | 实测 | 结果 |
| --- | --- | --- |
| 插件能够启动、日志无未处理错误 | 重启后自动 STARTED;`halo-restart2.log` 0 条 ERROR | 通过 |
| 登录/登出审计(P0 修复路径) | 失败登录记 `login-failure`(attemptedUsername=admin)、成功登录记 `login`、登出记 `logout`(302) | 通过 |
| 操作者归属语义 | 认证端点记录统一 `username=unknown` + `attemptedUsername`(链首无认证上下文,`AuthEndpointAuditWebFilter` Javadoc 声明的设计行为,非缺陷) | 符合设计 |
| API 成功路径 | query(115→121 条,分页/排序正常)、export(200,29KB CSV) | 通过 |
| 无权限路径 | 匿名访问 query 端点被 302 重定向拒绝,登出后原会话权限即时失效 | 通过 |
| 无效输入 | `page=-1&size=0` 被归一化处理(无 500) | 通过 |
| 依赖失败路径 | `POST alerts/-/test`:webhook 指向环回地址被 OutboundUrlGuard 拒绝,返回结构化 `success:false` + 原因 | 通过 |
| 配置/重启生效 | 实例 18:45 重启后插件自动恢复 STARTED,历史审计数据保留(累计 121 条) | 通过 |
> 本轮新增核对项:GET /login 页面访问也产生 `login`(HTTP 200)记录——属
> `isAuthEndpoint` 设计内覆盖(失败回显 `?error=...` 会被标注登录失败),非噪声缺陷。
>
> ⚠️ **此判断已于 2026-12-05 第五轮推翻**(commit `fc79842`):对登录页的 GET 访问不是
> 登录事件,却被记成绿色「登录 200」,正是生产反馈「登录失败也显示成功」的根因;现已改为
> 只记录 `POST /login`、`POST /logout`,详见
> [第五轮复测记录](#复测记录2026-12-05-第五轮commit-fc79842)。
## 复测记录(2026-11-22 第三轮,commit `fd3ea71`)
按 [plugin-testing.md](./plugin-testing.md) 分层流程的第三次全量复测。源码自 `99bd109`
以来仅有文档改动,本轮同时验证自动化管线、JAR 制品、真实 Halo 联调与多角色权限。
```text
Commit: fd3ea71 (master,工作区干净,仅文档改动)
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8099 冒烟实例,H2 内置库,
一次性数据目录,与生产数据无任何关联)
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain;本机 JAVA_HOME 指向 jre7,
每次 Gradle 调用临时覆盖 JAVA_HOME)、Node v24.19.0、
npm 11.17.0(UI 子项目实际使用 npm,无 pnpmCheck 任务,
等效检查为 :ui:testFrontend + :ui:buildFrontend)、
pnpm 11.22.0 已安装但未被本项目使用
Commands run: ./gradlew test --rerun、./gradlew :ui:testFrontend
:ui:buildFrontend --rerun、./gradlew check、
./gradlew clean build;
联调:实例重启恢复、RSA 加密登录(失败+成功)、登出、
query/export、匿名与 auditor3 权限矩阵、无效分页参数、
告警测试端点(环回拒绝)、停用→启用往返
Automated checks: PASS(后端 26 类/270 全过,0 失败 0 跳过;UI vitest 69/69;
vue-tsc 类型检查与 vite 构建通过;check 与 clean build 通过)
Roles and dependency states: admin(全量权限)与 auditor3(仅 role-template-audit-view,
verbs get/list)实测;无权限路径另以匿名会话验证
Manual paths checked: 重启后插件自动 STARTED 且历史数据保留(121→167 条);
失败登录(含 403 CSRF 拦截与 302 invalid-credential 两类)
→login-failure(attemptedUsername=admin);
成功登录→login(302→/uc);GET /logout 确认页→logout(200,
设计内);POST /logout→logout(302→/login?logout)且原会话
权限即时回收;匿名 query 302 拒绝;auditor3 矩阵 5/5
(query 200 / export 200 / POST test 403 / DELETE 403 /
越权 GET users 403);page=-1&size=0 归一化不 500;
导出 CSV 200(35KB,表头+数据完整);告警测试端点对环回
地址返回结构化 success:false;停用→query 404→启用→
STARTED→query 200;Console bundle 静态资源(入口 JS/CSS)
经 /plugins/{name}/assets/console/ 正常下发;
服务端日志 0 ERROR
Known limitations: DevTools haloServer 因本机无 Docker 不可用(同前两轮);
Webhook 公网投递、卸载测试、spec.requires 下探 2.26.0
仍未执行(见"未覆盖项");Windows 升级 API JAR 文件锁
环境限制未变(本轮未再触发升级)
```
### 联调冒烟结果明细(对照 plugin-testing.md 检查清单)
| 检查项 | 实测 | 结果 |
| --- | --- | --- |
| 插件能够启动、日志无未处理错误 | 重启后自动 STARTED;`halo-round3.log` 0 条 ERROR | 通过 |
| 登录/登出审计(P0 修复路径回归) | 失败登录两类(403 CSRF 拦截、302 invalid-credential)均记 `login-failure`(attemptedUsername=admin);成功登录记 `login`(302→/uc);POST /logout 记 `logout`(302→/login?logout),GET /logout 确认页也记 `logout`(200,`isAuthEndpoint` 设计内) | 通过 |
| 操作者归属语义 | 认证端点记录统一 `username=unknown` + `attemptedUsername`(链首无认证上下文,设计行为,非缺陷) | 符合设计 |
| API 成功路径 | query(分页/筛选正常,总数 167 持续增长)、export(200,35KB CSV,UTF-8 BOM+中文表头) | 通过 |
| 无权限路径 | 匿名 query 302 重定向拒绝;auditor3 越权 GET users 403 | 通过 |
| 多角色权限矩阵(auditor3,仅 role-template-audit-view) | query 200 / export 200 / POST alerts test 403 / DELETE auditlog 403 / 越权探测 403,**5/5 符合预期**;角色绑定跨重启持久生效 | 通过 |
| 无效输入 | `page=-1&size=0` 归一化处理,无 500 | 通过 |
| 依赖失败路径 | `POST alerts/-/test` webhook 指向环回地址被 OutboundUrlGuard 拒绝,返回结构化 `success:false` + 中文原因 | 通过 |
| 登录失败告警生产路径 | 失败登录后 `AlertWebhookSender` 实际发起投递(日志 2 条 WARN),因配置的 webhook 为环回地址被出站防护拦截——回调链路真实生效,仅受测试配置所限未送达 | 通过 |
| 配置/重启生效 | 实例重启后告警 webhook 配置(上轮残留的环回地址)仍生效并触发投递尝试;角色绑定、启用状态持久化恢复 | 通过 |
| 生命周期:停用/启用往返 | 停用→phase DISABLED、query 端点 404 下线;启用→phase STARTED、query 恢复 200;历史数据完整保留 | 通过 |
| Console 入口资源 | `ui-plugin.json` 与 hash 文件名入口 JS(21,356B)、CSS(7,375B)经 `/plugins/operation-audit/assets/console/` 正常下发 | 通过 |
### 本轮联调协议要点(影响可复现性,记录备查)
- **登录协议**:Halo 2.26 的 `POST /login` 要求密码经登录页内嵌 RSA 公钥
(jsencrypt,PKCS#1 v1.5)加密后提交;明文密码提交必然返回
`invalid-credential`(服务端解密失败),并非密码错误。
- **CSRF 豁免范围**:仅 `/api/**`、`/apis/**`、`/actuator/**`、`/system/setup`
豁免;`/login`、`/logout` 均要求 CSRF。表单流程必须提交页面渲染的
XOR 编码 `_csrf` 隐藏域值(将 `XSRF-TOKEN` cookie 值直接以 `X-XSRF-TOKEN`
头回传**不能**通过校验);`GET /logout` 返回含 `_csrf` 的确认表单,POST
/logout 应以该值提交。
- Console bundle 静态资源路径为 `/plugins/{name}/assets/console/...`,
入口文件名为 vite 产物 hash 名(以 `ui-plugin.json` 的 `entry` 为准)。
- API 层面 403 为纯文本 `Access Denied`(Spring 默认 AccessDeniedHandler),
无结构化响应体,前端需自行处理展示。
## 复测记录(2026-11-22 第四轮:发布验收补测,commit `81693e4`/`44eca75`)
发布验收清单 [plugin-release-checklist.md](./plugin-release-checklist.md) 确认报告的 P1/P2
待办补测。本轮覆盖:0.1.0-SNAPSHOT→0.1.0 正式版升级、**卸载(uninstall)生命周期**、
卸载后重装闭环,另补齐 manifest 元数据与 `ui/` 输出迁移。
```text
Commit: 81693e4(UI ui/ 迁移+manifest 元数据)/ 44eca75(CI/CD 工作流)
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8099 烟测实例,H2 内置库)
与 2.26.0(最低版本下探一次性全新实例,见下节);
数据目录均为一次性目录,与生产数据无任何关联
Java, Node.js and pnpm versions: Java 21.0.10(Gradle toolchain;本机 JAVA_HOME 指向 jre7,
每次 Gradle 调用临时覆盖 JAVA_HOME)、Node v24.19.0、npm
Automated checks: PASS(clean build -Pversion=0.1.0 全绿;后端+UI 检查同 check)
Manual paths checked: 正式版升级(upgrade API,0.1.0-SNAPSHOT→0.1.0,历史 169 条
数据保留);卸载全流程(对齐 Console"卸载并删除配置"路径:
停用→DELETE Plugin CR→删 Setting/ConfigMap);卸载后核对
(CR/JAR/Setting/ConfigMap/RoleTemplate 清理、RoleBindings
残留、auditlog 端点 404、日志 0 ERROR);重启后无插件残留;
重装 0.1.0(install API→enable→STARTED,审计数据 169→172
条完整回归,pf4j disabled.txt 残留被 Halo 自动清除)
Known limitations: 2.26.0 最低版本下探已于本节补充执行并通过;Windows 升级 JAR
文件锁环境限制未变(本轮 upgrade API 实测正常,旧 JAR 未被锁)
```
### 卸载(uninstall)生命周期核对(对照 plugin-testing.md 第 6 步)
**卸载前快照**(Halo 2.26.1,0.1.0 STARTED):
| 资源 | 状态 |
| --- | --- |
| Plugin CR `operation-audit`(0.1.0,STARTED,169 条审计数据) | ✅ |
| Setting `operation-audit-settings` / ConfigMap `operation-audit-configmap` | ✅ 200 |
| RoleTemplate `role-template-audit-view` | ✅ 200 |
| RoleBindings(auditor3 等 2 个绑定 role-template-audit-view) | ✅ 200 |
| JAR `plugins/operation-audit-0.1.0.jar` | ✅ 存在 |
**卸载操作**(对齐 Console「卸载并删除配置」分支,经查证 Halo 2.26.1 源码
`use-plugin.ts` + `PluginReconciler#cleanupResources`):
1. `PUT /apis/api.console.halo.run/v1alpha1/plugins/operation-audit/plugin-state`(enable=false)→ 200;
2. `DELETE /apis/plugin.halo.run/v1alpha1/plugins/operation-audit` → 200
(finalizer `plugin-protection` 异步清理,约 24s 完成);
3. `DELETE /api/v1alpha1/settings/operation-audit-settings` → 200;
4. `DELETE /api/v1alpha1/configmaps/operation-audit-configmap` → 200。
**卸载后核对**:
| 核对项 | 结果 | 判定 |
| --- | --- | --- |
| Plugin CR(GET) | 404 | ✅ 已删除(finalizer 清理完成) |
| JAR(workdir/plugins) | 文件已删除 | ✅ reconciler 清理 |
| Setting / ConfigMap | 404 | ✅ 已删除 |
| RoleTemplate `role-template-audit-view` | 404 | ✅ 已随插件卸载清理 |
| RoleBindings(auditor3 等) | **残留 2 个** | ⚠️ Halo 不清理宿主侧 RoleBinding;RoleTemplate 已删,绑定无实际授权效果,但管理端可见孤儿绑定 |
| AuditLog 查询端点 | 404 | ✅ 随插件下线(扩展模型 scheme 注销) |
| **审计数据(H2 内)** | 保留 | ✅ Halo 不删除插件自定义扩展数据;卸载后不可见、重装后回归 |
| 重启 Halo 后 | 无插件加载、日志 0 ERROR、无残留 JAR | ✅ |
| **重装 0.1.0**(install API → enable) | STARTED;审计数据 169→172 条完整回归;**停用期间 pf4j `disabled.txt` 写入的 `operation-audit` 残留被 Halo 启动插件时自动清除** | ✅ 闭环 |
**卸载结论**:Halo 2.26.1 卸载语义下,本插件卸载行为符合预期——运行时资源
(JAR)释放、预置资源(Setting/ConfigMap/RoleTemplate)清理、审计数据保留
(重装后回归),无不可恢复的破坏性影响;唯一残留是宿主侧 RoleBinding 孤儿绑定
(Halo 平台行为,非本插件可管理范围,重启不影响其他功能,可接受并记录)。
### 2.26.0 最低版本下探实测(官方发布 JAR,一次性全新实例)
对应验收清单第 7 步"在声明范围内的最低 Halo 版本上重复关键路径"。制品为同一次
干净构建的 `plugin-operation-audit-0.1.0.jar`(SHA-256 见发布证据块);Halo 2.26.0
官方独立 JAR(GitHub release 资产,`sha256sum` 与官方 `halo-2.26.0.jar.sha256`
逐字符一致),一次性数据目录 `workdir-260`(未初始化生产数据,测试后已停用丢弃)。
| 检查项 | 实测 | 结果 |
| --- | --- | --- |
| 系统初始化 | `POST /system/setup`(form-urlencoded,含 siteTitle/externalUrl) | 302 ✅ |
| admin 登录 | RSA + `_csrf` 表单契约(同 2.26.1) | 302 ✅ |
| 插件安装 | install API 上传 0.1.0 JAR | 200 ✅ |
| 插件启用 | CR phase | **STARTED** ✅ |
| 审计捕获 | install/enable/update 自身操作入库 | ✅(total=1 起) |
| 登录成功审计 | 语义动作 `login` | ✅ |
| **登录失败审计** | 错误密码 → 401 JSON(**2.26.0 与 2.26.1 行为不同:2.26.1 为 302→error 参数**),仍被认证端点过滤器捕获 | 语义动作 **`login-failure`** ✅ |
| 查询端点 | `GET auditlogs/-/query` | 200 ✅ |
| CSV 导出 | `GET auditlogs/-/export` | 200(339B,UTF-8 BOM)✅ |
| 匿名拒绝 | 无会话 GET query | 302 重定向 ✅ |
| **`ui/` ESM bundle** | `GET /plugins/operation-audit/assets/ui/ui-plugin.json` | 200 ✅(ui/ 迁移产物在 2.26.0 正常下发) |
| 实例日志 | 全程 | **0 ERROR** ✅ |
**结论**:插件在声明最低版本 Halo 2.26.0 上安装、启用、捕获、查询、导出、
权限拒绝与 UI 资源下发全部正常;2.26.1(此前三轮联调平台)为当前版本复验。
`spec.requires >=2.26.0` 的实测验证完成。
## 复测记录(2026-12-05 第五轮,commit `fc79842`)
**触发来源:生产环境现场反馈。** 站长在生产站(Halo 2.26.1)的操作审计页反馈
「没有失败,全是成功,登录失败也显示成功」,截图中的记录全是
`未知用户 · GET auth /login`、`GET auth /login?authentication_required`,描述「登录」、
结果绿色 200。本轮在一次性实例上复现、修复并复测;第二轮记录中「GET /login 页面访问
产生 login 记录属设计内覆盖,非噪声缺陷」的判断据此**推翻**。
```text
Commit: fc79842(master)
制品: plugin-operation-audit-0.1.0-SNAPSHOT.jar
SHA-256 73b4fb37246c9e02fb38ba43ef76ee32514299ca322e8f4651f994367647a4de
Halo versions tested: 2.26.1(官方独立 JAR,127.0.0.1:8097 一次性实例,H2 内置库,
数据目录 C:/Users/Windows11/.halo-repro/workdir-baseline,与生产数据无关联)
升级场景: 实例中保留修复前构建(afda8d0)写入的数据,停服替换 JAR 后启动
(Windows 部署路径);插件 STARTED,历史记录全部保留
Java and Node.js versions: Java 21.0.10、Node v24.19.0
Automated checks: PASS(./gradlew clean build:后端 27 类 286/286,UI vitest 9 文件 74/74,
vue-tsc 与 vite 构建通过;demo node:test 61/61)
Manual paths checked: 登录页 GET 访问不落库 → 失败登录(表单 302 / JSON 401 / 缺 CSRF 403)
→ 成功登录 → 登出 → 结果筛选 → 语义动作筛选 → CSV 导出 → Console 页面
Known limitations: 本轮未在 2.26.0 重测;生产站实际部署的插件构建未核对(见文末「本轮未覆盖」)
```
### 现象复现(修复前,commit `afda8d0` 构建)
Halo 2.26.1 的登录页是服务端渲染表单,表单登录无论成败在 HTTP 层**都是 302**,而登录页
自身的响应恒为 200。修复前的认证端点过滤器对 `/login`、`/logout` 不区分方法,把对页面的
GET 访问也当成登录事件落库:
| 浏览器行为 | 宿主实际响应 | 修复前落库(`action` / 状态码) |
| --- | --- | --- |
| 打开登录页 `GET /login` | 200 | `login` / 200 |
| 匿名访问受保护页,被弹回 `GET /login?authentication_required` | 302 → 登录页 200 | `login` / 200 |
| 密码错误 `POST /login`,浏览器跟随跳转到 `GET /login?error=invalid-credential&method=local` | 302 → 登录页 200 | `login-failure` / 302,另加一条 `login-failure` / 200 |
| 密码正确 `POST /login` | 302 → `/uc` | `login` / 302 |
`POST /login` 的成败标注本身是对的,但**每一次对登录页的访问都会落一条绿色「登录 200」**
(即生产截图中的记录)。从登录页发起的一次输错密码的登录共落 3 条记录,其中 1 条是绿色
「登录 200」;刷新登录页、被弹回登录页、扫描器反复探测 `/login` 同样如此,列表看起来
「全是成功」,真正的登录成败被淹没。
### 修复内容(commit `fc79842`)
| 层 | 改动 |
| --- | --- |
| 捕获 | 认证端点只记录认证操作 `POST /login`、`POST /logout`;登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出确认页)原样透传,不触碰请求体、不落库(`CaptureRule.isAuthOperation`) |
| 成败判定 | `LoginOutcome.isFailure`:仅 2xx,或 30x 且跳转目标不是登录页(`/uc`、已保存的原请求、两步验证页)才算成功;跳回 `/login`、带 `error` 参数、缺失 Location、4xx/5xx 一律判失败 |
| 结果语义 | 新增 `AuditResult`(成功 / 失败 / 页面访问),作为结果筛选、CSV 导出与列表徽标的同一套规则 |
| 历史记录 | 升级前落库的 GET 记录**不改写**(审计只追加):描述按方法纠正为「访问登录页 / 访问登出页」,结果显示灰色「—」,不计成败;结果筛选与「登录 / 登出」语义动作筛选均排除它们;带 `login-failure` 标注的旧回显页仍按「登录失败 · 失败」展示 |
| 界面 | 登录成功显示「成功」、登录失败显示红色「失败」,其余操作仍显示状态码;详情抽屉与 CSV 结果列同步 |
| 测试 | 后端 270 → 286、UI 69 → 74、demo 56 → 61 |
### 真实实例脚本复核(交付 JAR 本体)
自实例启动(13:30:02)起写入的记录:
| 检查项 | 实测 | 结果 |
| --- | --- | --- |
| 打开登录页 `GET /login` | 200,认证记录 0 条 | ✅ |
| 匿名访问受保护页 → `GET /login?authentication_required` | 302 → 200,认证记录 0 条 | ✅ |
| 登出确认页 `GET /logout` | 200,认证记录 0 条 | ✅ |
| 自启动起写入的认证端点记录 | 18 条**全部为 POST**(`/login`、`/logout`);页面访问记录 0 条 | ✅ |
| 密码错误 `POST /login`(表单) | 302 → `/login?error=invalid-credential&method=local`,记 `login-failure` | ✅ |
| 密码错误 / 不存在的账号(命中宿主限频时) | 302 → `/login?error=rate-limit-exceeded&method=local`,记 `login-failure` | ✅ |
| 密码错误(`Accept: application/json`) | 401,记 `login-failure` | ✅ |
| 缺少 `_csrf` 的 `POST /login` | 403,记 `login-failure` | ✅ |
| 密码正确 `POST /login` | 302 → `/uc`,记 `login` | ✅ |
| `POST /logout` | 302 → `/login?logout`,记 `logout` | ✅ |
| 结果筛选 `result=success` | 不含任何页面访问记录 | ✅ |
| 结果筛选 `result=failure` | 28 条:24 条 `POST` 登录失败、3 条旧回显页、1 条 `POST /logout` 403;不含旧「登录 / 登出」页面访问记录 | ✅ |
| 语义动作筛选 `spec.action=login` | 12 条,全部为 `POST /login`(302) | ✅ |
| CSV 导出(描述 / 结果) | 登录 / 成功 ×13、登录失败 / 失败 ×28、登出 / 成功 ×4、登出 / 失败 ×1、访问登录页 / 页面访问 ×7、访问登出页 / 页面访问 ×1 | ✅ |
| 实例日志 | 0 ERROR | ✅ |
说明:
- 修复前构建留在库中的 11 条 GET 记录(存储标注 `login` ×7、`login-failure` ×3、
`logout` ×1)原样保留、未改写:导出时 8 条为「访问登录页 / 访问登出页 · 页面访问」,
3 条带 `login-failure` 标注的旧回显页仍为「登录失败 · 失败」。
- Halo 2.26.1 内置登录限频为每 IP 每分钟 3 次尝试
(`resilience4j.ratelimiter.configs.authentication`)。连续失败尝试会触发限频:复核输出中
`invalid-credential` 与 `rate-limit-exceeded`(表单 302 / JSON 401)两种拒绝原因都实际出现过,
二者都是被拒绝的登录尝试,均记 `login-failure`。限频窗口内即使密码正确,宿主同样拒绝
(复核中实际出现 1 次),该尝试也如实记为登录失败。
- 18 条新记录 = 登录成功 5 + 登出 2 + 登录失败 11(脚本两轮的失败场景 8 条,另有 3 条来自
复核命令本身:2 次命令行输错实例密码的真实失败登录,以及上述被限频拒绝的 1 次)。
- `spec.action=login` 的 12 条取自脚本复核时点,CSV 直方图取自随后的事后抽查
(期间又有 1 次成功登录)。
### Console 页面(应用内浏览器真实登录)
截图所用构建与交付 JAR 逐条目内容一致(67 个条目的名称 / 大小 / CRC-32 全部相同,
仅打包时间戳不同);截图存于 `docs/assets/gui-test-screenshots/`。
| 检查项 | 实测 | 结果 | 截图 |
| --- | --- | --- | --- |
| 浏览器输错密码 | 落在 `/login?error=invalid-credential&method=local`,列表新增一行「登录失败 · 失败」 | ✅ | t6 |
| 登录成功 / 登出 | 「登录 · 成功」(绿)、「登出 · 302」 | ✅ | t6 |
| 修复前写入的 GET 记录 | 「访问登录页 · —」(灰,含 `/login?authentication_required`);带 `login-failure` 标注的旧回显页仍为「登录失败 · 失败」 | ✅ | t7 |
| 结果 = 成功(资源类型 auth) | 10 条:8 条「登录 · 成功」+ 2 条「登出 · 302」,无页面访问记录 | ✅ | t8 |
| 结果 = 失败(资源类型 auth) | 17 条「登录失败 · 失败」+ 1 条「登出 · 403」 | ✅ | — |
详情抽屉的结果语义(成功 / 失败 / 页面访问)由 `AuditLogDetail.appearance.spec.ts` 锁定,
本轮未做浏览器截图。
### 与前几轮记录的关系
- 第二轮「GET /login 页面访问产生 login 记录属设计内覆盖,非噪声缺陷」的判断作废:该行为
正是本次现场反馈的根因,现已改为不记录。
- 首轮 P0 修复(`f4d1200`)确立的「认证端点在 Security 链最前承接」结论不变,本次只收紧
了它记录的范围(仅 POST)与成败判定。
### 本轮未覆盖
- **未在 Halo 2.26.0 重测**:本轮改动用到的 `Queries.notEqual` / `Queries.startsWith` 已在
2.26.0 平台 API(`api-2.26.0.jar`,即 `halo-2.26.0.jar` 内置的那份)中核对签名存在,但
最低版本上的运行时复测未做,留待下次发布前执行。
- **生产站实际部署的插件构建未核对**:若生产站输错密码后没有新增 `POST /login` 记录,
说明线上仍是修复前的构建,需升级 JAR 才生效。
- Webhook 公网投递同前几轮,未重测。
## 复测记录(2026-12-05 第六轮:发布制品复核,commit `00c8d3f`)
**触发来源:发布前判定。** 此前「发布就绪」的结论针对的是 commit `81693e4` 的制品,其后代码
又有变更(`fc79842` 登录页访问修复等),且第五轮把最低版本复测留到了「下次发布前」。本轮按
[plugin-testing.md](./plugin-testing.md) 与 [plugin-release-checklist.md](./plugin-release-checklist.md)
对**当前 HEAD 的正式版制品**重做验收,不沿用旧结论。发布判定与阻断项清单以
[发布验收清单确认报告](./operation-audit-release-checklist-review.md)「六、第六轮复核」为准。
```text
Commit: 00c8d3f(master,工作区干净)
制品: plugin-operation-audit-0.1.0.jar(clean build -Pversion=0.1.0)
SHA-256 8391674adcd894b82497f1684ae2382b0d5be44192065014c5b52a8fcf185a83
121,681 字节,67 个条目 / 48 个类
Halo versions tested: 2.26.0(requires 下限)、2.26.1(目标版本)、2.27.4(当前最新)
均为官方独立 JAR(SHA-256 分别以 c71b9e5d / 7a1d6ea0 / ee0f1284 开头),
H2 内置库,一次性数据目录,127.0.0.1:8081~8085,与生产数据无关联
Java and Node.js versions: Java 21.0.10、Node v24.19.0(项目 UI 使用 npm)
Commands run: ./gradlew clean build -Pversion=0.1.0(仓库根入口 + -p plugin-operation-audit,
与 CI 工作流同款);node --test demo/test/audit-core.test.mjs;
联调:install / upgrade / uninstall API、启停、重启、登录登出、
query / export / alerts test、角色矩阵、设置生效、SSRF(驱动脚本不随仓库分发)
Automated checks: PASS(后端 27 类 286/286,UI vitest 9 文件 74/74 + vue-tsc + vite,demo 61/61)
Roles and dependency states: admin(超级管理员)、auditor(仅 role-template-audit-view)、
无角色普通用户、匿名;无插件依赖
Manual paths checked: 安装→启用→审计捕获→筛选→详情→导出→停用→启用→重启→升级→卸载→
卸载后重启;Console 桌面 1440×900 与窄屏 390×844
Known limitations: 见文末「本轮未覆盖」;敏感字段脱敏仅按字段名匹配(见下)
```
### 构建与 JAR 内容(清单第一、二节)
| 检查项 | 实测 | 结果 |
| --- | --- | --- |
| `clean build -Pversion=0.1.0` | BUILD SUCCESSFUL;`check` 内的后端测试、UI 测试、类型检查全部执行 | ✅ |
| 版本三处一致 | JAR 文件名、`plugin.yaml` 的 `spec.version`、Manifest `Implementation-Version` 均为 `0.1.0` | ✅ |
| `git status --short` | 构建后工作区干净,`build/` 未入库 | ✅ |
| `plugin.yaml` | `operation-audit` / `>=2.26.0` / logo / homepage / repo / issues / author / `GPL-3.0` | ✅ |
| Manifest | `Plugin-Main-Class`、`Implementation-Version` 正确(考证见第四轮) | ✅ |
| 运行时资源 | 后端类、`extensions/*.yaml`、`plugin-components.idx` 齐全 | ✅ |
| UI | `ui/ui-plugin.json`(ESM)声明的入口 `main.BR7J9rzn.js`(21,843 B)与样式 `assets/index.OTLFxW7_.css`(7,501 B)均在包内 | ✅ |
| 不含敏感文件 | 条目清单无凭据、`.env`、测试数据 | ✅ |
| 已运行 `generateApiClient`、无手写类型 | 入库的 `ui/src/api/generated` 是手工对齐的 bootstrap 契约;用真实运行时再生成后 UI 类型检查不过 | ❌ 见下 |
### 安装、启停、重启、卸载(清单第三节)
每个实例均为一次性全新数据目录,JAR 经 Console 的 install API 以默认 `deployment` 模式上传。
「重启」指强制结束进程后以原数据目录重新启动(比正常重启更严格)。
| 实例 | Halo | 场景 | 结果 |
| --- | --- | --- | --- |
| A | 2.26.1 | 全新安装 → 核心套件 → 重启 → 停用/启用往返 | 安装 11/11;核心套件分段通过;重启检查 22/22 |
| B | 2.26.1 | 全新安装 → 卸载 → 重启 | 安装 11/11;卸载 12/12;卸载后重启 7/7 |
| C | 2.26.0 | 全新安装 → 核心套件全量(含设置生效)→ 重启 → 停用/启用往返 | 11/11;111/111;22/22 |
| D | 2.27.4 | 全新安装 → 核心套件 → 重启 → 停用/启用往返 | 11/11;93 项(92 通过,1 项为无关 ERROR 断言);22/22 |
| E | 2.26.1 | 旧构建遗留数据 → upgrade API 升级 → 重启 → 停用/启用往返 | 升级复核 20/20;重启检查 22/22 |
核心套件覆盖(C 实例全量 111 项为最完整的一次):UI 清单与入口下发;登录/登出审计
(缺 CSRF 403、密码错误表单 302 / JSON 401 记 `login-failure`,成功记 `login`,登出记 `logout`,
页面访问 0 条,每条只带白名单字段);结果/语义动作/组合筛选与非法参数(400,无 500);
新建 / 修改 / 删除的字段级 diff 与 404 失败写入;凭据类写入(建用户、改密码、建 Secret、
保存设置)后审计库、查询端点、CSV、运行日志均不含密码与令牌标记;CSV 表头与行数;
角色矩阵(只读角色可查不可改、普通用户 403、匿名跳登录);设置保存后经 60 秒 TTL 生效;
SSRF 守卫拒绝 10 类受限地址且日志不带令牌;真实登录失败告警路径触发并 fail closed。
未全绿的运行及归因(均非插件缺陷,对应项已按修正后的脚本复核通过):
- A 首轮 71 项中 3 项未过:删除标签时宿主返回 409(受控实验中重复删除 13 次全部成功,属宿主
reconciler 的瞬时冲突,脚本改为重试);日志断言把脚本自身畸形探测引发的宿主 500 计入。
- D 93 项中 1 项未过:日志断言计入了 Halo 2.27.4 内置插件 `ai-page-builder` 启动时的
无关 ERROR;按插件范围复核为 0 条。
- 重启检查首版断言「停用后 UI 包不可访问」在 2.26.1 与 2.27.4 上同样不过:实测停用后
Halo 仍以 200 下发插件的静态 JS/CSS(所有插件一致的平台行为,数据端点此时为 404)。
该断言已改为观察项。
重启与停用/启用往返(A/C/D/E 各 22 项):管理员可登录;插件重新 STARTED;设置与
Webhook Secret 引用保留;重启前的记录全部还在;停用后三个数据端点 404、停用期间的登录
失败与写操作 0 条记录、宿主写流程不受影响;重新启用后查询恢复且每次操作只有一条记录
(无重复注册的过滤器)。
**卸载(B)**:停用 → 删除 Plugin CR → finalizer 清理完成;JAR、预置 Setting、ConfigMap、
RoleTemplate 全部移除,端点与 UI 包下线,插件列表中不再出现,日志无插件相关 ERROR;
宿主侧留下 1 条孤儿 RoleBinding(Halo 平台行为,角色已删、无授权效果)。卸载后重启:
主机流程正常(建标签 2xx)、`/actuator/health` UP。
**升级(E)**:实例先运行 tag `v0.1.0`(commit `5d05d63`)的 `0.1.0-SNAPSHOT` 构建并写入
遗留数据,复现了第五轮的缺陷——`result=success` 的 19 条里有 8 条是登录页访问。经 upgrade
API 换成发布制品后:插件 STARTED、版本 `0.1.0`;设置保留(保留 45 天、告警引用 / 阈值 /
窗口);升级前的记录一条未丢;旧页面访问记录原样保留(审计只追加,未改写);
`result=success` 中的页面访问 8 → 0;`spec.action=login` 只剩 `POST /login`;CSV 把旧 GET
记录呈现为「访问登录页 / 访问登出页 · 页面访问」(带失败标注的旧回显页仍为「登录失败 · 失败」);
UI 为发布制品的包;只读角色绑定仍然有效;日志无插件相关 ERROR。升级后重启:设置与数据保留。
### Console 页面(应用内浏览器,A 实例,发布制品本体)
截图存于 `docs/assets/gui-test-screenshots/`(`r6_` 前缀)。测试过程中页面未出现任何错误表现;
浏览器工具不提供控制台日志读取,未收集控制台信息。
| 检查项 | 实测 | 结果 | 截图 |
| --- | --- | --- | --- |
| 登录后左侧菜单出现「操作审计」,进入列表 | 筛选条、导出/刷新、表格、分页(共 10 页)正常渲染 | ✅ | r6_t1 |
| 结果 = 失败 | 19 行全部为红色「失败」或 4xx/5xx 状态码;「重置」变为可用 | ✅ | r6_t2 |
| 语义动作 = 登录 | 共 8 项,全部为 `POST /login`「登录 · 成功」 | ✅ | r6_t3 |
| 「重置」 | 筛选清空,列表恢复全量 | ✅ | — |
| 详情抽屉(登录记录) | 只读定义列表(操作者 / 尝试用户 / 描述 / 动作 / 资源 / 结果 · 状态码 / 路径 / 时间 / IP / UA / 记录标识),仅有「关闭」按钮 | ✅ | r6_t4 |
| 详情抽屉(带变更的记录) | 「字段变更」逐字段显示 5 个新增字段及取值 | ✅ | r6_t4b |
| 「导出」 | 触发真实下载:`audit-logs-20261205-225130.csv`,57,731 字节,UTF-8 BOM + CRLF,13 列表头与文档一致,187 行(成功 147 / 失败 40),登录行 8 条「登录 · 成功」+ 7 条「登录失败 · 失败」,无页面访问行 | ✅ | — |
| 插件详情页 | 详情 / 审计设置 / 告警通知三个页签;版本 0.1.0、要求 >=2.26.0、权限模板显示正确 | ✅ | r6_t6 |
| 审计设置页签 | 三个开关与保留天数回显已保存的值 | ✅ | r6_t6a |
| 告警通知页签 | 开关、Secret 选择器(`rv-hook`,含字段 `webhookUrl`)、阈值、窗口回显 | ✅ | r6_t6b |
| 「发送测试告警」 | 按钮旁同步显示「发送失败:Webhook 主机解析到受限网络地址…已拒绝」,不含令牌 | ✅ | r6_t6c |
| 窄屏 390×844 | 筛选项纵向堆叠,页面无横向溢出(`scrollWidth` = 390),表格在容器内横向滚动 | ✅ | r6_t7 |
### 敏感字段脱敏缺口(必须修复)
字段级 diff 的脱敏只按字段名匹配 `password|passwd|secret|token|credential`
(`ChangeDiffEngine.SENSITIVE_FIELD`)。实测(A 实例,经真实 diff 路径):
| 字段名 | 审计记录中的值 |
| --- | --- |
| `password`、`clientSecret`、`api_token` | `******` |
| `apiKey`、`accessKey`、`accessKeyId`、`privateKey`、`authHeader` | **明文** |
影响:插件记录的是**全后台** `/apis/**` 的写操作,第三方插件资源里常见的 `spec.apiKey` /
`accessKey` / `privateKey` 一旦被管理员保存,其值就会明文进入审计库,并在详情抽屉与 CSV
导出中可见。这与应用市场审核指南 4.3.2(不得存储明文密钥、不得在日志中泄露敏感信息)
直接冲突,README 的「敏感字段自动脱敏」表述也名不副实。建议把规则扩展为按键名
(`api[-_]?key`、`access[-_]?key`、`private[-_]?key`、`keyId`、`authorization`、`sign(ature)`、
`salt`、`cert` 等)加按值特征(JWT、长 base64/hex 串)的双重判定,并补单测。
### API 客户端不是生成器产物(必须修复)
官方清单要求「已运行 `generateApiClient`,UI 使用生成的模型和请求方法,没有另行手写同一
资源的类型和路径」。本轮用发布制品所在的运行实例真实执行了生成管线:
- 请求层契约一致:3 个端点(`/-/query`、`/-/export`、`/-/test`)的路径、方法与全部查询参数名
(`page/size/sort/fieldSelector/result/keyword/startTime/endTime`)与入库客户端完全相同,
运行时行为不受影响。
- 模型层不一致:运行时文档对插件模型没有声明 `required` 与描述,再生成的 `AuditLog.spec`
等字段全部为可选、枚举被内联,另带入了 Halo 全局的 JSON Patch 模型。用再生成产物替换后
`vue-tsc` 报错(`AuditLogList.vue` 第 366~402 行:`'log.spec' is possibly 'undefined'` 等)。
也就是说入库的 `ui/src/api/generated` 是手写契约,README 记载的再生成步骤照做会打断构建。
修正方向二选一:在后端模型上补 `@Schema(requiredMode = REQUIRED)` 与描述后真实再生成并入库;
或按再生成产物调整视图代码。两者都要让「生成 → 构建通过」成为可重复的事实。
再生成的环境要求(README 记载有误,需一并更正):devtools 0.8.0 不识别
`-PhaloPlugin.openApi.useExistingServer`,任务图仍包含 `:pullHaloImage`,无 Docker 时失败;
须在 `build.gradle` 里设 `useExistingServer = true` + `apiDocsUrl`。且正式运行的 Halo 默认
`springdoc.api-docs.enabled=false`(`/v3/api-docs/**` 返回 404),目标实例必须以
`--springdoc.api-docs.enabled=true` 并带上与 `groupingRules` 等价的 `springdoc.group-configs`
启动才能取到 `extensionApis` 文档。
### 链接域名迁移(2026-12-05 晚,仓库推送地址变更)
仓库推送地址迁移为 `https://gitea.guichumo.com/836061373/halo-ops-audit.git`(实测 HTTPS 200,
HTTP 自动 301 到 HTTPS,`/issues` 200)。据此把 `plugin.yaml` 里四处指向裸 IP
`http://101.43.163.221:3000/...` 的链接(homepage / repo / issues / author.website)改为该
HTTPS 域名,修复发布阻断项 B7。
- 重新 `clean build -Pversion=0.1.0`:BUILD SUCCESSFUL;新制品
`b26623e9fbbe39e8f57072f554d9c018c1fa603bdcc5d8810f220d09e3b2eaa0`(121,673 字节)。
- 与通过完整矩阵的上一制品(`8391674a…`)逐条目对比:57 个条目中仅 `plugin.yaml`
内容变化,其余 56 个条目逐字节相同。
- 提交 `23d8846` 已推送到新远端 master;推送后 Actions 页面仍为 `0 workflow runs`
(列表里能看到 CI、CD 两个工作流),确认 B4「CI 未运行」在迁移后的平台上依旧成立。
- 全新 Halo 2.26.1 实例安装复验:install → enable → STARTED,Plugin CR 的
homepage / repo / issues / author.website 均为新域名,安装检查 11/11;核心套件
(UI 下发、登录登出、筛选、写入 diff、凭据不落库、CSV、角色矩阵、SSRF、告警)
**93/93** 通过、0 失败。
- 未变的结论:B7 之外,B1(脱敏)、B2(远端 tag 指向修复前提交)、B4(CI 未运行)、
B5(API 客户端非生成器产物)、B6(LICENSE 与 README 三节)仍待处理;B3(`gradlew`
无执行位)已同步修复(两处改为 `100755`)。整体判定仍为**暂不可发布**。
### 本轮未覆盖
- **Webhook 公网投递未验证**:SSRF 守卫按设计拒绝环回地址,本地无法搭接收端;未向外部服务
发送数据。成功投递只有单测(本地 HTTP 服务)覆盖。
- **保留期清理未在真实环境验证**:Halo 在创建时覆盖客户端提供的 `creationTimestamp`
(实测 POST 指定 60 天前的时间戳被改写为当前时间),无法在验收窗口内构造过期数据;
最小保留 7 天。仅有单元测试覆盖。
- CI 未实际运行(见验收确认报告第四节),自动化检查结果来自本机同款命令。
## 附:测试环境残留与清理
- 测试实例保留运行于 `http://127.0.0.1:8099`(admin / 测试密码已脱敏,
数据目录 `C:/Users/Windows11/.halo-smoke-test/workdir`,可丢弃,与生产数据无任何关联);
- 第三轮联调中重置了 auditor3 密码(测试凭据已脱敏,供只读角色矩阵复测),
残留测试用户 auditor3(role-template-audit-view)保留于实例中;
- 已恢复干净版插件 JAR 并确认无诊断日志残留(重启后 0 条 AUDIT-DIAG);
- 源码工作区干净,截图证据已归档至 `docs/assets/gui-test-screenshots/` 并纳入版本控制。
- 2026-12-05 核对:上述 8099 实例已不在运行(端口未监听),数据目录仍保留。
- 第五轮的一次性实例(127.0.0.1:8097,数据目录
`C:/Users/Windows11/.halo-repro/workdir-baseline`)已停服,目录保留、可整体删除;
复现与抽查脚本在 `C:/Users/Windows11/.halo-repro/scripts/`(`repro.py`、`spotcheck.py`、
`inspect.py`),不随仓库分发。
- 第六轮的五个一次性实例(127.0.0.1:8081~8085,数据目录
`C:/Users/Windows11/.halo-release-verify/workdir-{a..e}`)已全部停服,Gradle 守护进程已停止,
目录保留、可整体删除。驱动脚本、各次运行输出与结果(`scripts/hv.py`、`out-*.log`、
`results-*.json`、`halo-*.log`)、浏览器导出的 CSV 样本,以及用于 API 客户端再生成的
HEAD 导出副本(`src-head/`)与日志(`build-apiclient*.log`)都在该目录下,不随仓库分发;
第六轮截图为 `docs/assets/gui-test-screenshots/r6_*.png`。
+98
View File
@@ -0,0 +1,98 @@
# 插件发布验收清单
> For AI agents: the complete documentation index is available at https://docs.halo.run/llms.txt, the full documentation bundle is available at https://docs.halo.run/llms-full.txt.
本清单用于验证准备发布的插件 JAR,而不只是开发目录。先完成[插件测试](https://docs.halo.run/developer-guide/plugin/testing.md),再使用最终制品在 `plugin.yaml` 的 `spec.requires` 所声明的 Halo 版本范围内完成验收。
## 构建发布制品
使用准备发布的版本号执行干净构建:
```bash
./gradlew clean build -Pversion=1.2.3
git status --short
```
Windows 环境将 `./gradlew` 替换为 `gradlew.bat`。构建完成后,插件 JAR 通常位于 `build/libs`。
确认以下结果:
- `clean build` 成功,并运行了所有接入 `check` 的后端和 UI 检查。
- JAR 文件名、Gradle 项目版本和准备发布的版本一致。
- `git status --short` 只显示预期的源码变化;不要手动修改或提交 `build` 中的生成文件。
- 多模块项目只发布 Halo 插件 JAR,不要把 API 模块、测试夹具或其他 JAR 误当作插件制品。
## 检查 JAR 内容
将示例文件名替换为实际制品:
```bash
jar tf 'build/libs/plugin-name-1.2.3.jar'
unzip -p 'build/libs/plugin-name-1.2.3.jar' plugin.yaml
unzip -p 'build/libs/plugin-name-1.2.3.jar' META-INF/MANIFEST.MF
```
确认以下内容来自本次构建:
- JAR 根目录包含 `plugin.yaml`,其中 `metadata.name`、`spec.version`、`spec.requires`、插件依赖、Logo、主页、问题反馈地址和许可证正确。
- Manifest 包含正确的 `Plugin-Main-Class` 和 `Implementation-Version`。
- 后端类、`extensions`、设置、模板、静态资源和其他运行时资源完整。
- 包含 UI 的插件应打包完整的 `ui` 目录;使用 ESM 输出时,`ui/ui-plugin.json` 记录的入口、样式和异步资源均存在。旧项目可能使用 `console` 目录,具体规则参考 [UI 构建](https://docs.halo.run/developer-guide/plugin/basics/ui/build.md#output-format)。
- API 契约变化后已经运行 `generateApiClient`,UI 使用生成的模型和请求方法,没有另行手写同一资源的类型和路径。
- JAR 不包含凭据、私钥、`.env`、本地工作目录、测试数据或其他不应分发的文件。
不要解压后修改 JAR 或构建目录来修正版本和资源。发现问题时应修改源文件或构建配置,然后重新构建完整制品。
## 验证安装和升级
至少准备一个干净的 Halo 实例;已经发布过插件时,再准备一个安装了上一正式版的实例:
1. 以默认的 `deployment` 模式上传 JAR,完成安装和启用。
2. 检查插件信息、默认配置、权限、Console 或用户中心入口及主要功能。
3. 重启 Halo,再次验证插件启动、配置和持久化数据。
4. 禁用后重新启用插件,确认运行时资源能够释放和恢复。
5. 从上一正式版升级,确认配置、业务数据、API 和 UI 能够兼容或按文档完成迁移。
6. 在可丢弃环境中卸载插件,按照[插件生命周期](https://docs.halo.run/developer-guide/plugin/basics/server/lifecycle.md)核对运行时资源、预置资源、外部资源和持久化数据的处理结果。
7. 在声明范围内的最低 Halo 版本和计划支持的当前版本上重复关键路径。
如果插件依赖其他插件、外部服务或主题模板,还需要覆盖依赖缺失、停用、版本不满足、认证失败和正常可用的状态。
涉及表单、密钥或第三方服务时还应确认:
- 普通插件设置由 Setting YAML 渲染,页面和弹窗表单复用 FormKit 与 Halo 组件。
- 密码、Token、API Key 和私钥保存在 `Secret` 中,普通资源和 API 不返回明文。
- 用户可配置的出站地址符合[敏感数据与出站请求](https://docs.halo.run/developer-guide/plugin/security/outbound-http.md)中的 SSRF、重定向、超时和凭据发送限制。
- 公开 API 和安全开关在配置缺失、读取失败和依赖异常时保持关闭。
## 核对 CI/CD
Halo 的可复用插件 CI 工作流运行 `./gradlew clean build`,能够执行检查并生成制品。插件 CD 工作流会根据 GitHub Release tag 注入版本号,并使用 `-x check` 构建 JAR,因此 CD 构建不能替代发布前的 CI 和测试。
使用可复用工作流时确认:
- 发布 commit 的 CI 已通过,没有被跳过或允许失败的必要检查。
- Release tag 去掉可选的 `v` 前缀后,与 JAR 文件名和 `plugin.yaml` 中的 `spec.version` 一致。
- `artifacts-path` 只匹配计划发布的制品。
- 首次上架前不自动同步应用市场;首次审核通过后再配置应用 ID 和最小权限的个人令牌。
CI/CD 配置和应用市场流程参考[发布应用](https://docs.halo.run/developer-guide/app-store/publish-app.md#%E4%BD%BF%E7%94%A8-github-actions-%E8%87%AA%E5%8A%A8%E6%9E%84%E5%BB%BA%E5%92%8C%E5%8F%91%E5%B8%83)。
## 记录发布证据
发布记录至少保留以下信息:
```text
Commit and tag:
Plugin version:
Halo versions tested:
Clean install: pass/fail
Upgrade from: version, pass/fail
Commands run:
Roles and dependency states checked:
Known limitations:
Artifact path and SHA-256:
```
macOS 可以使用 `shasum -a 256 'build/libs/plugin-name-1.2.3.jar'`,Linux 可以使用 `sha256sum 'build/libs/plugin-name-1.2.3.jar'` 生成摘要。
发现以下任一问题时应停止发布:检查或构建失败、JAR 无法安装或启用、版本信息不一致、主要功能或权限失效、升级导致数据损坏,或制品包含不应分发的敏感文件。验收通过后,再根据[发布应用](https://docs.halo.run/developer-guide/app-store/publish-app.md)准备版本说明、截图、许可证和应用市场资料。
+109
View File
@@ -0,0 +1,109 @@
> For AI agents: the complete documentation index is available at https://docs.halo.run/llms.txt, the full documentation bundle is available at https://docs.halo.run/llms-full.txt.
# 测试插件
插件测试应覆盖源码级自动化检查、开发环境联调和最终 JAR 安装验证。`haloServer` 能快速加载开发目录,但不能代替对发布制品的安装测试;准备发布时还需要完成[插件发布验收清单](https://docs.halo.run/developer-guide/plugin/release-checklist.md)。
## 选择验证层级
| 变更范围 | 开发时至少执行 | 交付或发布前补充 |
| ------------ | ----------------- | ---------------------------------- |
| Java 后端 | `./gradlew test` | `./gradlew clean build`、本地 Halo 联调 |
| 插件 UI | UI 项目已有的检查任务 | `./gradlew check`、桌面和窄屏人工检查 |
| API 或生成客户端 | 后端测试、项目已有的客户端生成任务 | 审查生成差异、后端与 UI 联调 |
| 权限、扩展点、插件依赖 | 相关自动化测试 | 使用不同角色和依赖状态联调 |
| 生命周期、升级或数据迁移 | 相关自动化测试 | 使用最终 JAR 完成安装、启停、升级和卸载测试 |
优先运行与改动最相关的最小任务,再运行完整构建。不要因为页面可以打开,就跳过权限、失败路径和生命周期验证。
## 运行自动化检查
### 后端测试
Halo 插件通常使用 JUnit 5,测试代码位于 `src/test/java`。只验证后端时运行:
```bash
./gradlew test
```
测试应围绕实际行为编写,至少覆盖本次变更涉及的正常路径和失败路径。处理用户输入、权限、外部服务或响应式错误时,还应验证无权限、无效输入、依赖不可用和异常传播。
### UI 检查
推荐的插件工程会在 UI 子项目中注册 `pnpmCheck`,并把它接入 Gradle 的 `check` 生命周期:
```bash
./gradlew :ui:pnpmCheck
```
如果 UI 目录名为 `console`,将命令中的 `ui` 替换为 `console`。不同项目的 `pnpmCheck` 可能只运行单元测试,也可能同时运行格式、Lint 和类型检查;以仓库的 `ui/build.gradle`、`package.json` 和 CI 配置为准。接入方式参考 [UI 构建](https://docs.halo.run/developer-guide/plugin/basics/ui/build.md)。
不要手动修改 OpenAPI 生成的 API client。API 契约变化时,应运行项目已有的生成任务,并把生成差异与后端契约一起审查。
### 完整检查
运行所有已接入 Gradle 验证生命周期的任务:
```bash
./gradlew check
```
发布前执行干净构建:
```bash
./gradlew clean build
```
标准 Java Gradle 工程的 `build` 会依赖 `check`,并在 `build/libs` 生成插件 JAR。自定义测试任务只有接入 `check` 后才会随完整构建执行,因此新增测试任务时需要同时检查任务依赖关系。
## 在本地 Halo 中联调
使用 [DevTools](https://docs.halo.run/developer-guide/plugin/basics/devtools.md) 启动加载开发目录的 Halo:
```bash
./gradlew haloServer
```
修改插件后,可以重新加载或持续监听:
```bash
./gradlew reloadPlugin
# 或者持续监听
./gradlew watch
```
`haloServer` 和 `watch` 需要 Docker,并会复用项目的 `workplace` 目录。该目录中的数据会跨任务重启保留;需要验证首次安装或默认配置时,应使用新的测试数据目录或干净环境,不要把生产数据用于开发测试。
同时联调多个插件项目时,DevTools 0.9.0 及以上版本可以通过 `./gradlew haloServer -Pport=8091` 或 `./gradlew watch -Pport=8091` 为各项目指定不同端口。后续在同一项目目录中执行 `./gradlew reloadPlugin` 无需重复传入端口,详见[同时运行多个插件项目](https://docs.halo.run/developer-guide/plugin/basics/devtools.md#%E5%90%8C%E6%97%B6%E8%BF%90%E8%A1%8C%E5%A4%9A%E4%B8%AA%E6%8F%92%E4%BB%B6%E9%A1%B9%E7%9B%AE)。
联调时至少检查:
- 插件能够启动,服务端和浏览器控制台没有未处理错误。
- API 的成功、无权限、无效输入和依赖失败路径符合预期。
- Console 或用户中心入口在不同角色下正确显示并限制操作。
- 配置保存、重新加载和 Halo 重启后仍然生效。
- 使用外部服务时,超时、认证失败和服务不可用不会破坏 Halo 的主要流程。
- [与主题集成](https://docs.halo.run/developer-guide/plugin/theme-integration.md)并提供 Finder、模板或前台资源时,在实际主题中验证输出;声明插件依赖时,验证依赖缺失、停用、版本不满足和正常启用的状态。
## 验证兼容性和生命周期
至少在 [`plugin.yaml`](https://docs.halo.run/developer-guide/plugin/basics/manifest.md) 的 `spec.requires` 所声明的最低 Halo 版本和计划支持的当前版本上验证关键路径。不要仅根据编译成功推断兼容范围。
禁用、重载和重启后,插件应能恢复工作,持久化业务数据不应被意外删除。升级和卸载测试应使用可丢弃环境,并按照[插件生命周期](https://docs.halo.run/developer-guide/plugin/basics/server/lifecycle.md)确认运行时资源、预置资源和持久化数据的处理结果。
## 记录可复核结果
人工测试或 AI Agent 执行后,应保留能够复现结论的信息:
```text
Commit:
Halo versions tested:
Java, Node.js and pnpm versions:
Commands run:
Automated checks: pass/fail
Roles and dependency states checked:
Manual paths checked:
Known limitations:
```
命令失败、测试被跳过或环境与声明兼容范围不一致时,应明确记录,不能用“构建成功”概括未执行的验证。
Vendored Executable
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# 仓库根目录不是 Gradle 构建根:插件项目位于 plugin-operation-audit/ 子目录。
# Halo 官方可复用插件 CI/CD 工作流(halo-sigs/reusable-workflows)从仓库根执行
# ./gradlew clean build,此脚本将调用转发到子项目的 Gradle wrapper。
# 本地等价命令:./gradlew clean build -p plugin-operation-audit
exec "$(dirname "$0")/plugin-operation-audit/gradlew" "$@"
Vendored
+6
View File
@@ -0,0 +1,6 @@
@echo off
rem 仓库根目录不是 Gradle 构建根:插件项目位于 plugin-operation-audit\ 子目录。
rem Halo 官方可复用插件 CI/CD 工作流(halo-sigs/reusable-workflows)从仓库根执行
rem ./gradlew clean build,此脚本将调用转发到子项目的 Gradle wrapper。
rem 本地等价命令:gradlew.bat clean build -p plugin-operation-audit
"%~dp0plugin-operation-audit\gradlew.bat" %*
+112 -25
View File
@@ -9,7 +9,14 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
- **操作记录**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH), - **操作记录**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH),
一条通用规则覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作; 一条通用规则覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作;
另捕获 `/login`、`/logout`(登录成功/失败/登出)。 另捕获认证操作 `POST /login`、`POST /logout`(登录成功/失败/登出),登录请求白名单
提取尝试的用户名落库(`spec.attemptedUsername`,密码等其余字段绝不落库,登录时操作者
记"未知用户")。登录/登出页面的 GET 访问(打开登录页、被弹回登录页、失败回显、登出
确认页)不是操作,不记录。
- **登录成败标注**:表单登录成败在 HTTP 层都是 302,按重定向目标是否跳回登录页判定
(`LoginOutcome`,只有响应明确确认才算成功);列表/详情显示「成功」/红色「失败」,
CSV 结果列同理。升级前落库的登录页访问记录(`GET /login`,曾显示成绿色「登录 200」)
纠正为灰色「—」的「访问登录页」,不计成败。
- **系统内部变更**:定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记, - **系统内部变更**:定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,
执行者记为 "system"(Console 展示为"系统");只记录用户可写面有实际变化的更新/删除, 执行者记为 "system"(Console 展示为"系统");只记录用户可写面有实际变化的更新/删除,
并附字段级新旧值,与页面/API 操作区分归属、不重复记录。 并附字段级新旧值,与页面/API 操作区分归属、不重复记录。
@@ -18,13 +25,20 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
中文操作描述由同一套推导生成,贯穿列表、详情与导出 CSV,历史记录同样适用。 中文操作描述由同一套推导生成,贯穿列表、详情与导出 CSV,历史记录同样适用。
- **审计日志查看**:Console 左侧菜单"操作审计"——列表 + 八维筛选(操作者/资源类型/动作/ - **审计日志查看**:Console 左侧菜单"操作审计"——列表 + 八维筛选(操作者/资源类型/动作/
语义动作/结果/时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。 语义动作/结果/时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。
有资源名称的记录行内提供「历史」快捷动作:一键预填资源类型 + 资源名关键字并刷新列表,
直接回答"这个资源被谁改过"(功能评审 P1-1)。
- **导出 CSV**:列表页「导出」按钮按当前筛选条件导出全部记录——后端全量流式生成 - **导出 CSV**:列表页「导出」按钮按当前筛选条件导出全部记录——后端全量流式生成
(UTF-8 BOM + `\r\n`,Excel/WPS 双击打开中文不乱码),列与界面一致(操作时间、操作者、 (UTF-8 BOM + `\r\n`,Excel/WPS 双击打开中文不乱码),列与界面一致(操作时间、操作者、
动作、资源类型、资源名称、路径、操作描述、结果、状态码、来源 IP、User-Agent), 尝试用户、动作、资源类型、资源名称、路径、操作描述、变更、结果、状态码、来源 IP、
含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。 User-Agent),含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。
- **登录失败告警**:统计窗口内登录失败达到阈值时向 Webhook 地址异步推送 JSON 告警 - **登录失败告警**:统计窗口内登录失败达到阈值时向 Webhook 地址异步推送 JSON 告警
(默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零);独立于审计开关, (默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零;内容含尝试的用户名,
在插件设置「告警通知」中配置(默认关闭)。 可区分定向撞库与无差别扫描);独立于审计开关,在插件设置「告警通知」中配置(默认关闭)。
Webhook 地址凭据存于 Halo `Secret`(设置仅保存 Secret 引用,支持含 `access_token` 等
凭据的地址);发送前对地址做 SSRF 防护校验(http(s) 白名单、拒绝内网/环回/链路本地/
云元数据等受限地址段,并钉定校验通过的地址建连以防范 DNS rebinding)。
该区提供「发送测试告警」入口:以 `type: "test"` 测试消息向已保存的 Webhook 地址推送并
同步反馈发送结果,无需等待真实告警即可验证配置是否可用。
- **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录, - **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录,
启动时补跑一次。 启动时补跑一次。
- **权限**:默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view` - **权限**:默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`
@@ -48,46 +62,60 @@ Console「插件 → 操作审计 → 设置」:
| 配置项 | 默认 | 说明 | | 配置项 | 默认 | 说明 |
|---|---|---| |---|---|---|
| 启用审计 | 开 | 关闭后不再记录新日志,已有记录仍可查询 | | 启用审计 | 开 | 关闭后不再记录新日志,已有记录仍可查询 |
| 记录字段变更 | 开 | 对成功的新建/修改/删除操作记录字段级新旧值(敏感字段自动脱敏) | | 记录字段变更 | 开 | 对成功的新建/修改/删除操作记录字段级新旧值(字段名命中敏感规则的字段以 `******` 落库,覆盖范围见「已知局限」) |
| 记录系统内部变更 | 开 | 记录定时发布等非页面操作触发的资源变更(执行者记为 system) | | 记录系统内部变更 | 开 | 记录定时发布等非页面操作触发的资源变更(执行者记为 system) |
| 保留天数 | 90 | 最小 7 天;过期记录每日自动清理 | | 保留天数 | 90 | 最小 7 天;过期记录每日自动清理 |
| 启用登录失败告警 | 关 | 统计窗口内失败达到阈值时推送 Webhook 告警(独立于审计开关) | | 启用登录失败告警 | 关 | 统计窗口内失败达到阈值时推送 Webhook 告警(独立于审计开关) |
| Webhook 地址 | 空 | 接收告警的 http(s) 地址,JSON POST 异步推送 | | Webhook 地址(Secret) | 空 | 选择或创建存放 Webhook 地址的 Secret(键 `webhookUrl`);地址仅存于 Secret,可含 access_token 等凭据,JSON POST 异步推送 |
| 发送测试告警(按钮) | - | 向已保存的 Webhook 地址推送 `type: "test"` 测试消息并直接反馈发送结果(不保存配置值,仅超级管理员可用) |
| 触发阈值(次) | 5 | 统计窗口内累计登录失败达到该次数即触发一次告警 | | 触发阈值(次) | 5 | 统计窗口内累计登录失败达到该次数即触发一次告警 |
| 统计窗口(分钟) | 5 | 失败次数的累计窗口;告警后窗口重开,登录成功立即清零 | | 统计窗口(分钟) | 5 | 失败次数的累计窗口;告警后窗口重开,登录成功立即清零 |
设置经 60 秒 TTL 缓存读取,变更最多延迟 1 分钟生效。 设置经 60 秒 TTL 缓存读取,变更最多延迟 1 分钟生效。
**告警负载**:通用 JSON 结构(`type` / `title` / `content` / `timestamp` / `data`), **告警负载**:通用 JSON 结构(`type` / `title` / `content` / `timestamp` / `data`),
以 JSON POST 异步推送,超时 10 秒、失败不重试仅记日志: 以 JSON POST 异步推送,超时 10 秒、失败不重试仅记日志;发送前经 SSRF 防护校验,
受限地址(内网/环回/元数据等)在建立连接前即拒绝,校验失败与推送失败同样只记日志
(日志只记主机名,不记可能含凭据的完整地址):
```json ```json
{ {
"type": "login-failure", "type": "login-failure",
"title": "操作审计告警:登录失败", "title": "操作审计告警:登录失败",
"content": "5 分钟内出现 5 次登录失败,最近一次来自 1.2.3.4(Mozilla/5.0 ...)。 "content": "5 分钟内出现 5 次登录失败,最近一次来自 1.2.3.4(Mozilla/5.0 ...),
可在 Console「操作审计」查看详情。", 尝试的账号:admin。可在 Console「操作审计」查看详情。",
"timestamp": "2026-11-21T12:34:56Z", "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 Secret 未配置、Secret 缺少 `webhookUrl` 键时提示先完成配置。
不内置钉钉、企业微信、飞书等平台的专属消息格式适配,需要时可在中转服务侧转换
(地址凭据已可安全存于 Secret,直连含 token 的地址在传输层可行,消息格式仍需接收方兼容通用 JSON)。
## 模型 group 与权限标识 ## 模型 group 与权限标识
- **group**:已按"自有域名反写(`audit.<你的域名>`)"约定定为 `audit.guichumo.com`。 - **group**:已按"自有域名反写(`audit.<你的域名>`)"约定定为 `audit.guichumo.com`。
唯一事实来源是 `AuditLog.GROUP` 常量(查询端点、测试挂载路径均引用它); 唯一事实来源是 `AuditLog.GROUP` 常量(查询端点、测试挂载路径均引用它);
`role-template.yaml` 的 `apiGroups` 与 `ui/src/views/AuditLogList.vue` 的 `role-template.yaml` 的 `apiGroups` 与 build.gradle `openApi.groupingRules.pathsToMatch`
`QUERY_ENDPOINT` 需与其保持一致。⚠️ group 是已落库数据的身份标识,一旦插件启用并 需与其保持一致。⚠️ group 是已落库数据的身份标识,一旦插件启用并
产生审计记录,再改 group 会导致旧记录不可见,届时请勿随意变更。 产生审计记录,再改 group 会导致旧记录不可见,届时请勿随意变更。
- **UI 权限标识**:`plugin:operation-audit:view`(role-template.yaml 与 `ui/src/index.ts` - **UI 权限标识**:`plugin:operation-audit:view`(role-template.yaml 与 `ui/src/index.ts`
保持一致即可,如需改名请两处同步)。 保持一致即可,如需改名请两处同步)。
## 已知局限(对应产品设计第 7 节) ## 已知局限(对应产品设计第 7 节)
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2),记为"未知用户";
登录失败告警同样不含尝试的用户名,仅含失败次数与最近一次来源 IP/User-Agent。
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等) - 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)
不记录(几乎均伴随页面/API 操作,已被过滤器捕获)。 不记录(几乎均伴随页面/API 操作,已被过滤器捕获)。
- 系统内部变更的描述由事件类型推导(更新/删除),无法像页面操作那样区分"定时发布/恢复" - 系统内部变更的描述由事件类型推导(更新/删除),无法像页面操作那样区分"定时发布/恢复"
@@ -102,13 +130,25 @@ Console「插件 → 操作审计 → 设置」:
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口;角色模板已对普通授权 - 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口;角色模板已对普通授权
角色收紧到 `get`/`list`)。 角色收紧到 `get`/`list`)。
- 审计写入失败静默降级为运行日志,不阻塞业务操作。 - 审计写入失败静默降级为运行日志,不阻塞业务操作。
- **字段级 diff 的脱敏只按字段名匹配** `password|passwd|secret|token|credential`
(`ChangeDiffEngine.SENSITIVE_FIELD`):`apiKey`、`accessKey`、`accessKeyId`、`privateKey`、
`authHeader` 等命名的值会**原样落库**并在详情与 CSV 中可见。审计覆盖全后台写操作,
第三方插件资源里这类字段很常见——在扩展规则前,请勿让本插件记录含此类凭据的写入,
或先把凭据放进 Halo `Secret`(Secret 的值不会被字段级 diff 展开)。
- 来源 IP 取自 Halo HTTP 服务器解析后的地址(含 forwarding 配置): - 来源 IP 取自 Halo HTTP 服务器解析后的地址(含 forwarding 配置):
反向代理未配置 forwarded header 时,记录到的是代理 IP;系统内部变更记录无 IP/UA。 反向代理未配置 forwarded header 时,记录到的是代理 IP;系统内部变更记录无 IP/UA。
- **Windows 升级注意事项**:插件运行期间其 JAR 被进程锁定(Windows 文件锁),
`upgrade` API 报 500(`FileSystemException: 另一个程序正在使用此文件`),停用插件后
句柄也不释放。Windows 站点升级本插件需停服换 JAR 后重启;Linux/macOS 无此限制。
## 技术说明 ## 技术说明
- 目标平台 Halo 2.26.1(JDK 21)。捕获经 `AfterSecurityWebFilter` 扩展点(认证之后, - 目标平台 Halo 2.26.1(JDK 21)。捕获经双过滤器扩展点分治:`/apis/**` 写操作走
`doFinally` 读最终状态码);存储为自定义 Extension + 索引查询,全程响应式非阻塞。 `AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证操作 `POST /login`、
`POST /logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器
命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证操作请求,
必须在链首承接(操作者记"未知用户",登录尝试账号由请求体白名单提取)。存储为自定义
Extension + 索引查询,全程响应式非阻塞。
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有 - 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
扩展模型写入(回调在写入链内执行,全程捕获异常不影响业务):Halo 对仅 status 变化 扩展模型写入(回调在写入链内执行,全程捕获异常不影响业务):Halo 对仅 status 变化
或无实际变化的更新不派发事件,回收站清理走存储层不产生事件,天然降噪;HTTP 写请求 或无实际变化的更新不派发事件,回收站清理走存储层不产生事件,天然降噪;HTTP 写请求
@@ -121,18 +161,53 @@ Console「插件 → 操作审计 → 设置」:
遍历全量,流式输出 CSV——升序保证导出期间并发写入不打乱分页边界。 遍历全量,流式输出 CSV——升序保证导出期间并发写入不打乱分页边界。
- 定时清理采用 Reactor 调度方案(技术方案风险项 #3 预案),不依赖 `@Scheduled` - 定时清理采用 Reactor 调度方案(技术方案风险项 #3 预案),不依赖 `@Scheduled`
在插件上下文的可用性。 在插件上下文的可用性。
- **API 客户端生成**(官方检查清单第 2 条):Console UI 的 TS 类型与请求方法全部由
devtools `generateApiClient` 生成(`ui/src/api/generated`),UI 经 `ui/src/api/index.ts`
封装层注入宿主 `axiosInstance` 调用,不手写类型/端点路径,不裸 `fetch`。管线配置在
build.gradle `haloPlugin.openApi`(groupingRules 限定自有子资源端点,`AuditLog`
模型类型经响应 schema 引用生成);规范 JSON 落盘 `build/openapi/`(不入库)。
当前入库的规范文件为 **bootstrap 契约**(`build/openapi/extensionApis.json` 的一次性
手工对齐产物,与 Springdoc 声明一一对应)——生成任务需从运行中的 Halo 抓取
OpenAPI 文档(需 Docker 或 `useExistingServer`),待环境可用时运行
`./gradlew generateOpenApiDocs generateApiClient` 即以运行时契约覆盖重生成;
此后修改 API 契约一律改后端 Springdoc 声明再重跑生成任务。
- 登录失败告警(产品设计 V2「告警通知」):触发点在捕获过滤器(POST `/login` 结束, - 登录失败告警(产品设计 V2「告警通知」):触发点在捕获过滤器(POST `/login` 结束,
经 `CaptureRule.isLoginAttempt` 判定),`LoginFailureAlertService` 维护阈值窗口状态 经 `CaptureRule.isLoginAttempt` 判定),`LoginFailureAlertService` 维护阈值窗口状态
(告警后重开窗口防轰炸,登录成功清零;状态为单例计数,无内存队列),设置经 (告警后重开窗口防轰炸,登录成功清零;状态为单例计数,无内存队列),设置经
`AlertSettingProvider`(60s TTL 缓存)读取、独立于审计开关;`AlertWebhookSender` `AlertSettingProvider`(60s TTL 缓存)读取、独立于审计开关;Webhook 地址存于
以 JSON POST 异步推送(fire-and-forget,超时 10 秒、失败不重试不抛出)。 Halo `Secret`(键 `webhookUrl`,设置仅存引用名,fail closed:引用缺失/Secret 缺键
- 关于测试:`./gradlew test`(当前 188 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、 绝不发送);`AlertWebhookSender` 以 JSON POST 异步推送(fire-and-forget,超时
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、查询端点参数校验、导出 CSV 10 秒、失败不重试不抛出)。
- **出站安全(SSRF 防护,官方《敏感数据与出站请求》指南)**:`OutboundUrlGuard`
在发送前校验 Webhook 地址——URI 解析 + scheme 白名单(http/https)+ 禁止用户名/
密码形态;解析全部 A/AAAA 记录(boundedElastic 调度,不阻塞事件循环),任一地址
命中环回/私网/链路本地/组播/未指定/云元数据(169.254.169.254、100.100.100.200、
fd00:ec2::254 等)/CGNAT/ULA/Teredo/6to4/文档与保留段即整体拒绝;通过后以
`PinnedAddressResolverGroup` 钉定校验地址建连(DNS rebinding 防护,TLS SNI/Host
头仍取原主机名),重定向显式关闭,连接/响应/整体三层超时 10 秒,响应体不落内存
(toBodilessEntity)。校验失败归一为失败结果,消息只含类别描述,不回显完整地址。
- 登录尝试用户名(功能评审 P0-1):`LoginAttemptCapture` 为登录端点单独缓存请求体
(表单/JSON 双形态,Content-Length 预检 + 64KB 上限,下游可重复读),字段白名单制
仅提取 `username` 并经现有敏感字段脱敏规则兜底,随 `spec.attemptedUsername` 落库
并进入告警负载;与审计开关、告警开关均无关(消费方各自决定是否使用)。
- Webhook 测试告警(功能评审 P0-2):`AlertWebhookSender.sendForResult` 在
fire-and-forget 推送之外提供结果化推送(送达与否 + 原因摘要,超时/网络错误/非 2xx/
地址校验拒绝一律归一为失败结果,永不抛出,真实告警路径语义不变);`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`(当前 286 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为(含认证端点仅记录
`POST /login`、`POST /logout`,登录成败判定与结果语义)、登录尝试用户名提取
(表单/JSON/白名单/脱敏兜底/降级)、查询端点参数校验、导出 CSV
(BOM/表头/转义/注入防护/分批取数)、操作描述与语义动作标注推导(与前端 (BOM/表头/转义/注入防护/分批取数)、操作描述与语义动作标注推导(与前端
describeOperation / deriveAction 用例一一对应)、设置缓存与保留期清理、登录失败告警 describeOperation / deriveAction 用例一一对应)、设置缓存与保留期清理、登录失败告警
(阈值窗口推进/告警防轰炸/成功清零/设置归一/真实 HTTP 推送与静默降级);Console UI 以 (阈值窗口推进/告警防轰炸/成功清零/设置归一/Secret 地址解析 fail closed/真实 HTTP
vitest 断言 推送与静默降级/建连钉定证明/Webhook 结果化推送与测试端点反馈/测试负载结构)、
路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)+ 类型检查 + 构建通过为准 出站地址守卫(结构校验/危险地址段枚举/IPv4 映射内嵌/日志主机名卫生);
Console UI 以 vitest 断言路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)、
生成客户端链路形态(不手写端点/不裸 fetch)、导出下载链路 + 类型检查 + 构建通过为准
(技术方案 §7,MVP 不引入组件测试)。 (技术方案 §7,MVP 不引入组件测试)。
## 开发 ## 开发
@@ -144,4 +219,16 @@ cd plugin-operation-audit
./gradlew haloServer # 启动开发用 Halo(devtools,需 Docker) ./gradlew haloServer # 启动开发用 Halo(devtools,需 Docker)
``` ```
**API 客户端再生成**(后端 Springdoc 契约变更后执行):
```bash
./gradlew generateOpenApiDocs generateApiClient
# generateOpenApiDocs 需运行中的 Halo:Docker(haloServer)或
# haloPlugin.openApi.useExistingServer = true + apiDocsUrl 指向现有实例
```
生成产物落在 `ui/src/api/generated`(每次先清空重生成,禁止手改);
`build/openapi/extensionApis.json` 为规范 JSON(不入库;当前为 bootstrap 手工对齐契约,
详见技术说明「API 客户端生成」)。
前端独立开发:`cd ui && npm install && npm run dev`(watch 构建)。 前端独立开发:`cd ui && npm install && npm run dev`(watch 构建)。
+48 -3
View File
@@ -38,14 +38,17 @@ test {
} }
} }
// 将 ui 子项目构建产物打包进插件 jar 的 console/ 目录(Console 前端入口由 ui-plugin.json 清单声明) // 将 ui 子项目构建产物打包进插件 jar 的 ui/ 目录(Console 前端入口由 ui-plugin.json 清单声明)。
// 目标 Halo >=2.25.0 时 ui/ 是官方规范输出位置;console/ 为旧项目兼容回退,本插件不再使用。
tasks.register('processUiResources', Copy) { tasks.register('processUiResources', Copy) {
from project(':ui').layout.buildDirectory.dir('dist') from project(':ui').layout.buildDirectory.dir('dist')
into layout.buildDirectory.dir('resources/main/console') into layout.buildDirectory.dir('resources/main/ui')
dependsOn project(':ui').tasks.named('assemble') dependsOn project(':ui').tasks.named('assemble')
shouldRunAfter tasks.named('processResources') shouldRunAfter tasks.named('processResources')
// 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar // 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar;
// 同时清掉旧构建可能残留的 console/ 目录,防止过期产物被打进 jar
doFirst { doFirst {
delete layout.buildDirectory.dir('resources/main/ui')
delete layout.buildDirectory.dir('resources/main/console') delete layout.buildDirectory.dir('resources/main/console')
} }
} }
@@ -61,3 +64,45 @@ tasks.named('generatePluginComponentsIdx') {
halo { halo {
version = '2.26.1' version = '2.26.1'
} }
// API 客户端生成(官方检查清单第 2 条):UI 的 TS 类型与请求方法一律由
// generateApiClient 任务生成,禁止手写。管线两步:
// 1) ./gradlew generateOpenApiDocs —— 从运行中的 Halo(Docker haloServer 或
// useExistingServer 指向的实例)抓取 /v3/api-docs/extensionApis,按 groupingRules
// 过滤插件路径,落盘到 openApi.outputDir(每次生成先清空,须为专属目录);
// 2) ./gradlew generateApiClient —— 读取上一步的规范 JSON,产出 TS 客户端到
// generator.outputDir(同样先清空;产物入库,UI 经 ui/src/api 封装层调用)。
haloPlugin {
openApi {
// 规范 JSON 落盘目录(generateOpenApiDocs 产物 / generateApiClient 输入;
// 每次生成先清空,须为专属目录,位于 build/ 下不入库)
outputDir = file("${projectDir}/build/openapi")
// 仅覆盖插件自有子资源端点(/-/query、/-/export、/-/test);
// AuditLog 模型类型经响应 schema 引用一并生成
groupingRules {
extensionApis {
displayName = 'Operation Audit Extension API'
pathsToMatch = [
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/**',
'/apis/audit.guichumo.com/v1alpha1/alerts/-/**',
]
}
}
groupedApiMappings = [
'/v3/api-docs/extensionApis': 'extensionApis.json'
]
generator {
outputDir = file("${projectDir}/ui/src/api/generated")
additionalProperties = [
useES6 : 'true',
useSingleRequestParameter : 'true',
withSeparateModelsAndApi : 'true',
apiPackage : 'api',
modelPackage : 'models',
]
typeMappings = [
set: 'Array'
]
}
}
}
Vendored Regular → Executable
View File
@@ -0,0 +1,31 @@
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);
}
/** 失败结果(原因摘要已就绪,如 SSRF 校验拒绝的类别描述)。 */
public static AlertSendResult failure(String message) {
return new AlertSendResult(false, message);
}
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);
}
}
@@ -4,14 +4,21 @@ import java.time.Duration;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Secret;
import run.halo.app.plugin.ReactiveSettingFetcher; import run.halo.app.plugin.ReactiveSettingFetcher;
/** /**
* 告警设置的短 TTL 缓存读取(与审计设置 {@code AuditSettingProvider} 同款模式,技术方案 D6)。 * 告警设置的短 TTL 缓存读取(与审计设置 {@code AuditSettingProvider} 同款模式,技术方案 D6),
* 以及 Webhook 地址的 Secret 解析。
* *
* <p>开关变更最多延迟 1 分钟生效——告警为旁路功能,可接受。读取失败或未配置时 * <p>凭据安全(官方《敏感数据与出站请求》指南):Setting 只存 Secret 引用名,
* 静默回退默认值(关闭告警),绝不影响登录与审计主流程。 * 真实 Webhook 地址(可能内嵌 access_token)存于 Halo {@code Secret},经
* {@link ReactiveExtensionClient} 按需读取;解析失败以错误信号报出(调用方决定
* 降级方式:真实告警路径静默跳过,测试告警端点转为 400 提示),消息只含引用名
* 与键名,绝不携带 Secret 内容。
*/ */
@Slf4j @Slf4j
@Component @Component
@@ -21,7 +28,11 @@ public class AlertSettingProvider {
/** 缓存有效期(与审计设置缓存一致)。 */ /** 缓存有效期(与审计设置缓存一致)。 */
public static final Duration TTL = Duration.ofSeconds(60); public static final Duration TTL = Duration.ofSeconds(60);
/** Webhook 地址在 Secret stringData 中的字段名(与 settings.yaml requiredKeys 一致)。 */
public static final String WEBHOOK_URL_FIELD = "webhookUrl";
private final ReactiveSettingFetcher fetcher; private final ReactiveSettingFetcher fetcher;
private final ReactiveExtensionClient client;
/** TTL 缓存条目;包内可见以便测试构造过期条目。 */ /** TTL 缓存条目;包内可见以便测试构造过期条目。 */
record CacheEntry(AlertSettings value, long expireAtNanos) { record CacheEntry(AlertSettings value, long expireAtNanos) {
@@ -50,4 +61,33 @@ public class AlertSettingProvider {
.defaultIfEmpty(AlertSettings.defaults()) .defaultIfEmpty(AlertSettings.defaults())
.doOnNext(value -> cache = new CacheEntry(value, System.nanoTime() + TTL.toNanos())); .doOnNext(value -> cache = new CacheEntry(value, System.nanoTime() + TTL.toNanos()));
} }
/** 便捷解析:先读设置再解析 Webhook 地址(测试告警端点用)。 */
public Mono<String> webhookUrl() {
return get().flatMap(this::webhookUrl);
}
/**
* 从设置引用的 Halo Secret 解析 Webhook 地址。
*
* <p>未配置引用、Secret 不存在、缺少 {@link #WEBHOOK_URL_FIELD} 字段均以
* {@link IllegalStateException} 报错(fail closed:配置不完整绝不发送),
* 消息不含 Secret 内容;真实告警路径捕获后静默跳过,测试端点转为 400。
*/
public Mono<String> webhookUrl(AlertSettings settings) {
var secretName = settings.webhookSecretNameOrDefault();
if (secretName == null) {
return Mono.error(new IllegalStateException(
"Webhook 地址未配置(需在设置中选择或创建 Secret),请先保存设置"));
}
return client.fetch(Secret.class, secretName)
.switchIfEmpty(Mono.error(new IllegalStateException(
"Webhook Secret 不存在(" + secretName + "),请检查设置")))
// mapNotNull:字段缺失(null)或空白都归一为空 → switchIfEmpty 统一报错
.mapNotNull(secret -> secret.getStringData().get(WEBHOOK_URL_FIELD))
.map(String::trim)
.filter(StringUtils::hasText)
.switchIfEmpty(Mono.error(new IllegalStateException(
"Webhook Secret 缺少 " + WEBHOOK_URL_FIELD + " 字段,请更新 Secret")));
}
} }
@@ -3,10 +3,14 @@ package run.halo.operationaudit.alert;
/** /**
* 告警通知设置(存储于插件 ConfigMap 的 {@code alerts} 组,独立于审计设置组)。 * 告警通知设置(存储于插件 ConfigMap 的 {@code alerts} 组,独立于审计设置组)。
* *
* <p>取值经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值; * <p>凭据安全(官方《敏感数据与出站请求》指南):Webhook 地址可能内嵌 access_token
* Webhook 地址非 http(s) 或为空时归一为 null(调用方静默跳过发送)。 * 等凭据,本记录只持有 Halo {@code Secret} 的引用名({@code webhookSecretName}),
* 真实地址存于 Secret 的 {@code webhookUrl} 键,由
* {@link AlertSettingProvider#webhookUrl()} 按需解析,绝不落 ConfigMap、日志或状态。
*
* <p>取值经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值。
*/ */
public record AlertSettings(Boolean enabled, String webhookUrl, Integer thresholdCount, public record AlertSettings(Boolean enabled, String webhookSecretName, Integer thresholdCount,
Integer windowMinutes) { Integer windowMinutes) {
/** ConfigMap 中的配置组名(settings.yaml 的告警通知表单组)。 */ /** ConfigMap 中的配置组名(settings.yaml 的告警通知表单组)。 */
@@ -25,20 +29,12 @@ public record AlertSettings(Boolean enabled, String webhookUrl, Integer threshol
return enabled != null && enabled; return enabled != null && enabled;
} }
/** /** 归一 Secret 引用名:空白返回 null(未配置,调用方静默跳过发送)。 */
* 归一 Webhook 地址:空白或非 http(s) 开头返回 null(不可用,调用方静默跳过), public String webhookSecretNameOrDefault() {
* 其余去除首尾空白后返回。 if (webhookSecretName == null || webhookSecretName.isBlank()) {
*/
public String webhookUrlOrDefault() {
if (webhookUrl == null) {
return null; return null;
} }
var trimmed = webhookUrl.trim(); return webhookSecretName.trim();
var lower = trimmed.toLowerCase();
if (trimmed.isEmpty() || !(lower.startsWith("http://") || lower.startsWith("https://"))) {
return null;
}
return trimmed;
} }
/** 触发阈值:小于 1 视为非法回退默认。 */ /** 触发阈值:小于 1 视为非法回退默认。 */
@@ -0,0 +1,106 @@
package run.halo.operationaudit.alert;
import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder;
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;
import run.halo.operationaudit.audit.AuditQueryEndpoint;
/**
* 告警测试端点(功能评审 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 地址经 {@link AlertSettingProvider#webhookUrl()} 从 Halo {@code Secret}
* 解析(Setting 只存 Secret 引用,凭据不出 Secret);未配置引用、Secret 不存在或缺键
* 返回 400;地址校验(SSRF 防护,见 {@link OutboundUrlGuard})与推送失败不抛出——
* 以 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")
.tag(AuditQueryEndpoint.TAG)
.description("向当前配置的 Webhook 地址推送一条测试告警(type=test)并返回"
+ "推送结果:success 为是否送达(接收方 2xx),message 为状态/原因摘要;"
+ "Webhook 未配置或非法时返回 400")
.response(responseBuilder().responseCode("200")
.description("推送结果")
.implementation(AlertSendResult.class))
.build())
.build();
}
private Mono<ServerResponse> test(ServerRequest request) {
return settingProvider.webhookUrl()
.flatMap(url -> sender.sendForResult(url, buildTestPayload(Instant.now()))
.doOnNext(result -> {
if (result.success()) {
log.info("Test alert sent to {}: {}",
OutboundUrlGuard.urlHost(url), result.message());
} else {
log.warn("Failed to send test alert to {}: {}",
OutboundUrlGuard.urlHost(url), result.message());
}
})
.flatMap(result -> ServerResponse.ok().bodyValue(result)))
// 未配置引用 / Secret 不存在 / 缺键:设置问题归一为 400(消息不含 Secret 内容)
.onErrorResume(e -> {
if (e instanceof IllegalStateException ise) {
return ServerResponse.badRequest()
.bodyValue(Map.of("message", String.valueOf(ise.getMessage())));
}
return Mono.error(e);
});
}
/**
* 组装测试告警负载:与真实告警同结构(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";
}
@@ -2,47 +2,91 @@ package run.halo.operationaudit.alert;
import java.time.Duration; import java.time.Duration;
import java.util.Map; import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
/** /**
* 告警 Webhook 推送器:向配置地址异步 POST JSON 负载。 * 告警 Webhook 推送器:向配置地址异步 POST JSON 负载。
* *
* <p>fire-and-forget(产品设计原则 4):超时 10 秒后放弃,失败(网络错误、非 2xx 响应、 * <p>fire-and-forget(产品设计原则 4):超时 10 秒后放弃,失败(网络错误、非 2xx 响应、
* URL 非法)仅记 warn 日志,不重试、不抛出,绝不影响登录与审计主流程。 * 地址非法)仅记 warn 日志,不重试、不抛出,绝不影响登录与审计主流程。
* *
* <p>负载为通用 JSON 结构(type/title/content/timestamp/data),不内置钉钉、企业微信、 * <p>负载为通用 JSON 结构(type/title/content/timestamp/data),不内置钉钉、企业微信、
* 飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。 * 飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
*
* <p>功能评审 P0-2:{@link #sendForResult(String, Map)}——返回推送结果
* (送达与否 + 原因摘要)供测试告警端点同步反馈到设置页;登录失败告警路径
* 仍走 {@link #send(String, Map)}(fire-and-forget 语义不变)。
*
* <p>出站安全(官方《敏感数据与出站请求》指南):发送前经 {@link OutboundUrlGuard}
* 完成 SSRF 校验(scheme/主机名/用户信息/端口 + 全量 DNS 解析危险地址段拒绝),
* 建连钉定校验通过的地址(DNS rebinding 防护);重定向显式关闭;连接/响应/整体
* 三层超时(10 秒);响应体不落内存(toBodilessEntity)。校验失败归一为
* {@link AlertSendResult#failure(String)},永不抛出。
*/ */
@Slf4j @Slf4j
@Component @Component
@RequiredArgsConstructor
public class AlertWebhookSender { public class AlertWebhookSender {
/** 发送超时:告警为旁路功能,超时即放弃(不重试)。 */ /** 发送超时:告警为旁路功能,超时即放弃(不重试)。 */
private static final Duration TIMEOUT = Duration.ofSeconds(10); private static final Duration TIMEOUT = Duration.ofSeconds(10);
private final WebClient webClient; private final OutboundUrlGuard guard;
public AlertWebhookSender() { /** 异步推送 JSON 负载;任何失败仅记 warn 日志(只记主机名,不记可能含凭据的地址)。 */
this.webClient = WebClient.builder().build(); public void send(String url, Map<String, Object> payload) {
sendForResult(url, payload).subscribe(result -> {
if (!result.success()) {
log.warn("Failed to send alert webhook to {}: {}",
OutboundUrlGuard.urlHost(url), result.message());
}
});
} }
/** 异步推送 JSON 负载;任何失败仅记 warn 日志,不影响调用方。 */ /**
public void send(String url, Map<String, Object> payload) { * 推送 JSON 负载并返回结果(功能评审 P0-2):成功为接收方 2xx;超时、网络错误、
try { * 非 2xx、地址校验失败等任何失败均归一为失败结果,绝不抛出、绝不重试。
webClient.post() *
.uri(url) * <p>返回的 Mono 永不为空、永不报错,超时上限与 fire-and-forget 路径一致
* (10 秒)——测试告警端点同步等待该结果反馈到设置页。
*/
public Mono<AlertSendResult> sendForResult(String url, Map<String, Object> payload) {
return guard.validate(url)
.flatMap(target -> sendToTarget(target, payload))
.onErrorResume(OutboundUrlGuard.InvalidUrlException.class,
e -> Mono.just(AlertSendResult.failure(e.getMessage())));
}
/**
* 向已完成 SSRF 校验并钉定地址的目标推送(包内可见以便测试直接构造回环目标,
* 绕过守卫测试 HTTP 机制本身)。
*/
Mono<AlertSendResult> sendToTarget(OutboundUrlGuard.ValidatedTarget target,
Map<String, Object> payload) {
var httpClient = HttpClient.create()
// 建连钉定校验通过的地址:TLS SNI/Host 头仍取原始主机名,证书校验不受影响
.resolver(new PinnedAddressResolverGroup(target.toSocketAddress()))
// Webhook 无重定向语义:显式关闭,杜绝跳转绕过目标校验
.followRedirect(false)
.responseTimeout(TIMEOUT);
return Mono.defer(() -> WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build()
.post()
.uri(target.uri())
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.bodyValue(payload) .bodyValue(payload)
.retrieve() .retrieve()
.toBodilessEntity() .toBodilessEntity())
.timeout(TIMEOUT) .timeout(TIMEOUT)
.subscribe(null, e -> log.warn("Failed to send alert webhook to {}", url, e)); .map(response -> AlertSendResult.ok(response.getStatusCode().value()))
} catch (Exception e) { .onErrorResume(e -> Mono.just(AlertSendResult.failure(e)));
// URL 非法等同步异常同样静默降级,绝不影响调用方
log.warn("Failed to initiate alert webhook to {}", url, e);
}
} }
} }
@@ -7,6 +7,7 @@ import java.util.Map;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import run.halo.operationaudit.audit.RequestSnapshot; import run.halo.operationaudit.audit.RequestSnapshot;
/** /**
@@ -14,14 +15,17 @@ import run.halo.operationaudit.audit.RequestSnapshot;
* 推送一次 JSON 告警。 * 推送一次 JSON 告警。
* *
* <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}): * <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}):
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击 * 登录成功立即清零计数,失败累计。成败由过滤器经 {@code LoginOutcome} 判定后传入——
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。 * 表单登录的成功与失败均为 302 重定向,以重定向目标是否含 {@code error} 参数区分,
* 不能只看状态码。告警后重开窗口(同一攻击波次不会连环轰炸,下次告警需再次达到阈值);
* 窗口过期同样重开,无失败时不累计。
* *
* <p>登录失败暂无法得知尝试的用户名(产品设计已知局限,与登录记录一致),告警负载 * <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
* 仅含失败次数、窗口、最近一次来源 IP 与 User-Agent。 * (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
* *
* <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关 * <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关
* 相互独立。任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。 * 相互独立;Webhook 地址凭据存于 Halo Secret(Setting 只存引用),解析失败静默跳过。
* 任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
*/ */
@Slf4j @Slf4j
@Component @Component
@@ -38,30 +42,59 @@ public class LoginFailureAlertService {
int failureCount; int failureCount;
/** /**
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。 * 登录结果回调:仅处理 POST /login 请求(成功清零计数,失败累计告警)。
* 任何失败静默降级,不影响调用方。 * 成败由调用方(捕获过滤器)经 {@code LoginOutcome} 判定后传入,本服务不做
* 状态码推断。任何失败静默降级,不影响调用方。
*
* @param success 登录是否成功(表单登录 302 重定向目标含 error 参数或
* 响应 4xx/5xx 为失败;2xx 与成功重定向为成功)
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
* 提取失败为 null)
*/ */
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode) { public void onLoginResult(RequestSnapshot snapshot, boolean success,
var success = statusCode != null && statusCode >= 200 && statusCode < 300; String attemptedUsername) {
settingProvider.get().subscribe( 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 {}", e -> log.warn("Failed to load alert settings, skip login alert for {}",
snapshot.getFullPath(), e)); snapshot.getFullPath(), e));
} }
/** /**
* 阈值窗口判定与告警决策。now 由调用方传入(测试可控);发送在锁外执行。 * 告警入口:开关开启时先解析 Webhook 地址(凭据存于 Halo Secret,见
* handle 包内可见以便测试直接驱动窗口推进。 * {@link AlertSettingProvider#webhookUrl(AlertSettings)}),未配置/读取失败则
* 静默跳过(既不计数也不告警,与旧版"无地址不计数"语义一致);地址可用后进入
* 阈值窗口判定。now 由调用方传入(测试可控)。
*
* <p>handle 包内可见以便测试直接驱动。
*/ */
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success, Instant now) { void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success,
String attemptedUsername, Instant now) {
try { try {
if (!settings.enabledOrDefault()) { if (!settings.enabledOrDefault()) {
return; return;
} }
var url = settings.webhookUrlOrDefault(); settingProvider.webhookUrl(settings)
if (url == null) { .onErrorResume(e -> {
return; log.warn("Failed to resolve webhook url, skip login alert for {}",
snapshot.getFullPath(), e);
return Mono.empty();
})
.subscribe(url -> countAndAlert(url, settings, snapshot, success,
attemptedUsername, now));
} catch (Exception e) {
// 告警为旁路功能,任何异常静默降级,绝不影响登录主流程
log.warn("Failed to handle login failure alert for {}",
snapshot.getFullPath(), e);
} }
}
/**
* 阈值窗口判定与告警决策(Webhook 地址已解析)。发送在锁外执行。
* countAndAlert 包内可见以便测试直接驱动窗口推进。
*/
void countAndAlert(String url, AlertSettings settings, RequestSnapshot snapshot,
boolean success, String attemptedUsername, Instant now) {
try {
var window = Duration.ofMinutes(settings.windowMinutesOrDefault()); var window = Duration.ofMinutes(settings.windowMinutesOrDefault());
int failures; int failures;
synchronized (stateLock) { synchronized (stateLock) {
@@ -85,7 +118,7 @@ public class LoginFailureAlertService {
failureCount = 0; failureCount = 0;
} }
sender.send(url, buildPayload(failures, settings.windowMinutesOrDefault(), sender.send(url, buildPayload(failures, settings.windowMinutesOrDefault(),
snapshot.getRemoteIp(), snapshot.getUserAgent(), now)); snapshot.getRemoteIp(), snapshot.getUserAgent(), attemptedUsername, now));
} catch (Exception e) { } catch (Exception e) {
// 告警为旁路功能,任何异常静默降级,绝不影响登录主流程 // 告警为旁路功能,任何异常静默降级,绝不影响登录主流程
log.warn("Failed to handle login failure alert for {}", log.warn("Failed to handle login failure alert for {}",
@@ -98,16 +131,19 @@ public class LoginFailureAlertService {
* data 供程序化消费方取结构化字段。 * data 供程序化消费方取结构化字段。
*/ */
static Map<String, Object> buildPayload(int failures, int windowMinutes, String remoteIp, 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 + " 次登录失败,最近一次来自 " var content = windowMinutes + " 分钟内出现 " + failures + " 次登录失败,最近一次来自 "
+ remoteIp + (userAgent != null && !userAgent.isBlank() + remoteIp + (userAgent != null && !userAgent.isBlank()
? "(" + userAgent + ")" : "") ? "(" + userAgent + ")" : "")
+ (attemptedUsername != null && !attemptedUsername.isBlank()
? ",尝试的账号:" + attemptedUsername : "")
+ "。可在 Console「操作审计」查看详情。"; + "。可在 Console「操作审计」查看详情。";
var data = new LinkedHashMap<String, Object>(); var data = new LinkedHashMap<String, Object>();
data.put("failures", failures); data.put("failures", failures);
data.put("windowMinutes", windowMinutes); data.put("windowMinutes", windowMinutes);
data.put("remoteIp", remoteIp); data.put("remoteIp", remoteIp);
data.put("userAgent", userAgent); data.put("userAgent", userAgent);
data.put("attemptedUsername", attemptedUsername);
var payload = new LinkedHashMap<String, Object>(); var payload = new LinkedHashMap<String, Object>();
payload.put("type", "login-failure"); payload.put("type", "login-failure");
payload.put("title", "操作审计告警:登录失败"); payload.put("title", "操作审计告警:登录失败");
@@ -0,0 +1,246 @@
package run.halo.operationaudit.alert;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
/**
* 用户可配置出站地址的 SSRF 防护(官方《敏感数据与出站请求》指南):
*
* <ol>
* <li>URI 解析 + 白名单式 scheme 校验(仅 http/https),禁止用户名/密码形态
* ({@code user:pass@host})与不支持的结构;</li>
* <li>解析目标的全部 IPv4/IPv6 地址(DNS 查询经 boundedElastic 调度,不阻塞事件循环),
* 任一地址命中环回、私网、链路本地、组播、未指定、云平台元数据及保留段即整体拒绝
* (连接可能选择任意一条记录);</li>
* <li>校验通过后钉定(pin)第一个可用地址:建连走 {@link PinnedAddressResolverGroup},
* DNS 校验结果与实际建连使用同一地址,杜绝 DNS rebinding 的"校验时公网、
* 建连时内网"窗口;TLS SNI/Host 头仍取原始主机名,证书校验不受影响。</li>
* </ol>
*
* <p>重定向由 WebClient 默认不跟随(显式声明关闭);超时与响应体边界由
* {@link AlertWebhookSender} 承担。校验失败以 {@link InvalidUrlException} 报错,
* 消息只含主机名或类别描述,绝不回显完整地址(Webhook 地址可能内嵌
* access_token 等凭据,不得进入日志与错误响应)。
*/
@Slf4j
@Component
public class OutboundUrlGuard {
/** 业务需要的协议白名单:Webhook 接收方为 http(s)。 */
private static final Set<String> ALLOWED_SCHEMES = Set.of("http", "https");
/** http/https 的默认端口(URL 未显式给出端口时使用)。 */
private static final int DEFAULT_HTTP_PORT = 80;
private static final int DEFAULT_HTTPS_PORT = 443;
/**
* 校验并解析出站目标:返回钉定地址与结构化 URI。
*
* <p>永不返回空 Mono;非法地址以 {@link InvalidUrlException} 报错,由调用方归一为
* 失败结果(fire-and-forget 语义不变)。DNS 解析调度在 boundedElastic。
*/
public Mono<ValidatedTarget> validate(String url) {
return Mono.fromSupplier(() -> checkStructure(url))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(this::resolvePinned);
}
/** 结构校验:scheme/主机名/用户信息/端口。返回解析后的 URI。 */
static URI checkStructure(String url) {
if (url == null || url.isBlank()) {
throw new InvalidUrlException("Webhook 地址为空,请先在设置中配置");
}
URI uri;
try {
uri = new URI(url.trim());
} catch (URISyntaxException e) {
throw new InvalidUrlException("Webhook 地址无法解析");
}
var scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase();
if (!ALLOWED_SCHEMES.contains(scheme)) {
throw new InvalidUrlException("仅支持 http(s) 协议的 Webhook 地址");
}
if (uri.getHost() == null || uri.getHost().isBlank()) {
throw new InvalidUrlException("Webhook 地址缺少主机名");
}
if (uri.getUserInfo() != null) {
throw new InvalidUrlException("不支持用户名/密码形态的 Webhook 地址");
}
var port = uri.getPort();
if (port == -1) {
port = "https".equals(scheme) ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT;
} else if (port < 1 || port > 65535) {
throw new InvalidUrlException("Webhook 地址端口非法");
}
return uri;
}
/** 解析全部 A/AAAA 记录并检查危险地址段;返回钉定目标。 */
private Mono<ValidatedTarget> resolvePinned(URI uri) {
var host = uri.getHost();
var port = uri.getPort() == -1
? ("https".equalsIgnoreCase(uri.getScheme())
? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT)
: uri.getPort();
return Mono.fromCallable(() -> {
InetAddress[] addresses;
try {
addresses = InetAddress.getAllByName(host);
} catch (UnknownHostException e) {
throw new InvalidUrlException("Webhook 主机无法解析(" + host + ")");
}
if (addresses == null || addresses.length == 0) {
throw new InvalidUrlException("Webhook 主机无法解析(" + host + ")");
}
for (InetAddress address : addresses) {
if (isForbiddenAddress(address)) {
throw new InvalidUrlException("Webhook 主机解析到受限网络地址"
+ "(环回/内网/链路本地/云元数据等),已拒绝");
}
}
return new ValidatedTarget(uri, port, addresses[0]);
})
.subscribeOn(Schedulers.boundedElastic());
}
/**
* 危险地址段判定(官方指南:环回、私网、链路本地、组播、未指定与云平台元数据地址),
* 另按 OWASP SSRF 防护清单补充:CGNAT/共享地址段(100.64/10,含阿里云元数据
* 100.100.100.200)、IPv6 唯一本地地址(fc00::/7,含 AWS IMDS IPv6
* fd00:ec2::254)、IPv4 映射/兼容地址内嵌段、Teredo/6to4 过渡机制段、
* 文档与保留段(192.0.0/24、192.0.2/24、198.18/15、198.51.100/24、
* 203.0.113/24、2001:db8::/32)、本网络段(0/8)与保留广播段(240/4)。
*
* <p>包内可见以便测试直接枚举地址段。
*/
static boolean isForbiddenAddress(InetAddress address) {
if (address.isLoopbackAddress()
|| address.isAnyLocalAddress()
|| address.isLinkLocalAddress()
|| address.isMulticastAddress()
|| address.isSiteLocalAddress()) {
return true;
}
if (address instanceof Inet4Address) {
return isForbiddenIpv4(address.getAddress());
}
return isForbiddenIpv6(address.getAddress());
}
/**
* IPv4 保留/特殊段判定:除 isSiteLocalAddress 覆盖的私网段(10/8、172.16/12、
* 192.168/16)在此显式复查外(IPv6 内嵌 IPv4 路径不经 isSiteLocalAddress),
* 另含各保留与文档段。
*/
static boolean isForbiddenIpv4(byte[] a) {
int b0 = a[0] & 0xFF;
int b1 = a[1] & 0xFF;
int b2 = a[2] & 0xFF;
if (b0 == 0) {
return true; // 0/8 本网络段(0.0.0.0 未指定已在上层拦截)
}
if (b0 == 10 || b0 == 127) {
return true; // 10/8 私网(127/8 环回,内嵌路径复查)
}
if (b0 == 172 && (b1 & 0xF0) == 0x10) {
return true; // 172.16/12 私网
}
if (b0 == 192 && b1 == 168) {
return true; // 192.168/16 私网
}
if (b0 == 100 && (b1 & 0xC0) == 0x40) {
return true; // 100.64/10 共享地址段(含阿里云元数据 100.100.100.200)
}
if (b0 == 192 && b1 == 0 && (b2 == 0 || b2 == 2)) {
return true; // 192.0.0/24 与 192.0.2/24(专用/文档)
}
if (b0 == 198 && (b1 & 0xFE) == 18) {
return true; // 198.18/15 基准测试段
}
if (b0 == 198 && b1 == 51 && b2 == 100) {
return true; // 198.51.100/24 文档段
}
if (b0 == 203 && b1 == 0 && b2 == 113) {
return true; // 203.0.113/24 文档段
}
return (b0 & 0xF0) == 0xF0; // 240/4 保留段(含 255.255.255.255 广播)
}
/** IPv6 特殊段补充判定(Java 未覆盖的 ULA、过渡机制与映射段)。 */
static boolean isForbiddenIpv6(byte[] a) {
if ((a[0] & 0xFE) == 0xFC) {
return true; // fc00::/7 唯一本地地址(ULA;AWS IMDS IPv6 fd00:ec2::254 同段)
}
if (a[0] == 0x20 && a[1] == 0x02) {
return true; // 2002::/16 6to4(内嵌 IPv4,可绕过校验)
}
if (a[0] == 0x20 && a[1] == 0x01 && a[2] == 0x00 && a[3] == 0x00) {
return true; // 2001::/32 Teredo(内嵌 IPv4)
}
if (a[0] == 0x20 && a[1] == 0x01 && (a[2] & 0xFF) == 0x0D
&& (a[3] & 0xFF) == 0xB8) {
return true; // 2001:db8::/32 文档段
}
// IPv4 映射(::ffff:0:0/96)与 IPv4 兼容(::/96)地址:按内嵌 IPv4 再判
boolean leadingZero = true;
for (int i = 0; i < 10; i++) {
if (a[i] != 0) {
leadingZero = false;
break;
}
}
if (leadingZero && (a[10] & 0xFF) == 0xFF && (a[11] & 0xFF) == 0xFF) {
return isForbiddenIpv4(Arrays.copyOfRange(a, 12, 16));
}
boolean allZero = true;
for (int i = 0; i < 12; i++) {
if (a[i] != 0) {
allZero = false;
break;
}
}
if (allZero) {
return isForbiddenIpv4(Arrays.copyOfRange(a, 12, 16));
}
return false;
}
/** 日志/错误消息用的主机名提取:绝不回显可能内嵌凭据的完整地址。 */
public static String urlHost(String url) {
if (url == null || url.isBlank()) {
return "<unset>";
}
try {
var host = new URI(url.trim()).getHost();
return host == null ? "<unparsed>" : host;
} catch (URISyntaxException e) {
return "<unparsed>";
}
}
/** 校验通过的目标:钉定地址供建连使用(DNS rebinding 防护)。 */
public record ValidatedTarget(URI uri, int port, InetAddress address) {
public InetSocketAddress toSocketAddress() {
return new InetSocketAddress(address, port);
}
}
/** 非法出站地址(结构不合法、无法解析或命中危险地址段)。 */
public static final class InvalidUrlException extends RuntimeException {
public InvalidUrlException(String message) {
super(message);
}
}
}
@@ -0,0 +1,54 @@
package run.halo.operationaudit.alert;
import io.netty.resolver.AbstractAddressResolver;
import io.netty.resolver.AddressResolver;
import io.netty.resolver.AddressResolverGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
import java.net.InetSocketAddress;
import java.util.List;
/**
* 将建连钉定在已校验地址上的解析器组({@link OutboundUrlGuard} 的 DNS rebinding 防护):
* Netty 建连时对"主机名 → 地址"的解析不再查 DNS,一律返回校验通过的钉定地址
* (端口仍取请求地址自带端口)。DNS 校验结果与实际建连使用同一地址,杜绝"校验时解析到
* 公网、建连时解析到内网"的重绑定窗口;TLS SNI/Host 头仍取原始主机名,证书校验不受影响。
*
* <p>实例为单次请求作用域(每个目标新建),解析器无外部资源,不做全局缓存。
*/
final class PinnedAddressResolverGroup extends AddressResolverGroup<InetSocketAddress> {
private final InetSocketAddress pinned;
PinnedAddressResolverGroup(InetSocketAddress pinned) {
this.pinned = pinned;
}
@Override
protected AddressResolver<InetSocketAddress> newResolver(EventExecutor executor) {
return new AbstractAddressResolver<InetSocketAddress>(executor) {
@Override
protected boolean doIsResolved(InetSocketAddress address) {
return !address.isUnresolved();
}
@Override
protected void doResolve(InetSocketAddress address,
Promise<InetSocketAddress> promise) {
promise.trySuccess(pinned(address));
}
@Override
protected void doResolveAll(InetSocketAddress address,
Promise<List<InetSocketAddress>> promise) {
promise.trySuccess(List.of(pinned(address)));
}
/** 端口取请求地址(校验阶段已确定),地址取钉定结果。 */
private InetSocketAddress pinned(InetSocketAddress address) {
return new InetSocketAddress(pinned.getAddress(), address.getPort());
}
};
}
}
@@ -38,9 +38,12 @@ public class AuditLogCsvExporter {
/** 每批查询条数。 */ /** 每批查询条数。 */
static final int EXPORT_BATCH_SIZE = 200; static final int EXPORT_BATCH_SIZE = 200;
/** CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要)。 */ /**
* CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要,
* "尝试用户"列为登录尝试的用户名,功能评审 P0-1)。
*/
private static final String CSV_HEADER = private static final String CSV_HEADER =
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent"; "操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
private static final DataBufferFactory BUFFER_FACTORY = private static final DataBufferFactory BUFFER_FACTORY =
DefaultDataBufferFactory.sharedInstance; DefaultDataBufferFactory.sharedInstance;
@@ -100,19 +103,21 @@ public class AuditLogCsvExporter {
private String toCsvLine(AuditLog log) { private String toCsvLine(AuditLog log) {
var spec = log.getSpec(); var spec = log.getSpec();
var statusCode = spec.getStatusCode(); var statusCode = spec.getStatusCode();
// 结果语义与前端 isSuccessful 一致:2xx/3xx 成功,其余(含空)失败
var success = statusCode != null && statusCode >= 200 && statusCode < 400;
return String.join(",", return String.join(",",
escape(formatTime(log.getMetadata().getCreationTimestamp())), escape(formatTime(log.getMetadata().getCreationTimestamp())),
escape(spec.getUsername()), escape(spec.getUsername()),
escape(spec.getAttemptedUsername()),
escape(spec.getMethod()), escape(spec.getMethod()),
escape(spec.getResourceType()), escape(spec.getResourceType()),
escape(spec.getResourceName()), escape(spec.getResourceName()),
escape(spec.getPath()), escape(spec.getPath()),
escape(OperationDescription.describe( // 优先落库语义动作(含登录失败标注与页面访问纠正),历史记录回退
spec.getMethod(), spec.getResourceType(), spec.getPath())), // method/path 现场推导
escape(OperationDescription.describe(spec)),
escape(ChangeDiffEngine.formatChanges(spec.getChanges())), escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
escape(success ? "成功" : "失败"), // 结果语义与前端一致(AuditResult):登录失败标注一律失败(HTTP 状态码
// 可能是 302/200),认证端点的页面访问记录(历史 GET)不计成败,其余按状态码
escape(AuditResult.of(spec).label()),
escape(statusCode == null ? null : String.valueOf(statusCode)), escape(statusCode == null ? null : String.valueOf(statusCode)),
escape(spec.getRemoteIp()), escape(spec.getRemoteIp()),
escape(spec.getUserAgent())); escape(spec.getUserAgent()));
@@ -25,6 +25,22 @@ final class AuditLogFilters {
static final Set<String> FILTERABLE_FIELDS = Set.of("spec.username", "spec.resourceType", static final Set<String> FILTERABLE_FIELDS = Set.of("spec.username", "spec.resourceType",
"spec.method", "spec.action", "spec.statusCode"); "spec.method", "spec.action", "spec.statusCode");
/**
* 登录/登出操作的语义动作键:按其筛选时排除页面访问记录——升级前落库的
* GET /login、GET /logout 带同样的标注,但展示为「访问登录页/登出页」。
*/
private static final Set<String> AUTH_OPERATION_ACTIONS = Set.of("login", "logout");
/**
* 页面访问记录({@link OperationDescription#isAuthPageVisit} 的索引查询形态):
* 非 POST 的 {@code /login}、{@code /logout} 请求(含查询串)。不是操作,不计成败。
*/
private static final Condition PAGE_VISIT = Queries.and(
Queries.notEqual("spec.method", "POST"),
Queries.or(
Queries.startsWith("spec.path", "/login"),
Queries.startsWith("spec.path", "/logout")));
private AuditLogFilters() { private AuditLogFilters() {
} }
@@ -44,7 +60,11 @@ final class AuditLogFilters {
if (!FILTERABLE_FIELDS.contains(field)) { if (!FILTERABLE_FIELDS.contains(field)) {
throw new IllegalArgumentException("Field not filterable: " + field); throw new IllegalArgumentException("Field not filterable: " + field);
} }
conditions.add(Queries.equal(field, value)); var condition = Queries.equal(field, value);
if ("spec.action".equals(field) && AUTH_OPERATION_ACTIONS.contains(value)) {
condition = Queries.and(condition, Queries.not(PAGE_VISIT));
}
conditions.add(condition);
} }
// 关键字:资源名称 / 完整路径 模糊匹配(OR) // 关键字:资源名称 / 完整路径 模糊匹配(OR)
@@ -56,16 +76,24 @@ final class AuditLogFilters {
Queries.contains("spec.path", kw))); Queries.contains("spec.path", kw)));
} }
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx // 结果筛选(与 AuditResult 同一规则):success = 2xx/3xx 且非登录失败标注、
// 非页面访问;failure = 登录失败标注(表单登录失败的 HTTP 状态码是 302,
// 仅凭状态码识别不出)或 4xx/5xx(页面访问除外)。页面访问记录不计成败
var resultFilter = params.getFirst("result"); var resultFilter = params.getFirst("result");
if (StringUtils.hasText(resultFilter)) { if (StringUtils.hasText(resultFilter)) {
var loginFailure = Queries.equal("spec.action",
OperationDescription.LOGIN_FAILURE_ACTION);
switch (resultFilter.trim().toLowerCase()) { switch (resultFilter.trim().toLowerCase()) {
case "success" -> { case "success" -> {
conditions.add(Queries.greaterThan("spec.statusCode", "200", true)); conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
conditions.add(Queries.lessThan("spec.statusCode", "400", true)); conditions.add(Queries.lessThan("spec.statusCode", "400", true));
conditions.add(Queries.not(loginFailure));
conditions.add(Queries.not(PAGE_VISIT));
} }
case "failure" -> conditions.add( case "failure" -> conditions.add(Queries.or(
Queries.greaterThan("spec.statusCode", "400", true)); loginFailure,
Queries.and(Queries.greaterThan("spec.statusCode", "400", true),
Queries.not(PAGE_VISIT))));
default -> throw new IllegalArgumentException( default -> throw new IllegalArgumentException(
"Invalid result, expect success or failure: " + resultFilter); "Invalid result, expect success or failure: " + resultFilter);
} }
@@ -14,13 +14,23 @@ public class AuditLogSpec {
/** 操作者用户名;登录失败记 {@link #UNKNOWN_USERNAME}。 */ /** 操作者用户名;登录失败记 {@link #UNKNOWN_USERNAME}。 */
private String username; private String username;
/**
* 登录尝试的用户名(功能评审 P0-1):仅 POST {@code /login} 请求从表单/JSON 请求体
* 白名单提取落库(密码等其余字段绝不提取);登录失败时操作者为
* {@link #UNKNOWN_USERNAME},本字段用于区分定向撞库与无差别扫描。
* 提取失败或非登录请求为 null;不建索引(无需按其筛选)。
*/
private String attemptedUsername;
/** HTTP 方法(动作),如 POST/PUT/DELETE/PATCH。 */ /** HTTP 方法(动作),如 POST/PUT/DELETE/PATCH。 */
private String method; private String method;
/** /**
* 语义动作键(语义动作标注,产品设计 V2):捕获时由 method/path 推导落库 * 语义动作键(语义动作标注,产品设计 V2):捕获时由 method/path 推导落库
* (如 login/logout/create/update/delete/publish/restore),注册索引后支持 * (如 login/logout/create/update/delete/publish/login-failure,可空),注册索引后
* 按语义动作筛选。升级前写入的历史记录无此字段,展示不受影响(现场推导)。 * 支持按语义动作筛选。升级前写入的历史记录无此字段,展示不受影响(现场推导);
* 升级前落库的登录页访问记录(GET,现已不再记录)带 login/logout 标注,
* 展示时按方法纠正为页面访问。
*/ */
private String action; private String action;
@@ -33,7 +43,10 @@ public class AuditLogSpec {
/** 完整请求路径(资源语义解析的兜底,保证完整性)。 */ /** 完整请求路径(资源语义解析的兜底,保证完整性)。 */
private String path; private String path;
/** 响应状态码(结果:2xx 成功,其余失败)。 */ /**
* 响应状态码,如实记录。结果语义见 {@link AuditResult}:不能只看状态码——表单登录
* 成败均为 302,登录失败靠语义动作 {@code login-failure} 标注识别。
*/
private Integer statusCode; private Integer statusCode;
/** 来源 IP。 */ /** 来源 IP。 */
@@ -1,9 +1,16 @@
package run.halo.operationaudit.audit; package run.halo.operationaudit.audit;
import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder;
import static org.springdoc.core.fn.builders.content.Builder.contentBuilder;
import static org.springdoc.core.fn.builders.parameter.Builder.parameterBuilder;
import static org.springdoc.core.fn.builders.schema.Builder.schemaBuilder;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerRequest;
@@ -13,6 +20,7 @@ import reactor.core.publisher.Mono;
import run.halo.app.core.extension.endpoint.CustomEndpoint; import run.halo.app.core.extension.endpoint.CustomEndpoint;
import run.halo.app.extension.GroupVersion; import run.halo.app.extension.GroupVersion;
import run.halo.app.extension.ListOptions; import run.halo.app.extension.ListOptions;
import run.halo.app.extension.ListResult;
import run.halo.app.extension.PageRequestImpl; import run.halo.app.extension.PageRequestImpl;
import run.halo.app.extension.ReactiveExtensionClient; import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.operationaudit.audit.AuditLog; import run.halo.operationaudit.audit.AuditLog;
@@ -35,6 +43,12 @@ public class AuditQueryEndpoint implements CustomEndpoint {
/** 每页大小上限,防止误用拖垮查询。 */ /** 每页大小上限,防止误用拖垮查询。 */
static final int MAX_PAGE_SIZE = 100; static final int MAX_PAGE_SIZE = 100;
/**
* OpenAPI tag(generateApiClient 以此生成 TS API 类,如 AuditV1alpha1ConsoleApi);
* 查询与导出端点共用,告警测试端点(AlertTestEndpoint)亦挂同一 tag。
*/
public static final String TAG = "AuditV1alpha1Console";
private final ReactiveExtensionClient client; private final ReactiveExtensionClient client;
private final AuditLogCsvExporter csvExporter; private final AuditLogCsvExporter csvExporter;
@@ -48,15 +62,78 @@ public class AuditQueryEndpoint implements CustomEndpoint {
return org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route() return org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route()
.GET("auditlogs/-/query", this::query, builder -> builder .GET("auditlogs/-/query", this::query, builder -> builder
.operationId("ListAuditLogs") .operationId("ListAuditLogs")
.tag(TAG)
.description("分页查询审计日志:支持等值筛选(fieldSelector,含 spec.action " .description("分页查询审计日志:支持等值筛选(fieldSelector,含 spec.action "
+ "语义动作)、关键字(resourceName/path 模糊)、结果(success/failure)、" + "语义动作)、关键字(resourceName/path 模糊)、结果(success/failure)、"
+ "时间区间(含边界)") + "时间区间(含边界)")
.parameter(parameterBuilder()
.name("page").in(ParameterIn.QUERY)
.description("页码(从 1 开始)")
.implementation(Integer.class))
.parameter(parameterBuilder()
.name("size").in(ParameterIn.QUERY)
.description("每页大小(1-" + MAX_PAGE_SIZE + ")")
.implementation(Integer.class))
.parameter(parameterBuilder()
.name("sort").in(ParameterIn.QUERY)
.description("排序(field,(asc|desc)),仅支持 metadata.creationTimestamp")
.implementation(String.class))
.parameter(parameterBuilder()
.name("fieldSelector").in(ParameterIn.QUERY)
.description("等值筛选,可重复(spec.username/spec.resourceType/spec.method/"
+ "spec.action)")
.implementationArray(String.class))
.parameter(parameterBuilder()
.name("result").in(ParameterIn.QUERY)
.description("结果筛选(success/failure)")
.implementation(String.class))
.parameter(parameterBuilder()
.name("keyword").in(ParameterIn.QUERY)
.description("关键字(resourceName/path 模糊匹配)")
.implementation(String.class))
.parameter(parameterBuilder()
.name("startTime").in(ParameterIn.QUERY)
.description("开始时间(ISO-8601,含边界)")
.implementation(String.class))
.parameter(parameterBuilder()
.name("endTime").in(ParameterIn.QUERY)
.description("结束时间(ISO-8601,含边界)")
.implementation(String.class))
.response(responseBuilder().responseCode("200")
.description("审计日志分页结果")
.implementation(ListResult.generateGenericClass(AuditLog.class)))
.build()) .build())
.GET("auditlogs/-/export", this::export, builder -> builder .GET("auditlogs/-/export", this::export, builder -> builder
.operationId("ExportAuditLogs") .operationId("ExportAuditLogs")
.tag(TAG)
.description("按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS " .description("按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS "
+ "可直接打开):筛选参数与 query 完全一致,不分页全量导出," + "可直接打开):筛选参数与 query 完全一致,不分页全量导出,"
+ "按时间升序输出") + "按时间升序输出")
.parameter(parameterBuilder()
.name("fieldSelector").in(ParameterIn.QUERY)
.description("等值筛选,可重复(与 query 一致)")
.implementationArray(String.class))
.parameter(parameterBuilder()
.name("result").in(ParameterIn.QUERY)
.description("结果筛选(success/failure)")
.implementation(String.class))
.parameter(parameterBuilder()
.name("keyword").in(ParameterIn.QUERY)
.description("关键字(resourceName/path 模糊匹配)")
.implementation(String.class))
.parameter(parameterBuilder()
.name("startTime").in(ParameterIn.QUERY)
.description("开始时间(ISO-8601,含边界)")
.implementation(String.class))
.parameter(parameterBuilder()
.name("endTime").in(ParameterIn.QUERY)
.description("结束时间(ISO-8601,含边界)")
.implementation(String.class))
.response(responseBuilder().responseCode("200")
.description("CSV 文件附件(UTF-8 BOM)")
.content(contentBuilder()
.mediaType(MediaType.APPLICATION_OCTET_STREAM_VALUE)
.schema(schemaBuilder().type("string").format("binary"))))
.build()) .build())
.build(); .build();
} }
@@ -35,9 +35,15 @@ public class AuditRecorder {
* *
* <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值, * <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值,
* 此处为防御性兜底,保证审计设置故障不影响捕获链路。 * 此处为防御性兜底,保证审计设置故障不影响捕获链路。
*
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
* @param loginFailed 登录失败标注:POST /login 结果失败(表单登录失败为
* 302 重定向且回跳登录页),语义动作标注 login-failure;
* 其余请求为 false
*/ */
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode, public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) { String username, String attemptedUsername, boolean loginFailed) {
settingProvider.get().subscribe( settingProvider.get().subscribe(
settings -> { settings -> {
if (!settings.enabledOrDefault()) { if (!settings.enabledOrDefault()) {
@@ -45,19 +51,20 @@ public class AuditRecorder {
snapshot.getMethod(), snapshot.getFullPath()); snapshot.getMethod(), snapshot.getFullPath());
return; return;
} }
write(snapshot, capture, statusCode, username); write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
}, },
e -> { e -> {
log.warn("Failed to load audit settings, record with defaults for {} {}", log.warn("Failed to load audit settings, record with defaults for {} {}",
snapshot.getMethod(), snapshot.getFullPath(), e); snapshot.getMethod(), snapshot.getFullPath(), e);
write(snapshot, capture, statusCode, username); write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
}); });
} }
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode, private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) { String username, String attemptedUsername, boolean loginFailed) {
try { try {
var auditLog = assemble(snapshot, capture, statusCode, username); var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername,
loginFailed);
client.create(auditLog) client.create(auditLog)
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}", .subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
snapshot.getMethod(), snapshot.getFullPath(), e)); snapshot.getMethod(), snapshot.getFullPath(), e));
@@ -144,18 +151,24 @@ public class AuditRecorder {
} }
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode, private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) { String username, String attemptedUsername, boolean loginFailed) {
var resolved = ResourceResolver.resolve(snapshot.getPath()); var resolved = ResourceResolver.resolve(snapshot.getPath());
var spec = new AuditLogSpec(); var spec = new AuditLogSpec();
spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME); spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME);
// 登录尝试用户名(功能评审 P0-1):仅登录请求由捕获器提取,其余请求为 null
spec.setAttemptedUsername(attemptedUsername);
spec.setMethod(snapshot.getMethod()); spec.setMethod(snapshot.getMethod());
spec.setResourceType(resolved.resourceType()); spec.setResourceType(resolved.resourceType());
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选 // 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选;
spec.setAction(OperationDescription.actionOf( // 登录失败(POST /login 回跳登录页或 4xx/5xx)标注 login-failure——
// 表单登录失败的 HTTP 状态码与成功相同(302),结果只能靠落库标注区分
spec.setAction(loginFailed ? OperationDescription.LOGIN_FAILURE_ACTION
: OperationDescription.actionOf(
snapshot.getMethod(), resolved.resourceType(), snapshot.getPath())); snapshot.getMethod(), resolved.resourceType(), snapshot.getPath()));
spec.setResourceName(resolved.optionalName().orElse(null)); spec.setResourceName(resolved.optionalName().orElse(null));
spec.setPath(snapshot.getFullPath()); spec.setPath(snapshot.getFullPath());
// 状态码如实记录(表单登录成败均为 302),登录成败看语义动作标注
spec.setStatusCode(statusCode); spec.setStatusCode(statusCode);
spec.setRemoteIp(snapshot.getRemoteIp()); spec.setRemoteIp(snapshot.getRemoteIp());
spec.setUserAgent(snapshot.getUserAgent()); spec.setUserAgent(snapshot.getUserAgent());
@@ -0,0 +1,44 @@
package run.halo.operationaudit.audit;
/**
* 审计记录的结果语义(纯函数):结果筛选({@link AuditLogFilters})、CSV 导出
* ({@link AuditLogCsvExporter})与前端 {@code ui/src/utils/audit.ts} 的结果徽标
* 共用同一规则——什么算成功、什么算失败,只能有一个定义。
*
* <ul>
* <li>{@link #FAILURE}:登录失败(语义动作 {@code login-failure},HTTP 状态码可能是
* 302/200);其余按状态码判定,4xx/5xx 为失败;</li>
* <li>{@link #PAGE_VISIT}:认证端点的页面访问(升级前落库的 GET /login、GET /logout
* 历史记录)——不是操作,不计成败;</li>
* <li>{@link #SUCCESS}:其余状态码 2xx/3xx。</li>
* </ul>
*/
enum AuditResult {
SUCCESS("成功"),
FAILURE("失败"),
PAGE_VISIT("页面访问");
/** 导出 CSV「结果」列的中文值。 */
private final String label;
AuditResult(String label) {
this.label = label;
}
static AuditResult of(AuditLogSpec spec) {
if (OperationDescription.LOGIN_FAILURE_ACTION.equals(
OperationDescription.semanticAction(spec))) {
return FAILURE;
}
if (OperationDescription.isAuthPageVisit(spec.getMethod(), spec.getPath())) {
return PAGE_VISIT;
}
var statusCode = spec.getStatusCode();
return statusCode != null && statusCode >= 200 && statusCode < 400
? SUCCESS : FAILURE;
}
String label() {
return label;
}
}
@@ -0,0 +1,99 @@
package run.halo.operationaudit.audit;
import static run.halo.operationaudit.audit.CaptureRule.isAuthOperation;
import static run.halo.operationaudit.audit.CaptureRule.isLoginAttempt;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import run.halo.app.security.BeforeSecurityWebFilter;
import run.halo.operationaudit.alert.LoginFailureAlertService;
/**
* 认证操作({@code POST /login}、{@code POST /logout})审计捕获过滤器(P0 修复,见测试报告)。
*
* <p>以 {@link BeforeSecurityWebFilter} 扩展点注册:位于 Security 过滤链最前
* ({@code SecurityWebFiltersOrder.FIRST})。原先认证端点由
* {@code AfterSecurityWebFilter} 扩展点注册的 {@link OperationAuditWebFilter} 捕获,
* 但该扩展点位于认证环节之后——表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中
* 请求后直接完成 302 响应、不再向下游传递,POST /login 与 POST /logout 永远到不了
* 链尾的审计过滤器(真实环境实测,登录失败告警生产路径随之失效)。因此认证操作整体
* 移交本过滤器,在 Security 链之前承接捕获与记录。
*
* <p>只记录认证操作本身:{@code POST /login} 是登录尝试,{@code POST /logout} 是登出。
* 登录/登出页面的 GET 访问(打开登录页、匿名访问被弹回登录页、登录失败后的回显、
* 登出确认页)原样透传、不记录——它们只是渲染页面(HTTP 200),落库会显示成
* 「未知用户 · 登录 · 200」,看起来像登录成功,真正的成败反而被淹没(现场实测反馈)。
*
* <p>操作者归属:Security 链最前无认证上下文(SecurityContext 由链内更晚位置的
* ReactorContextWebFilter 写入订阅上下文,对链首过滤器不可见),统一记
* {@link AuditLogSpec#UNKNOWN_USERNAME 未知用户}(既有兜底路径);登录尝试的账号
* 由 {@link LoginAttemptCapture} 从请求体白名单提取,落库 {@code spec.attemptedUsername}
* 并进入告警负载(功能评审 P0-1),账号归属信息不受影响。
*
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
* 回调给 {@link LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否
* 跳回登录页区分,不能只看状态码)。
*
* <p>登录失败标注(语义动作 {@code login-failure}):失败的 POST {@code /login} 落库
* 标注登录失败,供列表红色标记与筛选;HTTP 状态码仍如实记录。
*
* <p>任何失败均静默降级(记录器与告警服务内部兜底),绝不影响登录主流程(设计原则 4)。
*/
@Component
@RequiredArgsConstructor
public class AuthEndpointAuditWebFilter implements BeforeSecurityWebFilter {
private final AuditRecorder recorder;
private final HttpWriteMarker writeMarker;
private final LoginAttemptCapture loginAttemptCapture;
private final LoginFailureAlertService loginFailureAlertService;
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
var request = exchange.getRequest();
var path = request.getPath().value();
var method = request.getMethod().name();
if (!isAuthOperation(path, method)) {
// 登录/登出页面的 GET 访问等非认证操作一律原样透传:不触碰请求体、不记录
return chain.filter(exchange);
}
writeMarker.onRequestStart(request);
var snapshot = RequestSnapshot.of(request);
var loginAttempt = new LoginAttempt();
var loginAttempted = isLoginAttempt(path, method);
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
// 登出原样透传
var bodyPrepared = loginAttempted
? loginAttemptCapture.prepare(exchange, loginAttempt)
: Mono.just(exchange);
return bodyPrepared
.flatMap(chain::filter)
.doFinally(signal -> {
writeMarker.onRequestComplete(request);
var statusCode = statusOf(exchange);
// 登录结果判定(LoginOutcome):表单登录成败均为 302 重定向,
// 以重定向目标是否跳回登录页区分;登出不存在登录成败
var loginFailed = loginAttempted && LoginOutcome.isFailure(statusCode,
exchange.getResponse().getHeaders().getLocation());
if (loginAttempted) {
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
// 成功清零计数、失败累计,独立于审计记录
loginFailureAlertService.onLoginResult(snapshot, !loginFailed,
loginAttempt.getAttemptedUsername());
}
recorder.record(snapshot, null, statusCode,
AuditLogSpec.UNKNOWN_USERNAME,
loginAttempt.getAttemptedUsername(), loginFailed);
});
}
private static Integer statusOf(ServerWebExchange exchange) {
var status = exchange.getResponse().getStatusCode();
return status != null ? status.value() : 0;
}
}
@@ -6,11 +6,21 @@ import java.util.Set;
* 捕获规则(纯函数,技术方案 D1): * 捕获规则(纯函数,技术方案 D1):
* *
* <ul> * <ul>
* <li>{@code POST/PUT/DELETE/PATCH} + 路径前缀 {@code /apis/}</li> * <li>{@code /apis/**} 下的 {@code POST/PUT/DELETE/PATCH} 写操作({@link #shouldCapture},
* <li>或路径精确匹配 {@code /login}、{@code /logout}(登录端点不在 /apis/** 下, * 由 {@code AfterSecurityWebFilter} 注册的 {@link OperationAuditWebFilter} 消费,
* 是“一条通用规则覆盖全部管理面操作”的唯一必要例外,需在产品文档同步注明)</li> * 可获得认证用户上下文);</li>
* <li>认证操作 {@code POST /login}(登录尝试)与 {@code POST /logout}(登出)精确匹配
* ({@link #isAuthOperation},由 {@link AuthEndpointAuditWebFilter} 消费)——
* 登录/登出端点不在 /apis/** 下,且表单登录/登出过滤器命中请求后直接完成响应、
* 不再向下游传递,链尾的 AfterSecurityWebFilter 永远看不到(P0 缺陷实测),
* 因此必须在 Security 链之前独立捕获。</li>
* </ul> * </ul>
* *
* <p>登录/登出页面的 GET 访问不是操作,不记录({@link #isAuthEndpoint} 仅用于路径归类):
* 打开登录页、匿名访问被弹回登录页({@code /login?authentication_required})、登录失败
* 后的回显({@code /login?error=...})、登出确认页都只是渲染页面(HTTP 200),若落库
* 会显示成「未知用户 · 登录 · 200」,看起来像登录成功,而真正的登录尝试是 POST /login。
*
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。 * <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
*/ */
public final class CaptureRule { public final class CaptureRule {
@@ -19,32 +29,47 @@ public final class CaptureRule {
public static final Set<String> AUTH_ENDPOINTS = Set.of("/login", "/logout"); public static final Set<String> AUTH_ENDPOINTS = Set.of("/login", "/logout");
public static final String APIS_PREFIX = "/apis/"; public static final String APIS_PREFIX = "/apis/";
/** 登录端点(告警通道唯一触发路径;登出与登录页 GET 不算登录尝试)。 */ /** 登录端点(告警通道唯一触发路径;登录页 GET 不算登录尝试)。 */
public static final String LOGIN_ENDPOINT = "/login"; public static final String LOGIN_ENDPOINT = "/login";
/** 登出端点(POST 为登出操作;GET 为登出确认页)。 */
public static final String LOGOUT_ENDPOINT = "/logout";
private CaptureRule() { private CaptureRule() {
} }
/** 是否命中捕获规则。path 为不含查询串的请求路径。 */ /**
* 是否命中捕获规则。path 为不含查询串的请求路径。
*
* <p>仅覆盖 {@code /apis/**} 写操作;认证操作由 {@link #isAuthOperation} 单独判定、
* 由 {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,两个过滤器按此分治、
* 互不重叠,不会重复记录。
*/
public static boolean shouldCapture(String path, String method) { public static boolean shouldCapture(String path, String method) {
if (isAuthEndpoint(path)) {
return true;
}
if (path == null || !path.startsWith(APIS_PREFIX)) { if (path == null || !path.startsWith(APIS_PREFIX)) {
return false; return false;
} }
return method != null && WRITE_METHODS.contains(method); return method != null && WRITE_METHODS.contains(method);
} }
/** 是否为登录/登出端点。 */ /** 是否为登录/登出端点(仅用于路径归类,不代表需要记录)。 */
public static boolean isAuthEndpoint(String path) { public static boolean isAuthEndpoint(String path) {
return path != null && AUTH_ENDPOINTS.contains(path); return path != null && AUTH_ENDPOINTS.contains(path);
} }
/**
* 是否为认证操作(由 {@link AuthEndpointAuditWebFilter} 捕获):{@code POST /login}
* 与 {@code POST /logout}。登录/登出页面的 GET 访问不是操作,不记录。
*/
public static boolean isAuthOperation(String path, String method) {
return isLoginAttempt(path, method)
|| "POST".equals(method) && LOGOUT_ENDPOINT.equals(path);
}
/** /**
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」): * 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
* 登录失败告警的触发条件——2xx 为登录成功,其余为失败; * 登录失败告警的触发条件——结果由 {@link LoginOutcome} 判定(表单登录成败均为
* 登录页 GET 与登出不算。 * 302 重定向,不能只看状态码);登录页 GET 与登出不算。
*/ */
public static boolean isLoginAttempt(String path, String method) { public static boolean isLoginAttempt(String path, String method) {
return "POST".equals(method) && LOGIN_ENDPOINT.equals(path); return "POST".equals(method) && LOGIN_ENDPOINT.equals(path);
@@ -366,8 +366,11 @@ final class ChangeDiffEngine {
out.add(entry); 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("\\.")) { for (var segment : field.split("\\.")) {
if (SENSITIVE_FIELD.matcher(segment).find()) { if (SENSITIVE_FIELD.matcher(segment).find()) {
return true; 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;
}
@@ -0,0 +1,177 @@
package run.halo.operationaudit.audit;
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
import com.fasterxml.jackson.databind.JsonNode;
import java.nio.charset.StandardCharsets;
import java.util.List;
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} 的请求体为表单形态、
* 登录端点非注册模型,为登录端点单独提取尝试的用户名。
*
* <p>提取规则(安全边界):
* <ul>
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
* <li>超长用户名({@value #MAX_USERNAME_LENGTH} 字符以上)视为扫描载荷,不提取。</li>
* </ul>
*
* <p>表单形态({@code application/x-www-form-urlencoded}):经
* {@link ServerWebExchange#getFormData()} 读取——该 Mono 由
* {@code DefaultServerWebExchange} 在构造时创建并 {@code cache()},与下游 CSRF 过滤器、
* 表单登录转换器共享同一份解析结果。<b>绝不缓存原始请求体并装饰 exchange</b>:
* 装饰后的 exchange 会将 {@code getFormData()} 代理回原始 exchange、解析已被消费的
* 原始 body,导致下游 CSRF 读不到 {@code _csrf} 参数而拒绝登录(真实环境回归实证,
* 登录页表单提交整体失效)。JSON 形态则缓存原始请求体并装饰(下游无表单语义、
* 登录转换器不读 JSON 体,装饰使其可重复读)。
*
* <p>JSON 形态经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存;
* 分块传输/超限一律不读。任何解析异常均静默降级为不提取(返回 null),
* 绝不影响登录主流程(设计原则 4)。提取结果写入 {@link LoginAttempt},与审计开关、
* 告警开关均无关(两种消费方各自决定是否使用)。
*/
@Slf4j
@Component
public class LoginAttemptCapture {
/** JSON 请求体缓存上限(字节):登录请求体极小,上限远小于字段级变更捕获。 */
static final int MAX_BODY_BYTES = 64 * 1024;
/** 提取的用户名长度上限:超过视为扫描载荷,不提取(保证记录与告警负载卫生)。 */
static final int MAX_USERNAME_LENGTH = 256;
/** 提取字段白名单:仅用户名。密码等任何其他字段绝不提取。 */
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);
}
if (isForm(contentType)) {
return exchange.getFormData()
.map(form -> {
attempt.setAttemptedUsername(usernameOfFormValues(form.get(USERNAME_FIELD)));
return exchange;
})
.defaultIfEmpty(exchange)
.onErrorResume(e -> {
log.warn("Failed to capture login attempt form for username extraction", e);
return Mono.just(exchange);
});
}
// JSON 形态:缓存原始请求体(装饰后可重复读)并提取顶层 username 字段
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(extractJson(bytes));
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 isForm(contentType) || ChangeCaptureManager.isJson(contentType);
}
private static boolean isForm(MediaType contentType) {
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED);
}
/** JSON 体提取:仅取顶层白名单字段的标量值;任何异常静默返回 null。 */
private static String extractJson(byte[] bytes) {
try {
return usernameOfJson(Unstructured.OBJECT_MAPPER.readTree(bytes));
} catch (Exception e) {
// 解析异常静默:不提取,不影响登录主流程
return null;
}
}
/**
* 表单字段提取:仅取白名单字段的值(同名多值取最后一个,与逐字段解析语义一致);
* 超长值视为扫描载荷不提取。
*/
static String usernameOfFormValues(List<String> values) {
if (values == null || values.isEmpty()) {
return null;
}
var found = values.get(values.size() - 1);
if (!StringUtils.hasText(found) || found.length() > MAX_USERNAME_LENGTH) {
return null;
}
return maskIfSensitive(USERNAME_FIELD, found);
}
/** 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();
if (!StringUtils.hasText(text) || text.length() > MAX_USERNAME_LENGTH) {
return null;
}
return maskIfSensitive(USERNAME_FIELD, text);
}
/**
* 兜底脱敏:白名单保证仅提取 username,若未来白名单调整后字段名命中现有敏感字段
* 规则({@link ChangeDiffEngine}),提取值一律以 {@value ChangeDiffEngine#REDACTED_VALUE}
* 代替,密码/密钥绝不落库。
*/
static String maskIfSensitive(String fieldName, String value) {
return ChangeDiffEngine.isSensitiveField(fieldName) ? REDACTED_VALUE : 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();
}
}
@@ -0,0 +1,65 @@
package run.halo.operationaudit.audit;
import java.net.URI;
import java.util.Arrays;
/**
* 登录结果判定(纯函数):Halo 2.26 登录端点的成功/失败在 HTTP 层并非「非 2xx 即失败」——
* 表单提交的成功与失败都以 302 重定向收尾(成功 → {@code /uc} 或 2FA 页;失败 →
* {@code /login?error=...&method=...}),仅 XHR/JSON 请求才以 200/401 区分成败
* (见 Halo {@code LoginSuccessHandler} / {@code LoginFailureHandler})。
* 因此登录结果须结合重定向目标判定,不能只看状态码。
*
* <p>判定原则:只有响应明确确认登录完成才算成功,其余一律按失败记录——审计里把失败
* 登录记成成功,远比把异常响应记成失败更糟。
*/
public final class LoginOutcome {
/** 登录页路径:重定向回登录页即表示没有登录成功。 */
private static final String LOGIN_PAGE_PATH = "/login";
private LoginOutcome() {
}
/**
* POST {@code /login} 的登录结果判定(Halo 2.26 登录端点契约):
*
* <ul>
* <li>2xx → 成功(XHR/JSON 请求返回 200 + 主体 JSON);</li>
* <li>3xx → 重定向目标跳回登录页(查询串含 {@code error} 参数,如
* {@code /login?error=invalid-credential&method=...},或路径就是 {@code /login})
* 或缺失 Location → 失败;其余重定向目标(成功 → {@code /uc}、
* 两步验证 → {@code /challenges/two-factor/totp})→ 成功;</li>
* <li>其余(401 等)→ 失败(XHR 登录失败;状态码缺失/为 0 亦按失败处理)。</li>
* </ul>
*/
public static boolean isFailure(Integer statusCode, URI location) {
if (statusCode == null) {
return true;
}
if (statusCode >= 200 && statusCode < 300) {
return false;
}
if (statusCode >= 300 && statusCode < 400) {
// 跳回登录页必然是失败:Halo 2.26 的四种失败重定向均带 error 参数,
// 无参跳回登录页同样不可能是登录成功(成功只会去 /uc、已保存的原请求或 2FA 页)
return location == null
|| LOGIN_PAGE_PATH.equals(location.getPath())
|| hasErrorParam(location.getRawQuery());
}
return true;
}
/** 查询串是否含 {@code error} 参数(可为无值形式 {@code error})。 */
static boolean hasErrorParam(String query) {
if (query == null || query.isEmpty()) {
return false;
}
return Arrays.stream(query.split("&"))
.map(pair -> {
var idx = pair.indexOf('=');
return idx < 0 ? pair : pair.substring(0, idx);
})
.anyMatch("error"::equals);
}
}
@@ -3,7 +3,6 @@ package run.halo.operationaudit.audit;
import static run.halo.operationaudit.audit.CaptureRule.shouldCapture; import static run.halo.operationaudit.audit.CaptureRule.shouldCapture;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -13,13 +12,15 @@ import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import reactor.util.context.ContextView; import reactor.util.context.ContextView;
import run.halo.app.security.AfterSecurityWebFilter; import run.halo.app.security.AfterSecurityWebFilter;
import run.halo.operationaudit.alert.LoginFailureAlertService;
/** /**
* 审计捕获过滤器(技术方案 D1 / 5.1)。 * 审计捕获过滤器(技术方案 D1 / 5.1),仅负责 {@code /apis/**} 写操作。
* *
* <p>以 {@link AfterSecurityWebFilter} 扩展点注册:位于 Security 过滤链最后、认证之后, * <p>以 {@link AfterSecurityWebFilter} 扩展点注册:位于 Security 过滤链最后、认证之后,
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。 * 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。认证端点
* ({@code /login}、{@code /logout})不在此过滤器捕获——表单登录/登出过滤器命中请求后
* 直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到(P0 缺陷实测);
* 详见 {@link AuthEndpointAuditWebFilter}。
* *
* <p>注意 WebFlux 无 ThreadLocal:用户名提取经 {@code transformDeferredContextual} 在订阅 * <p>注意 WebFlux 无 ThreadLocal:用户名提取经 {@code transformDeferredContextual} 在订阅
* 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。 * 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。
@@ -29,13 +30,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
* <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON * <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON
* 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。 * 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。
* *
* <p>系统内部变更(产品设计 V2):所有写方法请求(含未被捕获规则命中的 {@code /api/**} * <p>系统内部变更(产品设计 V2):未被捕获规则命中的写方法请求({@code /api/**}
* 核心模型与登录端点)均经 {@link HttpWriteMarker} 登记目标资源与活动时间,供 * 核心模型)同样经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。 * {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
*
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
* Webhook;与审计开关相互独立。
*/ */
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -47,7 +44,6 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
private final AuditRecorder recorder; private final AuditRecorder recorder;
private final ChangeCaptureManager captureManager; private final ChangeCaptureManager captureManager;
private final HttpWriteMarker writeMarker; private final HttpWriteMarker writeMarker;
private final LoginFailureAlertService loginFailureAlertService;
@Override @Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
@@ -55,7 +51,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
var path = request.getPath().value(); var path = request.getPath().value();
var method = request.getMethod().name(); var method = request.getMethod().name();
if (!shouldCapture(path, method)) { if (!shouldCapture(path, method)) {
// 未命中捕获规则的写方法请求(/api/** 核心模型、登录端点等)不记录, // 未命中捕获规则的写方法请求(/api/** 核心模型等)不记录,
// 但仍登记标记:请求期触发的资源变更由该请求归属 // 但仍登记标记:请求期触发的资源变更由该请求归属
if (CaptureRule.WRITE_METHODS.contains(method)) { if (CaptureRule.WRITE_METHODS.contains(method)) {
writeMarker.onRequestStart(request); writeMarker.onRequestStart(request);
@@ -68,19 +64,16 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
var snapshot = RequestSnapshot.of(request); var snapshot = RequestSnapshot.of(request);
var capture = new ChangeCapture(); var capture = new ChangeCapture();
return captureManager.prepare(exchange, snapshot, capture) return captureManager.prepare(exchange, snapshot, capture)
.flatMap(prepared -> chain.filter(prepared)) .flatMap(chain::filter)
.transformDeferredContextual((mono, ctx) -> mono.doFinally( .transformDeferredContextual((mono, ctx) -> mono.doFinally(
signal -> { signal -> {
writeMarker.onRequestComplete(request); writeMarker.onRequestComplete(request);
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果, var statusCode = statusOf(exchange);
// 2xx 清零计数、其余累计,独立于下方审计记录决策 operatorOf(ctx).subscribe(
if (CaptureRule.isLoginAttempt(path, method)) {
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange));
}
operatorOf(ctx, path).subscribe(
username -> { username -> {
if (shouldRecord(path, username)) { if (shouldRecord(username)) {
recorder.record(snapshot, capture, statusOf(exchange), username); recorder.record(snapshot, capture, statusCode, username,
null, false);
} }
}, },
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ }); e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
@@ -90,10 +83,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
/** /**
* 从订阅上下文解析操作者用户名。 * 从订阅上下文解析操作者用户名。
* *
* <p>上下文中无 SecurityContext(匿名请求)→ 空用户名;登录端点的匿名请求记“未知用户”。 * <p>上下文中无 SecurityContext 或认证无用户名 → 记“未知用户”占位。
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static Mono<String> operatorOf(ContextView ctx, String path) { private static Mono<String> operatorOf(ContextView ctx) {
return ctx.getOrEmpty(SecurityContext.class) return ctx.getOrEmpty(SecurityContext.class)
.map(value -> ((Mono<SecurityContext>) value) .map(value -> ((Mono<SecurityContext>) value)
.flatMap(sc -> Mono.justOrEmpty(sc != null ? sc.getAuthentication() : null)) .flatMap(sc -> Mono.justOrEmpty(sc != null ? sc.getAuthentication() : null))
@@ -104,13 +97,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
} }
/** /**
* 记录决策(技术方案 D1):匿名判断在记录时做—— * 记录决策(技术方案 D1):匿名判断在记录时做——认证后仍为匿名主体
* {@code /apis/**} 下认证后仍为匿名主体(401/403 场景)的请求跳过不记。 * (401/403 场景)的请求跳过不记。
*/ */
private static boolean shouldRecord(String path, String username) { private static boolean shouldRecord(String username) {
if (CaptureRule.isAuthEndpoint(path)) {
return true;
}
return StringUtils.hasText(username) && !ANONYMOUS_USER.equals(username) return StringUtils.hasText(username) && !ANONYMOUS_USER.equals(username)
&& !AuditLogSpec.UNKNOWN_USERNAME.equals(username); && !AuditLogSpec.UNKNOWN_USERNAME.equals(username);
} }
@@ -119,10 +109,4 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
var status = exchange.getResponse().getStatusCode(); var status = exchange.getResponse().getStatusCode();
return status != null ? status.value() : 0; return status != null ? status.value() : 0;
} }
/** 仅供测试与未来扩展使用:判断认证主体是否匿名。 */
static boolean isAnonymous(Authentication authentication) {
return authentication == null || !StringUtils.hasText(authentication.getName())
|| ANONYMOUS_USER.equals(authentication.getName());
}
} }
@@ -12,10 +12,10 @@ import java.util.Map;
* 展示/导出由 {@link #describe} 推导中文短语,历史记录(无 action 字段)同样按 * 展示/导出由 {@link #describe} 推导中文短语,历史记录(无 action 字段)同样按
* method/path 现场推导,不受影响。 * method/path 现场推导,不受影响。
* *
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code deriveAction} / {@code describeOperation} * <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code deriveAction} / {@code semanticAction} /
* 保持一致(同一套 RESOURCE_LABELS / METHOD_ACTIONS / SEGMENT_ACTIONS / ACTION_PHRASES / * {@code describeOperation} 保持一致(同一套 RESOURCE_LABELS / METHOD_ACTIONS /
* ACTION_VERBS 映射与子动作解析规则),两处需同步修改。未识别的子动作回退为 * SEGMENT_ACTIONS / ACTION_PHRASES / ACTION_VERBS 映射与子动作解析规则),两处需同步修改。
* 「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。 * 未识别的子动作回退为「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
*/ */
final class OperationDescription { final class OperationDescription {
@@ -64,10 +64,29 @@ final class OperationDescription {
Map.entry("password", "password"), Map.entry("password", "password"),
Map.entry("resetpassword", "resetpassword")); Map.entry("resetpassword", "resetpassword"));
/**
* 登录失败语义动作键:POST {@code /login} 失败(重定向跳回登录页或 4xx/5xx)落库
* 标注,供列表红色标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
* 升级前落库的失败回显页(GET {@code /login?error=...},HTTP 200)带同一标注。
*/
static final String LOGIN_FAILURE_ACTION = "login-failure";
/**
* 登录页访问语义动作键:GET {@code /login}(打开登录页、被弹回登录页、失败回显)。
* 仅升级前落库的历史记录会出现——页面访问不是操作,现已不记录。
*/
static final String LOGIN_PAGE_ACTION = "login-page";
/** 登出页访问语义动作键:GET {@code /logout}(登出确认页),仅升级前的历史记录。 */
static final String LOGOUT_PAGE_ACTION = "logout-page";
/** 语义动作键 → 完整短语(不拼接资源名)。 */ /** 语义动作键 → 完整短语(不拼接资源名)。 */
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries( private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
Map.entry("login", "登录"), Map.entry("login", "登录"),
Map.entry(LOGIN_FAILURE_ACTION, "登录失败"),
Map.entry("logout", "登出"), Map.entry("logout", "登出"),
Map.entry(LOGIN_PAGE_ACTION, "访问登录页"),
Map.entry(LOGOUT_PAGE_ACTION, "访问登出页"),
Map.entry("auth", "认证操作"), Map.entry("auth", "认证操作"),
Map.entry("password", "修改密码"), Map.entry("password", "修改密码"),
Map.entry("resetpassword", "重置密码")); Map.entry("resetpassword", "重置密码"));
@@ -94,17 +113,26 @@ final class OperationDescription {
} }
/** /**
* 推导语义动作键(捕获时落库标注,供筛选):登录/登出/认证操作由路径判定, * 推导语义动作键(捕获时落库标注,供筛选):登录/登出/认证操作由路径与方法判定,
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view; * 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
* 无法识别(未知方法等)返回 null,记录不标注。 * 无法识别(未知方法等)返回 null,记录不标注。
*
* <p>认证端点按方法区分:POST 是登录/登出操作,其余方法是页面访问
* ({@link #LOGIN_PAGE_ACTION} / {@link #LOGOUT_PAGE_ACTION});路径含 {@code error}
* 参数的登录页是升级前落库的失败回显,无标注时现场推导为登录失败。
*/ */
static String actionOf(String method, String resourceType, String path) { static String actionOf(String method, String resourceType, String path) {
var cleanPath = pathWithoutQuery(path); var cleanPath = pathWithoutQuery(path);
if ("/login".equals(cleanPath)) { if ("/login".equals(cleanPath)) {
return "login"; var queryStart = path == null ? -1 : path.indexOf('?');
if (queryStart >= 0
&& LoginOutcome.hasErrorParam(path.substring(queryStart + 1))) {
return LOGIN_FAILURE_ACTION;
}
return "POST".equals(method) ? "login" : LOGIN_PAGE_ACTION;
} }
if ("/logout".equals(cleanPath)) { if ("/logout".equals(cleanPath)) {
return "logout"; return "POST".equals(method) ? "logout" : LOGOUT_PAGE_ACTION;
} }
if ("auth".equals(resourceType)) { if ("auth".equals(resourceType)) {
return "auth"; return "auth";
@@ -124,6 +152,35 @@ final class OperationDescription {
return METHOD_ACTIONS.get(method); return METHOD_ACTIONS.get(method);
} }
/**
* 是否为认证端点的页面访问:{@code GET /login}、{@code GET /logout}(含查询串),
* 即非 POST 的认证端点请求。页面访问不是登录/登出操作,结果不计成败;仅升级前
* 落库的历史记录会出现。
*/
static boolean isAuthPageVisit(String method, String path) {
if ("POST".equals(method)) {
return false;
}
var cleanPath = pathWithoutQuery(path);
return "/login".equals(cleanPath) || "/logout".equals(cleanPath);
}
/**
* 记录的语义动作键(展示、导出与结果判定共用):优先落库标注;认证端点的失败回显与
* 页面访问(升级前落库为 login/logout 或无标注的历史记录)按方法与路径纠正;
* 落库标注未识别时回退 method/path 现场推导(与前端 {@code semanticAction} 一致)。
*/
static String semanticAction(AuditLogSpec spec) {
var derived = actionOf(spec.getMethod(), spec.getResourceType(), spec.getPath());
if (LOGIN_FAILURE_ACTION.equals(derived) || LOGIN_PAGE_ACTION.equals(derived)
|| LOGOUT_PAGE_ACTION.equals(derived)) {
return derived;
}
var stored = spec.getAction();
return stored != null && describeAction(stored, spec.getResourceType()) != null
? stored : derived;
}
/** 由语义动作键推导中文描述;键为 null 或未识别返回 null(调用方回退 method 推导)。 */ /** 由语义动作键推导中文描述;键为 null 或未识别返回 null(调用方回退 method 推导)。 */
static String describeAction(String action, String resourceType) { static String describeAction(String action, String resourceType) {
if (action == null) { if (action == null) {
@@ -149,6 +206,19 @@ final class OperationDescription {
return method + resourceLabel(resourceType); return method + resourceLabel(resourceType);
} }
/**
* 由落库 spec 推导操作中文描述(导出用):以 {@link #semanticAction} 为准
* (含登录失败标注与页面访问纠正),无标注或未识别时回退为 method/path 现场推导
* (与前端 {@code describeOperation} 一致)。
*/
static String describe(AuditLogSpec spec) {
var phrase = describeAction(semanticAction(spec), spec.getResourceType());
if (phrase != null) {
return phrase;
}
return describe(spec.getMethod(), spec.getResourceType(), spec.getPath());
}
private static String resourceLabel(String resourceType) { private static String resourceLabel(String resourceType) {
return RESOURCE_LABELS.getOrDefault(resourceType, resourceType); return RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
} }
@@ -37,11 +37,19 @@ spec:
name: enabled name: enabled
value: false value: false
help: 统计窗口内登录失败达到触发阈值时向 Webhook 地址推送 JSON 告警(独立于审计开关,默认关闭) help: 统计窗口内登录失败达到触发阈值时向 Webhook 地址推送 JSON 告警(独立于审计开关,默认关闭)
- $formkit: text - $formkit: secret
label: Webhook 地址 label: Webhook 地址
name: webhookUrl name: webhookSecretName
value: "" descriptionPreset: 操作审计告警 Webhook
help: 接收告警的 http(s) 地址,告警以 JSON POST 异步推送(失败不重试,仅记日志) requiredKeys:
- key: webhookUrl
help: 接收告警的完整 http(s) 地址(可含 access_token 等凭据,仅存于 Secret)
help: 选择或创建存放 Webhook 地址的 Secret;地址仅在服务端读取,支持含 access_token 等凭据的地址。推送为 JSON POST 异步(失败不重试,仅记日志)
- $formkit: operationAuditTestAlert
name: testAlert
label: 测试告警
ignore: true
help: 向已保存的 Webhook 地址推送一条测试消息并直接反馈发送结果,用于验证配置是否可用(不保存任何配置值)
- $formkit: number - $formkit: number
label: 触发阈值(次) label: 触发阈值(次)
name: thresholdCount name: thresholdCount
@@ -0,0 +1,21 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
<!-- 操作审计插件 logo:审计清单(带勾选记录的文档) -->
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#4f6ef7"/>
<stop offset="1" stop-color="#2743c8"/>
</linearGradient>
</defs>
<rect x="4" y="4" width="120" height="120" rx="28" fill="url(#bg)"/>
<!-- 文档主体 -->
<rect x="34" y="30" width="60" height="68" rx="10" fill="#ffffff" opacity="0.96"/>
<!-- 顶部夹子 -->
<rect x="50" y="22" width="28" height="14" rx="7" fill="#dbe3ff"/>
<!-- 记录行:条目 + 勾选 -->
<circle cx="48" cy="52" r="5" fill="#2743c8"/>
<rect x="58" y="49" width="26" height="6" rx="3" fill="#b9c4f5"/>
<circle cx="48" cy="68" r="5" fill="#2743c8"/>
<rect x="58" y="65" width="26" height="6" rx="3" fill="#b9c4f5"/>
<path d="M43 85 l6 7 l12 -14" stroke="#2743c8" stroke-width="6" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="64" y="82" width="20" height="6" rx="3" fill="#b9c4f5"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -7,9 +7,15 @@ spec:
requires: ">=2.26.0" requires: ">=2.26.0"
author: author:
name: Guichumo name: Guichumo
website: https://gitea.guichumo.com/836061373/halo-ops-audit
logo: logo.svg
homepage: https://gitea.guichumo.com/836061373/halo-ops-audit
repo: https://gitea.guichumo.com/836061373/halo-ops-audit
issues: https://gitea.guichumo.com/836061373/halo-ops-audit/issues
displayName: "操作审计" displayName: "操作审计"
description: "记录后台写操作与登录事件,回答谁、在什么时候、对什么资源、做了什么操作、结果如何。" description: "记录后台写操作与登录事件,回答谁、在什么时候、对什么资源、做了什么操作、结果如何。"
settingName: operation-audit-settings settingName: operation-audit-settings
configMapName: operation-audit-configmap configMapName: operation-audit-configmap
license: license:
- name: "GPL-3.0" - name: "GPL-3.0"
url: "https://www.gnu.org/licenses/gpl-3.0.html"
@@ -1,6 +1,7 @@
package run.halo.operationaudit.alert; package run.halo.operationaudit.alert;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@@ -8,18 +9,34 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Secret;
import run.halo.app.plugin.ReactiveSettingFetcher; import run.halo.app.plugin.ReactiveSettingFetcher;
/** /**
* 告警设置 TTL 缓存测试(与审计设置同款模式):命中缓存、失败/缺省回退默认(告警关闭)。 * 告警设置 TTL 缓存测试(与审计设置同款模式):命中缓存、失败/缺省回退默认(告警关闭);
* Webhook 地址 Secret 解析:未配置引用 / Secret 不存在 / 缺字段 / 空白值均 fail closed
* (错误信号,绝不发送),字段值去除首尾空白。
*/ */
class AlertSettingProviderTest { class AlertSettingProviderTest {
private final ReactiveSettingFetcher fetcher = mock(ReactiveSettingFetcher.class); private final ReactiveSettingFetcher fetcher = mock(ReactiveSettingFetcher.class);
private final AlertSettingProvider provider = new AlertSettingProvider(fetcher); private final ReactiveExtensionClient client = mock(ReactiveExtensionClient.class);
private final AlertSettingProvider provider = new AlertSettingProvider(fetcher, client);
private static AlertSettings settings(String secretName) {
return new AlertSettings(true, secretName, 5, 5);
}
private static Secret secret(String url) {
var secret = new Secret();
secret.setStringData(Map.of(AlertSettingProvider.WEBHOOK_URL_FIELD, url));
return secret;
}
@Test @Test
void shouldCacheWithinTtl() { void shouldCacheWithinTtl() {
@@ -27,15 +44,15 @@ class AlertSettingProviderTest {
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class))) when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
.thenAnswer(inv -> { .thenAnswer(inv -> {
fetchCount.incrementAndGet(); fetchCount.incrementAndGet();
return Mono.just(new AlertSettings(true, "https://hooks.example.com/x", 3, 2)); return Mono.just(new AlertSettings(true, "webhook-secret", 3, 2));
}); });
var first = provider.get().block(); var first = provider.get().block();
var second = provider.get().block(); var second = provider.get().block();
assertThat(first).extracting(AlertSettings::enabled, AlertSettings::webhookUrl, assertThat(first).extracting(AlertSettings::enabled, AlertSettings::webhookSecretName,
AlertSettings::thresholdCount, AlertSettings::windowMinutes) AlertSettings::thresholdCount, AlertSettings::windowMinutes)
.containsExactly(true, "https://hooks.example.com/x", 3, 2); .containsExactly(true, "webhook-secret", 3, 2);
assertThat(second).isSameAs(first); assertThat(second).isSameAs(first);
assertThat(fetchCount.get()).isEqualTo(1); assertThat(fetchCount.get()).isEqualTo(1);
} }
@@ -49,7 +66,7 @@ class AlertSettingProviderTest {
assertThat(settings).isEqualTo(AlertSettings.defaults()); assertThat(settings).isEqualTo(AlertSettings.defaults());
assertThat(settings.enabledOrDefault()).isFalse(); assertThat(settings.enabledOrDefault()).isFalse();
assertThat(settings.webhookUrlOrDefault()).isNull(); assertThat(settings.webhookSecretNameOrDefault()).isNull();
} }
@Test @Test
@@ -73,4 +90,56 @@ class AlertSettingProviderTest {
provider.get().block(); provider.get().block();
verify(fetcher, times(2)).fetch(any(), any()); verify(fetcher, times(2)).fetch(any(), any());
} }
// ===== Webhook 地址 Secret 解析(fail closed) =====
@Test
void shouldResolveWebhookUrlFromSecret() {
when(client.fetch(eq(Secret.class), eq("webhook-secret")))
.thenReturn(Mono.just(secret(" https://hooks.example.com/x ")));
assertThat(provider.webhookUrl(settings("webhook-secret")).block())
.isEqualTo("https://hooks.example.com/x");
// 便捷方法:先读设置再解析
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
.thenReturn(Mono.just(settings("webhook-secret")));
assertThat(provider.webhookUrl().block()).isEqualTo("https://hooks.example.com/x");
}
@Test
void shouldFailClosedWhenSecretRefMissing() {
assertThatThrownBy(() -> provider.webhookUrl(settings(" ")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("未配置");
}
@Test
void shouldFailClosedWhenSecretMissing() {
when(client.fetch(eq(Secret.class), eq("gone"))).thenReturn(Mono.empty());
assertThatThrownBy(() -> provider.webhookUrl(settings("gone")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("不存在");
}
@Test
void shouldFailClosedWhenSecretFieldMissing() {
var secret = new Secret();
secret.setStringData(Map.of("other", "value"));
when(client.fetch(eq(Secret.class), eq("webhook-secret"))).thenReturn(Mono.just(secret));
assertThatThrownBy(() -> provider.webhookUrl(settings("webhook-secret")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining(AlertSettingProvider.WEBHOOK_URL_FIELD);
}
@Test
void shouldFailClosedWhenSecretFieldBlank() {
when(client.fetch(eq(Secret.class), eq("webhook-secret")))
.thenReturn(Mono.just(secret(" ")));
assertThatThrownBy(() -> provider.webhookUrl(settings("webhook-secret")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("缺少");
}
} }
@@ -5,7 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* 告警设置归一测试:缺省/非法值回退默认,Webhook 地址仅接受 http(s)。 * 告警设置归一测试:缺省/非法值回退默认;凭据安全要求下本记录只持有 Secret 引用名
* (真实 Webhook 地址由 AlertSettingProvider 从 Secret 解析)。
*/ */
class AlertSettingsTest { class AlertSettingsTest {
@@ -14,33 +15,25 @@ class AlertSettingsTest {
var settings = AlertSettings.defaults(); var settings = AlertSettings.defaults();
assertThat(settings.enabledOrDefault()).isFalse(); assertThat(settings.enabledOrDefault()).isFalse();
assertThat(settings.webhookUrlOrDefault()).isNull(); assertThat(settings.webhookSecretNameOrDefault()).isNull();
assertThat(settings.thresholdCountOrDefault()).isEqualTo(5); assertThat(settings.thresholdCountOrDefault()).isEqualTo(5);
assertThat(settings.windowMinutesOrDefault()).isEqualTo(5); assertThat(settings.windowMinutesOrDefault()).isEqualTo(5);
} }
@Test @Test
void shouldNormalizeWebhookUrl() { void shouldNormalizeSecretName() {
assertThat(new AlertSettings(true, " https://hooks.example.com/x ", null, null) assertThat(new AlertSettings(true, " operation-audit-webhook ", null, null)
.webhookUrlOrDefault()).isEqualTo("https://hooks.example.com/x"); .webhookSecretNameOrDefault()).isEqualTo("operation-audit-webhook");
assertThat(new AlertSettings(true, "http://127.0.0.1:9000/hook", null, null)
.webhookUrlOrDefault()).isEqualTo("http://127.0.0.1:9000/hook");
// 大写 scheme 同样接受(URL scheme 不区分大小写)
assertThat(new AlertSettings(true, "HTTPS://hooks.example.com/x", null, null)
.webhookUrlOrDefault()).isEqualTo("HTTPS://hooks.example.com/x");
} }
@Test @Test
void shouldRejectNonHttpWebhookUrl() { void shouldRejectBlankSecretName() {
assertThat(new AlertSettings(true, null, null, null).webhookUrlOrDefault()).isNull(); assertThat(new AlertSettings(true, null, null, null).webhookSecretNameOrDefault())
assertThat(new AlertSettings(true, "", null, null).webhookUrlOrDefault()).isNull(); .isNull();
assertThat(new AlertSettings(true, " ", null, null).webhookUrlOrDefault()).isNull(); assertThat(new AlertSettings(true, "", null, null).webhookSecretNameOrDefault())
assertThat(new AlertSettings(true, "ftp://hooks.example.com", null, null) .isNull();
.webhookUrlOrDefault()).isNull(); assertThat(new AlertSettings(true, " ", null, null).webhookSecretNameOrDefault())
assertThat(new AlertSettings(true, "hooks.example.com/x", null, null) .isNull();
.webhookUrlOrDefault()).isNull();
assertThat(new AlertSettings(true, "javascript:alert(1)", null, null)
.webhookUrlOrDefault()).isNull();
} }
@Test @Test
@@ -67,8 +60,11 @@ class AlertSettingsTest {
@Test @Test
void shouldRespectExplicitEnabledFlag() { void shouldRespectExplicitEnabledFlag() {
assertThat(new AlertSettings(null, "https://x", null, null).enabledOrDefault()).isFalse(); assertThat(new AlertSettings(null, "webhook-secret", null, null).enabledOrDefault())
assertThat(new AlertSettings(false, "https://x", null, null).enabledOrDefault()).isFalse(); .isFalse();
assertThat(new AlertSettings(true, "https://x", null, null).enabledOrDefault()).isTrue(); assertThat(new AlertSettings(false, "webhook-secret", null, null).enabledOrDefault())
.isFalse();
assertThat(new AlertSettings(true, "webhook-secret", null, null).enabledOrDefault())
.isTrue();
} }
} }
@@ -0,0 +1,123 @@
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 地址不可用(未配置引用/Secret 缺失/缺键)
* 返回 400、推送结果同步返回(200 + success/message)、测试负载结构(type=test 与
* login-failure 区分)。
*/
class AlertTestEndpointTest {
private static final String TEST_URI = "/apis/" + "audit.guichumo.com" + "/v1alpha1/alerts/-/test";
private static final String WEBHOOK_URL = "https://hooks.example.com/x";
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 secretName) {
return new AlertSettings(true, secretName, 5, 5);
}
@Test
void shouldRejectWhenWebhookUrlUnavailable() {
when(settingProvider.webhookUrl()).thenReturn(Mono.error(new IllegalStateException(
"Webhook 地址未配置(需在设置中选择或创建 Secret),请先保存设置")));
webClient.post().uri(TEST_URI)
.exchange()
.expectStatus().isBadRequest()
.expectBody()
.jsonPath("$.message").isEqualTo(
"Webhook 地址未配置(需在设置中选择或创建 Secret),请先保存设置");
verify(sender, org.mockito.Mockito.never()).sendForResult(any(), any());
}
@Test
void shouldReturnSuccessResult() {
when(settingProvider.webhookUrl()).thenReturn(Mono.just(WEBHOOK_URL));
when(sender.sendForResult(eq(WEBHOOK_URL), 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.webhookUrl()).thenReturn(Mono.just(WEBHOOK_URL));
when(sender.sendForResult(eq(WEBHOOK_URL), 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.webhookUrl()).thenReturn(Mono.just(WEBHOOK_URL));
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(WEBHOOK_URL);
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);
}
}
@@ -7,22 +7,32 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/** /**
* Webhook 推送集成测试(JDK 内置 HttpServer 走真实 HTTP): * Webhook 推送集成测试(JDK 内置 HttpServer 走真实 HTTP):
* JSON POST 负载可达、非 2xx / 连接失败 / URL 非法均静默降级不抛出。 *
* <p>HTTP 机制经 {@code sendToTarget} 直接驱动(目标已完成校验、地址钉定)——
* JSON POST 负载可达、非 2xx / 连接失败 / 校验失败均归一为结果或静默降级不抛出;
* 结果化推送(功能评审 P0-2)返回送达与否 + 原因摘要,同样永不抛出。
*
* <p>出站安全链路经 {@code sendForResult} 驱动(真实路径):回环/内网等受限地址
* 在 SSRF 校验阶段即拒绝(不建连),建连钉定校验地址(DNS rebinding 防护——
* 主机名 localhost + 钉定 127.0.0.2 的用例证明建连走钉定地址而非 DNS 结果)。
*/ */
class AlertWebhookSenderTest { class AlertWebhookSenderTest {
private HttpServer server; private HttpServer server;
private final AlertWebhookSender sender = new AlertWebhookSender(); private final AlertWebhookSender sender = new AlertWebhookSender(new OutboundUrlGuard());
@AfterEach @AfterEach
void tearDown() { void tearDown() {
@@ -31,10 +41,10 @@ class AlertWebhookSenderTest {
} }
} }
private HttpServer startServer(int status, AtomicReference<byte[]> body, /** 在指定回环地址上启动测试 HTTP 服务,返回实际端口。 */
private int startServer(InetAddress bind, int status, AtomicReference<byte[]> body,
AtomicReference<String> contentType, CountDownLatch received) throws Exception { AtomicReference<String> contentType, CountDownLatch received) throws Exception {
var httpServer = HttpServer.create( var httpServer = HttpServer.create(new InetSocketAddress(bind, 0), 0);
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
httpServer.createContext("/hook", exchange -> { httpServer.createContext("/hook", exchange -> {
body.set(exchange.getRequestBody().readAllBytes()); body.set(exchange.getRequestBody().readAllBytes());
contentType.set(exchange.getRequestHeaders().getFirst("Content-Type")); contentType.set(exchange.getRequestHeaders().getFirst("Content-Type"));
@@ -43,18 +53,30 @@ class AlertWebhookSenderTest {
received.countDown(); received.countDown();
}); });
httpServer.start(); httpServer.start();
return httpServer; server = httpServer;
return httpServer.getAddress().getPort();
}
/** 构造已校验钉定目标(等价守卫对公网地址放行后的产物)。 */
private static OutboundUrlGuard.ValidatedTarget pinnedTarget(String url)
throws Exception {
var uri = new URI(url);
return new OutboundUrlGuard.ValidatedTarget(uri, uri.getPort(),
InetAddress.getByName(uri.getHost()));
} }
@Test @Test
void shouldPostJsonPayload() throws Exception { void shouldPostJsonPayloadViaPinnedTarget() throws Exception {
var body = new AtomicReference<byte[]>(); var body = new AtomicReference<byte[]>();
var contentType = new AtomicReference<String>(); var contentType = new AtomicReference<String>();
var received = new CountDownLatch(1); var received = new CountDownLatch(1);
server = startServer(200, body, contentType, received); var port = startServer(InetAddress.getLoopbackAddress(), 200, body, contentType,
received);
var url = "http://127.0.0.1:" + port + "/hook";
sender.send("http://127.0.0.1:" + server.getAddress().getPort() + "/hook", // fire-and-forget 语义:订阅即异步执行,不等待结果
Map.of("title", "操作审计告警:登录失败", "failures", 3)); sender.sendToTarget(pinnedTarget(url),
Map.of("title", "操作审计告警:登录失败", "failures", 3)).subscribe();
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
@@ -64,31 +86,109 @@ class AlertWebhookSenderTest {
assertThat(payload.get("failures").asInt()).isEqualTo(3); assertThat(payload.get("failures").asInt()).isEqualTo(3);
} }
@Test
void shouldConnectToPinnedAddressInsteadOfDns() throws Exception {
// DNS rebinding 防护证明:主机名 localhost 的 DNS 结果是 127.0.0.1,
// 服务却监听在 127.0.0.2 —— 建连必须走钉定地址才能送达
var pinned = InetAddress.getByAddress(new byte[] {127, 0, 0, 2});
var body = new AtomicReference<byte[]>();
var contentType = new AtomicReference<String>();
var received = new CountDownLatch(1);
var port = startServer(pinned, 200, body, contentType, received);
// 目标地址与 URL 主机名刻意不同:模拟"校验时解析结果 ≠ 重绑定后的 DNS 结果"
var target = new OutboundUrlGuard.ValidatedTarget(
new URI("http://localhost:" + port + "/hook"), port, pinned);
var result = sender.sendToTarget(target, Map.of("pin", true))
.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 @Test
void shouldNotThrowOnNon2xxResponse() throws Exception { void shouldNotThrowOnNon2xxResponse() throws Exception {
var body = new AtomicReference<byte[]>(); var body = new AtomicReference<byte[]>();
var contentType = new AtomicReference<String>(); var contentType = new AtomicReference<String>();
var received = new CountDownLatch(1); var received = new CountDownLatch(1);
server = startServer(500, body, contentType, received); var port = startServer(InetAddress.getLoopbackAddress(), 500, body, contentType,
received);
var url = "http://127.0.0.1:" + port + "/hook";
assertThatCode(() -> sender.send( assertThatCode(() -> sender.sendToTarget(pinnedTarget(url), Map.of()).subscribe())
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of()))
.doesNotThrowAnyException(); .doesNotThrowAnyException();
// 500 响应同样送达(接收方先收到请求才返回 500),随后静默降级为日志 // 500 响应同样送达(接收方先收到请求才返回 500),随后静默降级为日志
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
StepVerifier.create(sender.sendToTarget(pinnedTarget(url), Map.of()))
.assertNext(result -> {
assertThat(result.success()).isFalse();
assertThat(result.message()).isNotBlank();
})
.verifyComplete();
} }
@Test @Test
void shouldNotThrowWhenTargetUnreachable() { void shouldReturnFailureResultWhenTargetUnreachable() throws Exception {
// 端口 1 保留端口,连接立即被拒:异步失败仅记日志 // 服务监听后立即停止(端口保留);或直接钉定无监听端口 → 连接失败归一为失败结果
assertThatCode(() -> sender.send("http://127.0.0.1:1/hook", Map.of())) var bound = InetAddress.getLoopbackAddress();
var socket = new java.net.ServerSocket(0, 1, bound);
var port = socket.getLocalPort();
socket.close();
var result = sender.sendToTarget(pinnedTarget("http://127.0.0.1:" + port + "/hook"),
Map.of())
.block(java.time.Duration.ofSeconds(10));
assertThat(result).isNotNull();
assertThat(result.success()).isFalse();
assertThat(result.message()).isNotBlank();
}
// ===== 出站安全链路(sendForResult:真实路径,SSRF 校验前置) =====
@Test
void shouldRejectLoopbackTargetBeforeConnecting() throws Exception {
// 回环地址在 SSRF 校验阶段即拒绝,绝不建连(端口 9 无监听,若建连会失败而非拒绝)
var result = sender.sendForResult("http://127.0.0.1:9/hook", Map.of())
.block(java.time.Duration.ofSeconds(10));
assertThat(result).isNotNull();
assertThat(result.success()).isFalse();
assertThat(result.message()).contains("受限网络地址");
}
@Test
void shouldRejectPrivateIpTarget() {
StepVerifier.create(sender.sendForResult("http://10.0.0.1/hook", Map.of()))
.assertNext(result -> {
assertThat(result.success()).isFalse();
assertThat(result.message()).contains("受限网络地址");
})
.verifyComplete();
}
@Test
void shouldNormalizeMalformedUrlToFailureResult() {
// 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();
assertThat(sender.sendForResult("ftp://hooks.example.com", 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:9/hook", Map.of()))
.doesNotThrowAnyException(); .doesNotThrowAnyException();
}
@Test
void shouldNotThrowWhenUrlMalformed() {
assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException(); assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException();
assertThatCode(() -> sender.send(null, Map.of())).doesNotThrowAnyException();
} }
} }
@@ -25,10 +25,14 @@ import run.halo.operationaudit.audit.RequestSnapshot;
/** /**
* 登录失败告警阈值窗口测试(产品设计 V2「告警通知」): * 登录失败告警阈值窗口测试(产品设计 V2「告警通知」):
* 达阈值告警一次、告警后重开窗口、窗口过期重开、登录成功清零、开关与地址归一降级。 * 达阈值告警一次、告警后重开窗口、窗口过期重开、登录成功清零、开关与地址降级。
* Webhook 地址凭据存于 Halo Secret:handle 先经 AlertSettingProvider 解析地址,
* 未配置/解析失败则静默跳过(不计数也不告警)。
*/ */
class LoginFailureAlertServiceTest { class LoginFailureAlertServiceTest {
/** 设置中持有的 Secret 引用名(测试桩,非真实凭据)。 */
private static final String WEBHOOK_REF = "operation-audit-webhook";
private static final String WEBHOOK_URL = "https://hooks.example.com/halo-alert"; private static final String WEBHOOK_URL = "https://hooks.example.com/halo-alert";
private AlertSettingProvider settingProvider; private AlertSettingProvider settingProvider;
@@ -40,11 +44,14 @@ class LoginFailureAlertServiceTest {
settingProvider = mock(AlertSettingProvider.class); settingProvider = mock(AlertSettingProvider.class);
sender = mock(AlertWebhookSender.class); sender = mock(AlertWebhookSender.class);
service = new LoginFailureAlertService(settingProvider, sender); service = new LoginFailureAlertService(settingProvider, sender);
// 默认解析成功:真实地址由 Secret 解析给出(凭据不出 Secret)
when(settingProvider.webhookUrl(any(AlertSettings.class)))
.thenReturn(Mono.just(WEBHOOK_URL));
} }
private void enableAlerts(int threshold, int windowMinutes) { private void enableAlerts(int threshold, int windowMinutes) {
when(settingProvider.get()).thenReturn(Mono.just( when(settingProvider.get()).thenReturn(Mono.just(
new AlertSettings(true, WEBHOOK_URL, threshold, windowMinutes))); new AlertSettings(true, WEBHOOK_REF, threshold, windowMinutes)));
} }
private static RequestSnapshot loginSnapshot() { private static RequestSnapshot loginSnapshot() {
@@ -67,12 +74,12 @@ class LoginFailureAlertServiceTest {
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
var now = Instant.now(); var now = Instant.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, now); service.handle(settings(3, 5), snapshot, false, null, now);
verify(sender, never()).send(any(), any()); 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(); var payload = capturedPayload();
assertThat(payload.get("type")).isEqualTo("login-failure"); assertThat(payload.get("type")).isEqualTo("login-failure");
@@ -86,7 +93,8 @@ class LoginFailureAlertServiceTest {
.containsEntry("failures", 3) .containsEntry("failures", 3)
.containsEntry("windowMinutes", 5) .containsEntry("windowMinutes", 5)
.containsEntry("remoteIp", "127.0.0.1") .containsEntry("remoteIp", "127.0.0.1")
.containsEntry("userAgent", "UA-1"); .containsEntry("userAgent", "UA-1")
.containsEntry("attemptedUsername", null);
} }
@Test @Test
@@ -96,11 +104,11 @@ class LoginFailureAlertServiceTest {
var now = Instant.now(); var now = Instant.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, now); service.handle(settings(3, 5), snapshot, false, null, 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, now); service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, now); service.handle(settings(3, 5), snapshot, false, null, now);
verify(sender, times(1)).send(any(), any()); verify(sender, times(1)).send(any(), any());
} }
@@ -111,11 +119,11 @@ class LoginFailureAlertServiceTest {
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
var now = Instant.now(); var now = Instant.now();
service.handle(settings, snapshot, false, now); service.handle(settings, snapshot, false, null, now);
service.handle(settings, snapshot, false, now); service.handle(settings, snapshot, false, null, now);
// 告警后窗口重开,再次累计到阈值 → 第二次告警 // 告警后窗口重开,再次累计到阈值 → 第二次告警
service.handle(settings, snapshot, false, now); service.handle(settings, snapshot, false, null, now);
service.handle(settings, snapshot, false, now); service.handle(settings, snapshot, false, null, now);
verify(sender, times(2)).send(any(), any()); verify(sender, times(2)).send(any(), any());
} }
@@ -127,13 +135,13 @@ class LoginFailureAlertServiceTest {
var now = Instant.now(); var now = Instant.now();
// 第一次失败开启窗口,10 分钟后窗口已过期 → 计数从新窗口重新开始 // 第一次失败开启窗口,10 分钟后窗口已过期 → 计数从新窗口重新开始
service.handle(settings(3, 5), snapshot, false, now); service.handle(settings(3, 5), snapshot, false, null, now);
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)));
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)));
verify(sender, never()).send(any(), any()); 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(); var payload = capturedPayload();
assertThat((Map<String, Object>) payload.get("data")).containsEntry("failures", 3); assertThat((Map<String, Object>) payload.get("data")).containsEntry("failures", 3);
@@ -145,36 +153,38 @@ class LoginFailureAlertServiceTest {
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
var now = Instant.now(); var now = Instant.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, now); service.handle(settings(3, 5), snapshot, false, null, now);
// 登录成功立即清零:其后失败需重新累计 // 登录成功立即清零:其后失败需重新累计
service.handle(settings(3, 5), snapshot, true, now); service.handle(settings(3, 5), snapshot, true, null, 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, now); service.handle(settings(3, 5), snapshot, false, null, now);
verify(sender, never()).send(any(), any()); 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()); verify(sender, times(1)).send(any(), any());
} }
@Test @Test
void shouldTreat3xxAsFailure() { void shouldCountFailureFromCallbackFlag() {
// 状态码→成败的解释已上移到 LoginOutcome(表单登录成败均为 302 重定向),
// 服务只按回调布尔计数:false 计失败
enableAlerts(1, 5); enableAlerts(1, 5);
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 302); service.onLoginResult(snapshot, false, null);
verify(sender, times(1)).send(eq(WEBHOOK_URL), any()); verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
} }
@Test @Test
void shouldTreat2xxAsSuccess() { void shouldResetCounterOnSuccessCallback() {
enableAlerts(1, 5); enableAlerts(1, 5);
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 200); service.onLoginResult(snapshot, true, null);
service.onLoginResult(snapshot, 204); service.onLoginResult(snapshot, true, null);
verify(sender, never()).send(any(), any()); verify(sender, never()).send(any(), any());
} }
@@ -184,34 +194,66 @@ class LoginFailureAlertServiceTest {
enableAlerts(1, 5); enableAlerts(1, 5);
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 401); service.onLoginResult(snapshot, false, null);
verify(sender, times(1)).send(eq(WEBHOOK_URL), any()); 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, false, "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, false, null);
var payload = capturedPayload();
assertThat((String) payload.get("content")).doesNotContain("尝试的账号");
assertThat((Map<String, Object>) payload.get("data"))
.containsEntry("attemptedUsername", null);
}
@Test @Test
void shouldSkipWhenAlertDisabled() { void shouldSkipWhenAlertDisabled() {
when(settingProvider.get()).thenReturn(Mono.just( when(settingProvider.get()).thenReturn(Mono.just(
new AlertSettings(false, WEBHOOK_URL, 1, 5))); new AlertSettings(false, WEBHOOK_REF, 1, 5)));
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用) // 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
service.onLoginResult(snapshot, 401); service.onLoginResult(snapshot, false, null);
service.onLoginResult(snapshot, 401); service.onLoginResult(snapshot, false, null);
verify(sender, never()).send(any(), any()); verify(sender, never()).send(any(), any());
assertThat(service.failureCount).isZero(); assertThat(service.failureCount).isZero();
} }
@Test @Test
void shouldSkipWhenWebhookUrlMissing() { void shouldSkipWhenWebhookUrlUnavailable() {
when(settingProvider.get()).thenReturn(Mono.just( when(settingProvider.get()).thenReturn(Mono.just(
new AlertSettings(true, " ", 1, 5))); new AlertSettings(true, " ", 1, 5)));
when(settingProvider.webhookUrl(any(AlertSettings.class)))
.thenReturn(Mono.error(new IllegalStateException("Webhook 地址未配置")));
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 401); // 地址解析失败(未配置 Secret / Secret 缺字段):静默跳过,不计数也不告警
service.onLoginResult(snapshot, false, null);
service.onLoginResult(snapshot, false, null);
verify(sender, never()).send(any(), any()); verify(sender, never()).send(any(), any());
assertThat(service.failureCount).isZero();
} }
@Test @Test
@@ -219,7 +261,8 @@ class LoginFailureAlertServiceTest {
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom"))); when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
var snapshot = loginSnapshot(); var snapshot = loginSnapshot();
assertThatCode(() -> service.onLoginResult(snapshot, 401)).doesNotThrowAnyException(); assertThatCode(() -> service.onLoginResult(snapshot, false, null))
.doesNotThrowAnyException();
verify(sender, never()).send(any(), any()); verify(sender, never()).send(any(), any());
} }
@@ -230,7 +273,7 @@ class LoginFailureAlertServiceTest {
doThrow(new IllegalStateException("webhook broken")) doThrow(new IllegalStateException("webhook broken"))
.when(sender).send(any(), any()); .when(sender).send(any(), any());
assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401)) assertThatCode(() -> service.onLoginResult(loginSnapshot(), false, null))
.doesNotThrowAnyException(); .doesNotThrowAnyException();
} }
@@ -241,15 +284,15 @@ class LoginFailureAlertServiceTest {
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678)) .remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.build()); .build());
service.onLoginResult(snapshot, 401); service.onLoginResult(snapshot, false, null);
var payload = capturedPayload(); var payload = capturedPayload();
assertThat((String) payload.get("content")).doesNotContain("()"); assertThat((String) payload.get("content")).doesNotContain("()");
assertThat((Map<String, Object>) payload.get("data")).containsEntry("userAgent", null); assertThat((Map<String, Object>) payload.get("data")).containsEntry("userAgent", null);
} }
/** 直接驱动 handle 用的告警设置(handle 不读设置缓存,参数须与断言一致)。 */ /** 直接驱动 handle 用的告警设置(handle 只读开关/阈值,地址走 provider 解析)。 */
private AlertSettings settings(int thresholdCount, int windowMinutes) { private AlertSettings settings(int thresholdCount, int windowMinutes) {
return new AlertSettings(true, WEBHOOK_URL, thresholdCount, windowMinutes); return new AlertSettings(true, WEBHOOK_REF, thresholdCount, windowMinutes);
} }
} }
@@ -0,0 +1,236 @@
package run.halo.operationaudit.alert;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
/**
* 出站地址守卫测试(官方《敏感数据与出站请求》指南逐项覆盖):
* 结构校验(scheme 白名单/主机名/用户名密码形态/端口)、危险地址段拒绝
* (环回/私网/链路本地/组播/未指定/云元数据/CGNAT/ULA/过渡机制/文档与保留段)、
* 内嵌 IPv4 映射地址、合法公网地址放行、钉定目标构造。
*/
class OutboundUrlGuardTest {
private final OutboundUrlGuard guard = new OutboundUrlGuard();
private static InetAddress addr(String literal) throws Exception {
return InetAddress.getByName(literal);
}
private static void assertForbidden(String literal) throws Exception {
assertThat(OutboundUrlGuard.isForbiddenAddress(addr(literal)))
.as("应拒绝 " + literal)
.isTrue();
}
private static void assertAllowed(String literal) throws Exception {
assertThat(OutboundUrlGuard.isForbiddenAddress(addr(literal)))
.as("应放行 " + literal)
.isFalse();
}
// ===== 结构校验(scheme / 主机名 / 用户名密码形态 / 端口) =====
@Test
void shouldRejectBlankOrNullUrl() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(null))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("为空");
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(" "))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("为空");
}
@Test
void shouldRejectUnparsableUrl() {
// "not-a-url" 被 URI 解析为相对引用(无 scheme):落入 scheme 白名单拒绝,
// 与无法解析同等不可用
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure("not-a-url"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("http(s)");
}
@Test
void shouldRejectNonHttpSchemes() {
for (var url : new String[] {"ftp://hooks.example.com/x", "javascript:alert(1)",
"file:///etc/passwd", "ws://hooks.example.com", "//hooks.example.com/x"}) {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(url))
.as(url)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("http(s)");
}
}
@Test
void shouldAcceptHttpAndHttpsInAnyCase() throws Exception {
assertThat(OutboundUrlGuard.checkStructure("http://hooks.example.com/x").getHost())
.isEqualTo("hooks.example.com");
assertThat(OutboundUrlGuard.checkStructure("HTTPS://hooks.example.com/x").getPort())
.isEqualTo(-1);
assertThat(OutboundUrlGuard.checkStructure("Http://hooks.example.com").getScheme())
.isEqualTo("Http");
}
@Test
void shouldRejectMissingHost() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure("http:///path"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("主机名");
}
@Test
void shouldRejectUserInfoForm() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(
"https://user:pass@hooks.example.com/x"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("用户名/密码");
}
@Test
void shouldRejectIllegalPort() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure("https://hooks.example.com:70000"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("端口");
}
// ===== 危险地址段判定 =====
@Test
void shouldRejectLoopbackAndUnspecified() throws Exception {
assertForbidden("127.0.0.1");
assertForbidden("127.5.5.5");
assertForbidden("0.0.0.0");
assertForbidden("0.1.2.3"); // 0/8 本网络段
assertForbidden("::1");
assertForbidden("::");
}
@Test
void shouldRejectPrivateRanges() throws Exception {
assertForbidden("10.0.0.1");
assertForbidden("172.16.0.1");
assertForbidden("192.168.1.1");
assertForbidden("fd00::1"); // IPv6 ULA(Java 未覆盖,补充判定)
assertForbidden("fd00:ec2::254"); // AWS IMDS IPv6
assertForbidden("fe80::1"); // 链路本地
}
@Test
void shouldRejectCloudMetadataAddresses() throws Exception {
assertForbidden("169.254.169.254"); // AWS/GCP/Azure 元数据(链路本地)
assertForbidden("100.100.100.200"); // 阿里云元数据(CGNAT 段,Java 未覆盖)
assertForbidden("100.64.0.1"); // 100.64/10 共享地址段
}
@Test
void shouldRejectMulticastAndReservedRanges() throws Exception {
assertForbidden("224.0.0.1");
assertForbidden("ff02::1");
assertForbidden("240.0.0.1");
assertForbidden("255.255.255.255");
assertForbidden("192.0.0.1");
assertForbidden("192.0.2.1");
assertForbidden("198.18.0.1");
assertForbidden("198.51.100.7");
assertForbidden("203.0.113.9");
}
@Test
void shouldRejectIpv6TransitionAndDocRanges() throws Exception {
assertForbidden("2001:0000:4136:e378:8000:63bf:3fff:fdd2"); // Teredo
assertForbidden("2002:a9fe:a9fe::1"); // 6to4 内嵌 169.254.169.254
assertForbidden("2001:db8::1"); // 文档段
}
@Test
void shouldRejectIpv4MappedOrCompatibleEmbeds() throws Exception {
// ::ffff:x.x.x.x 映射与 ::x.x.x.x 兼容形态按内嵌 IPv4 再判
assertForbidden("::ffff:10.0.0.1");
assertForbidden("::ffff:127.0.0.1");
assertForbidden("::10.0.0.1");
assertAllowed("::ffff:8.8.8.8"); // 映射公网地址放行
}
@Test
void shouldAllowPublicAddresses() throws Exception {
assertAllowed("8.8.8.8");
assertAllowed("1.1.1.1");
assertAllowed("2606:4700::1111");
}
@Test
void shouldClassifyAddressTypes() throws Exception {
assertThat(addr("8.8.8.8")).isInstanceOf(Inet4Address.class);
assertThat(addr("2606:4700::1111")).isInstanceOf(Inet6Address.class);
}
// ===== validate:解析 + 拒绝 + 放行(离线可验证场景) =====
@Test
void shouldValidatePublicIpLiteral() {
// IP 字面量不查 DNS(离线可测):公网地址放行并钉定
StepVerifier.create(guard.validate("https://8.8.8.8:8443/hook"))
.assertNext(target -> {
assertThat(target.address().getHostAddress()).isEqualTo("8.8.8.8");
assertThat(target.port()).isEqualTo(8443);
assertThat(target.uri().getPath()).isEqualTo("/hook");
assertThat(target.toSocketAddress().getPort()).isEqualTo(8443);
})
.verifyComplete();
}
@Test
void shouldRejectLoopbackHostname() {
// localhost 解析到环回地址:整体拒绝(validate 全链路)
StepVerifier.create(guard.validate("http://localhost:1/hook"))
.expectErrorSatisfies(e -> assertThat(e)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("受限网络地址"))
.verify();
}
@Test
void shouldRejectUnresolvableHost() {
// .invalid TLD 保证 NXDOMAIN(RFC 6761):解析失败 fail closed
StepVerifier.create(guard.validate("http://webhook.invalid/hook"))
.expectErrorSatisfies(e -> assertThat(e)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("无法解析"))
.verify();
}
@Test
void shouldRejectMalformedUrlViaValidate() {
StepVerifier.create(guard.validate("javascript:alert(1)"))
.expectErrorSatisfies(e -> assertThat(e)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("http(s)"))
.verify();
}
@Test
void shouldExposeUriAndPortOnValidatedTarget() throws Exception {
var target = new OutboundUrlGuard.ValidatedTarget(
new URI("http://hooks.example.com:9000/x"), 9000, addr("8.8.8.8"));
assertThat(target.toSocketAddress().getAddress().getHostAddress()).isEqualTo("8.8.8.8");
assertThat(target.toSocketAddress().getPort()).isEqualTo(9000);
}
// ===== 日志卫生:主机名提取(地址可能内嵌凭据,绝不整体落日志) =====
@Test
void shouldExtractHostForLogging() {
assertThat(OutboundUrlGuard.urlHost("https://hooks.example.com/x?token=abc"))
.isEqualTo("hooks.example.com");
assertThat(OutboundUrlGuard.urlHost(null)).isEqualTo("<unset>");
assertThat(OutboundUrlGuard.urlHost(" ")).isEqualTo("<unset>");
assertThat(OutboundUrlGuard.urlHost("not-a-url")).isEqualTo("<unparsed>");
}
}
@@ -39,7 +39,7 @@ class AuditExportEndpointTest {
"/apis/" + AuditLog.GROUP + "/v1alpha1/auditlogs/-/export"; "/apis/" + AuditLog.GROUP + "/v1alpha1/auditlogs/-/export";
private static final String CSV_HEADER = private static final String CSV_HEADER =
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent"; "操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
private ReactiveExtensionClient client; private ReactiveExtensionClient client;
private WebTestClient webClient; private WebTestClient webClient;
@@ -57,13 +57,14 @@ class AuditExportEndpointTest {
} }
private static AuditLog auditLog(String name, Instant creationTimestamp, String username, private static AuditLog auditLog(String name, Instant creationTimestamp, String username,
String method, String resourceType, String resourceName, String path, String attemptedUsername, String method, String resourceType, String resourceName,
Integer statusCode, String remoteIp, String userAgent) { String path, Integer statusCode, String remoteIp, String userAgent) {
var metadata = new Metadata(); var metadata = new Metadata();
metadata.setName(name); metadata.setName(name);
metadata.setCreationTimestamp(creationTimestamp); metadata.setCreationTimestamp(creationTimestamp);
var spec = new AuditLogSpec(); var spec = new AuditLogSpec();
spec.setUsername(username); spec.setUsername(username);
spec.setAttemptedUsername(attemptedUsername);
spec.setMethod(method); spec.setMethod(method);
spec.setResourceType(resourceType); spec.setResourceType(resourceType);
spec.setResourceName(resourceName); spec.setResourceName(resourceName);
@@ -94,11 +95,12 @@ class AuditExportEndpointTest {
void shouldExportCsvWithBomHeaderAndRows() { void shouldExportCsvWithBomHeaderAndRows() {
var time = Instant.parse("2026-11-01T00:00:00Z"); var time = Instant.parse("2026-11-01T00:00:00Z");
stubSinglePage(List.of( 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", "/apis/api.console.halo.run/v1alpha1/users", 201, "127.0.0.1",
"Mozilla/5.0"), "Mozilla/5.0"),
auditLog("auditlog-2", time.plusSeconds(60), "unknown", "POST", "auth", null, // 登录失败记录(功能评审 P0-1):尝试用户列为登录时尝试的用户名
"/login", 401, "10.0.0.8", "Mozilla/5.0"))); 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); var body = exportAndGetBody(EXPORT_URI);
@@ -106,16 +108,88 @@ class AuditExportEndpointTest {
var lines = body.split("\r\n"); var lines = body.split("\r\n");
assertThat(lines).hasSize(3); // 表头 + 2 行数据(末尾 \r\n 切出的空串不进 split 前段) assertThat(lines).hasSize(3); // 表头 + 2 行数据(末尾 \r\n 切出的空串不进 split 前段)
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time) 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"); + ",新建用户,,成功,201,127.0.0.1,Mozilla/5.0");
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60)) 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 shouldExportLoginFailureRowsAsFailureDespiteHttp2xx3xx() {
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)状态码落在
// 2xx/3xx,结果列仍应为「失败」;描述列优先落库语义动作(登录失败)。
// 升级前落库的失败回显页(GET /login?error=...,200,带同一标注)同样导出失败
var time = Instant.parse("2026-11-01T00:00:00Z");
var failedFormLogin = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth",
null, "/login", 302, "119.53.161.18", "Mozilla/5.0");
failedFormLogin.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
var failureEcho = auditLog("auditlog-2", time.plusSeconds(60), "unknown", null, "GET",
"auth", null, "/login?error=invalid-credential&method=local", 200, "119.53.161.18",
"Mozilla/5.0");
failureEcho.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
stubSinglePage(List.of(failedFormLogin, failureEcho));
var body = exportAndGetBody(EXPORT_URI);
var lines = body.split("\r\n");
assertThat(lines).hasSize(3);
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
+ ",unknown,admin,POST,auth,,/login,登录失败,,失败,302,119.53.161.18,Mozilla/5.0");
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
+ ",unknown,,GET,auth,,/login?error=invalid-credential&method=local"
+ ",登录失败,,失败,200,119.53.161.18,Mozilla/5.0");
}
@Test
void shouldExportSuccessfulLoginAsSuccessInsteadOfBareRedirectCode() {
// 登录成功(表单提交为 302):结果列写「成功」,与失败的「失败」对称
var time = Instant.parse("2026-11-01T00:00:00Z");
var success = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth", null,
"/login", 302, "116.179.32.88", "Mozilla/5.0");
success.getSpec().setAction("login");
stubSinglePage(List.of(success));
var body = exportAndGetBody(EXPORT_URI);
var lines = body.split("\r\n");
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
+ ",unknown,admin,POST,auth,,/login,登录,,成功,302,116.179.32.88,Mozilla/5.0");
}
@Test
void shouldExportAuthPageVisitsAsPageVisitInsteadOfLoginSuccess() {
// 升级前落库的页面访问记录(GET /login、GET /logout,带着 login/logout 标注、
// HTTP 200):原先导出为「登录,成功」,看起来像未知用户登录成功;
// 现在描述列写「访问登录页/访问登出页」,结果列写「页面访问」(不计成败)
var time = Instant.parse("2026-12-04T14:16:36Z");
var bounced = auditLog("auditlog-1", time, "unknown", null, "GET", "auth", null,
"/login?authentication_required", 200, "43.228.157.244", "Mozilla/5.0");
bounced.getSpec().setAction("login");
var opened = auditLog("auditlog-2", time.plusSeconds(9), "unknown", null, "GET", "auth",
null, "/login", 200, "43.228.157.244", "Mozilla/5.0");
opened.getSpec().setAction("login");
var logoutConfirm = auditLog("auditlog-3", time.plusSeconds(60), "unknown", null,
"GET", "auth", null, "/logout", 200, "127.0.0.1", "Mozilla/5.0");
logoutConfirm.getSpec().setAction("logout");
stubSinglePage(List.of(bounced, opened, logoutConfirm));
var body = exportAndGetBody(EXPORT_URI);
var lines = body.split("\r\n");
assertThat(lines).hasSize(4);
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
+ ",unknown,,GET,auth,,/login?authentication_required,访问登录页,,页面访问,200"
+ ",43.228.157.244,Mozilla/5.0");
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(9))
+ ",unknown,,GET,auth,,/login,访问登录页,,页面访问,200,43.228.157.244,Mozilla/5.0");
assertThat(lines[3]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
+ ",unknown,,GET,auth,,/logout,访问登出页,,页面访问,200,127.0.0.1,Mozilla/5.0");
} }
@Test @Test
void shouldExportChangesColumnWhenRecordHasChanges() { void shouldExportChangesColumnWhenRecordHasChanges() {
var time = Instant.parse("2026-11-04T00:00:00Z"); 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"); "/apis/content.halo.run/v1alpha1/posts/abc", 200, "127.0.0.1", "UA");
log.getSpec().setChanges(List.of( log.getSpec().setChanges(List.of(
change(ChangeType.UPDATED, "spec.title", "旧标题", "新标题"), change(ChangeType.UPDATED, "spec.title", "旧标题", "新标题"),
@@ -126,7 +200,7 @@ class AuditExportEndpointTest {
var lines = body.split("\r\n"); var lines = body.split("\r\n");
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time) 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" + ",修改文章,修改 spec.title:旧标题 → 新标题;新增 spec.cover:c.png"
+ ",成功,200,127.0.0.1,UA"); + ",成功,200,127.0.0.1,UA");
} }
@@ -152,7 +226,7 @@ class AuditExportEndpointTest {
void shouldEscapeSpecialCharactersAndFormulaInjection() { void shouldEscapeSpecialCharactersAndFormulaInjection() {
stubSinglePage(List.of( 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, "posts", "=sum(A1)", "/apis/content.halo.run/v1alpha1/posts/x,y", 200,
"127.0.0.1", "@evil"))); "127.0.0.1", "@evil")));
@@ -160,20 +234,20 @@ class AuditExportEndpointTest {
var lines = body.split("\r\n"); var lines = body.split("\r\n");
assertThat(lines).hasSize(2); assertThat(lines).hasSize(2);
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-02T00:00:00Z")) 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"); + ",修改文章,,成功,200,127.0.0.1,'@evil");
} }
@Test @Test
void shouldTreatNullStatusCodeAsFailureAndEmptyFields() { void shouldTreatNullStatusCodeAsFailureAndEmptyFields() {
stubSinglePage(List.of( stubSinglePage(List.of(
auditLog("auditlog-1", Instant.parse("2026-11-03T00:00:00Z"), "admin", "PATCH", auditLog("auditlog-1", Instant.parse("2026-11-03T00:00:00Z"), "admin", null,
"themes", null, null, null, null, null))); "PATCH", "themes", null, null, null, null, null)));
var body = exportAndGetBody(EXPORT_URI); var body = exportAndGetBody(EXPORT_URI);
var lines = body.split("\r\n"); var lines = body.split("\r\n");
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-03T00:00:00Z")) assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-03T00:00:00Z"))
+ ",admin,PATCH,themes,,,修改主题,,失败,,,"); + ",admin,,PATCH,themes,,,修改主题,,失败,,,");
} }
@Test @Test
@@ -229,8 +303,8 @@ class AuditExportEndpointTest {
var page1 = fullBatch(1); var page1 = fullBatch(1);
var page2 = fullBatch(2); var page2 = fullBatch(2);
var page3 = List.of( var page3 = List.of(
auditLog("auditlog-401", Instant.parse("2026-11-01T00:00:00Z"), "admin", "POST", auditLog("auditlog-401", Instant.parse("2026-11-01T00:00:00Z"), "admin", null,
"users", "zhangsan", "/apis/v1alpha1/users", 200, "127.0.0.1", "UA")); "POST", "users", "zhangsan", "/apis/v1alpha1/users", 200, "127.0.0.1", "UA"));
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class))) when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
.thenReturn(Mono.just(new ListResult<>(1, AuditLogCsvExporter.EXPORT_BATCH_SIZE, .thenReturn(Mono.just(new ListResult<>(1, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
401, page1)), 401, page1)),
@@ -266,7 +340,7 @@ class AuditExportEndpointTest {
for (int i = 0; i < AuditLogCsvExporter.EXPORT_BATCH_SIZE; i++) { for (int i = 0; i < AuditLogCsvExporter.EXPORT_BATCH_SIZE; i++) {
items.add(auditLog("auditlog-" + i, items.add(auditLog("auditlog-" + i,
Instant.ofEpochSecond(firstTimestampEpochSecond * 1000 + 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")); "127.0.0.1", "UA"));
} }
return items; return items;
@@ -0,0 +1,331 @@
package run.halo.operationaudit.audit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpStatus;
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.BadCredentialsException;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.WebFilterChainProxy;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationFailureHandler;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import run.halo.operationaudit.alert.LoginFailureAlertService;
/**
* 真实 Spring Security 过滤链集成测试(P0 修复回归防线)。
*
* <p>组件隔离测试(单元测试)无法发现的问题:表单登录/登出过滤器命中请求后直接完成
* 302 响应、不再向下游传递。本测试按 Halo 真实组装方式(源码级验证
* {@code SecurityWebFiltersConfigurer})构建 {@link SecurityWebFilterChain}:
*
* <ul>
* <li>{@link AuthEndpointAuditWebFilter} 注册于 {@link SecurityWebFiltersOrder#FIRST}
* (对应插件 {@code BeforeSecurityWebFilter} 扩展点);</li>
* <li>表单登录在 FORM_LOGIN、登出在 LOGOUT(命中即终止响应,模拟 Halo 行为);</li>
* <li>认证上下文注入过滤器模拟 ReactorContextWebFilter 的上下文写入;</li>
* <li>{@link OperationAuditWebFilter} 注册于 {@link SecurityWebFiltersOrder#LAST}
* (对应插件 {@code AfterSecurityWebFilter} 扩展点)。</li>
* </ul>
*
* <p>核心断言:POST /login(成败)、POST /logout 在真实链上均产生审计记录并回调
* 登录失败告警;{@code /apis/**} 写操作仍由链尾过滤器记录且操作者来自认证上下文。
*
* <p>验证时序:真实链存在线程切换(Security 链内过滤器切换调度器),且 Reactor 的
* {@code doFinally} 回调在完成信号向下游传播之后执行——{@code verifyComplete()} 返回时
* 记录可能尚未落库。生产路径为 fire-and-forget(记录器自行订阅),故本测试统一以
* Mockito {@code timeout()} 等待回调完成后再断言,与生产行为一致。
*/
class AuditFilterChainIntegrationTest {
/** doFinally 回调为响应式异步执行,断言等待上限(毫秒)。 */
private static final long CALLBACK_TIMEOUT_MS = 5_000;
/** 「不记录」断言的等待时长(毫秒):确认透传请求在全链上始终没有触发记录。 */
private static final long PASS_THROUGH_WAIT_MS = 500;
private static final String LOGIN_FORM = "username=admin&password=right-password";
private AuditRecorder recorder;
private ChangeCaptureManager captureManager;
private HttpWriteMarker writeMarker;
private LoginFailureAlertService loginFailureAlertService;
private WebFilterChainProxy proxy;
/** 终止型外层 chain:模拟 Security 链之后的业务处理(正常 200 响应)。 */
private static final WebFilterChainStub OUTER_CHAIN = new WebFilterChainStub();
private static final class WebFilterChainStub implements WebFilterChain {
@Override
public Mono<Void> filter(ServerWebExchange exchange) {
exchange.getResponse().setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
@BeforeEach
void setUp() {
recorder = mock(AuditRecorder.class);
captureManager = mock(ChangeCaptureManager.class);
writeMarker = mock(HttpWriteMarker.class);
loginFailureAlertService = mock(LoginFailureAlertService.class);
proxy = buildChain(csrf -> csrf.disable());
}
/**
* 按 Halo 真实组装方式构建过滤链代理。csrfCustomizer 由测试决定 CSRF 配置
* (禁用,或启用并指定仓库——用于验证表单参数通道)。
*/
private WebFilterChainProxy buildChain(
org.springframework.security.config.Customizer<ServerHttpSecurity.CsrfSpec> csrfCustomizer) {
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
any(ChangeCapture.class)))
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
var authEndpointFilter = new AuthEndpointAuditWebFilter(recorder, writeMarker,
new LoginAttemptCapture(), loginFailureAlertService);
var apisFilter = new OperationAuditWebFilter(recorder, captureManager, writeMarker);
// 表单登录认证管理器:right-password 成功,其余凭据失败(模拟 Halo 真实成败分流)
ReactiveAuthenticationManager authenticationManager = authentication -> {
var credentials = String.valueOf(authentication.getCredentials());
if ("right-password".equals(credentials)) {
var authenticated = UsernamePasswordAuthenticationToken.authenticated(
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
List.of(() -> "ROLE_ADMIN"));
return Mono.just(authenticated);
}
return Mono.error(new BadCredentialsException("invalid credential"));
};
var http = ServerHttpSecurity.http();
http.securityMatcher(ServerWebExchangeMatchers.anyExchange());
http.csrf(csrfCustomizer);
http.authorizeExchange(exchanges -> exchanges.anyExchange().permitAll());
// 模拟 ReactorContextWebFilter:认证后的请求向下游写入 SecurityContext,
// 使链尾过滤器可解析操作者(Halo 真实链由 ReactorContextWebFilter 完成)
var authentication = UsernamePasswordAuthenticationToken.authenticated(
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
List.of(() -> "ROLE_ADMIN"));
WebFilter contextFilter = (exchange, chain) -> chain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
http.addFilterAt(contextFilter, SecurityWebFiltersOrder.AUTHENTICATION);
http.formLogin(login -> login
.authenticationManager(authenticationManager)
// 与 Halo 登录端点契约一致:表单登录成败均为 302 重定向
.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/uc"))
.authenticationFailureHandler(new RedirectServerAuthenticationFailureHandler(
"/login?error=invalid-credential&method=local")));
http.logout(logout -> logout
.logoutHandler((exchange, auth) -> Mono.empty())
.logoutSuccessHandler((webFilterExchange, auth) -> {
var response = webFilterExchange.getExchange().getResponse();
response.setStatusCode(HttpStatus.FOUND);
response.getHeaders().setLocation(URI.create("/login?logout"));
return response.setComplete();
}));
// P0 修复核心:认证端点捕获过滤器位于链首,先于表单登录/登出终止过滤器
http.addFilterAt(authEndpointFilter, SecurityWebFiltersOrder.FIRST);
http.addFilterAt(apisFilter, SecurityWebFiltersOrder.LAST);
SecurityWebFilterChain securityChain = http.build();
return new WebFilterChainProxy(securityChain);
}
private MockServerWebExchange loginExchange(String password, String username) {
var body = "username=" + username + "&password=" + password;
return MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
.body(body));
}
@Test
void shouldRecordFormLoginSuccessThroughRealChain() {
// P0 缺陷核心回归:POST /login 成功(表单登录过滤器直接 302 完成响应,
// 不向下游传递)仍必须产生审计记录
var exchange = loginExchange("right-password", "admin");
proxy.filter(exchange, OUTER_CHAIN).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(false));
// 告警回调先于记录(同一回调体内),记录已到位则告警必然已回调
verify(loginFailureAlertService, timeout(CALLBACK_TIMEOUT_MS))
.onLoginResult(any(RequestSnapshot.class), eq(true), eq("admin"));
}
@Test
void shouldRecordFormLoginFailureThroughRealChain() {
var exchange = loginExchange("wrong", "admin");
proxy.filter(exchange, OUTER_CHAIN).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(true));
verify(loginFailureAlertService, timeout(CALLBACK_TIMEOUT_MS))
.onLoginResult(any(RequestSnapshot.class), eq(false), eq("admin"));
}
@Test
void shouldRecordLogoutThroughRealChain() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/logout")
.build());
proxy.filter(exchange, OUTER_CHAIN).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
// 登出不是登录尝试:记录回调完成后告警仍零调用
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
}
@Test
void shouldNotRecordLoginPageVisitThroughRealChain() {
// 登录页的 GET 访问不是操作:打开登录页、被弹回登录页(?authentication_required)、
// 登录失败后的回显(?error=...)都只渲染页面,全链任何位置都不得落库——
// 否则列表里全是「未知用户 · 登录 · 200」,真正的登录成败被淹没
for (var path : List.of("/login", "/login?authentication_required",
"/login?error=invalid-credential&method=local")) {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.get(path)
.build());
proxy.filter(exchange, OUTER_CHAIN).block();
}
// 真实链的记录回调可能异步晚于 block() 返回:等待一段时间后仍为零调用才算数
verify(recorder, after(PASS_THROUGH_WAIT_MS).never())
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
}
@Test
void shouldNotRecordLogoutConfirmPageThroughRealChain() {
// 登出确认页(GET /logout)同样只是页面访问
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.get("/logout")
.build());
proxy.filter(exchange, OUTER_CHAIN).block();
verify(recorder, after(PASS_THROUGH_WAIT_MS).never())
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
}
@Test
void shouldRecordApisWriteByLastPositionFilterWithAuthenticatedOperator() {
// /apis/** 捕获保持 AfterSecurityWebFilter(链尾)注册:操作者来自认证上下文
// (链尾过滤器经操作者独立订阅解析用户名,同样以 timeout 等待)
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/apis/api.content.halo.run/v1alpha1/posts")
.build());
proxy.filter(exchange, OUTER_CHAIN).block();
ArgumentCaptor<RequestSnapshot> captor = ArgumentCaptor.forClass(RequestSnapshot.class);
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(captor.capture(),
any(ChangeCapture.class), eq(200), eq("admin"), isNull(), eq(false));
assertThat(captor.getValue().getPath())
.isEqualTo("/apis/api.content.halo.run/v1alpha1/posts");
}
@Test
void mustNotBreakCsrfFormParamChannelForLoginRequests() {
// 真实环境回归实证(登录保护):认证端点过滤器若缓存原始请求体并装饰 exchange,
// 下游 CSRF 过滤器经 getFormData() 代理到原始 exchange、解析已被消费的 body,
// 读不到 _csrf 表单参数而拒绝全部登录(403 Access Denied,登录页整体失效)。
// 修复后的提取走 getFormData() 共享缓存,本测试以启用 CSRF + 表单参数令牌的
// 真实链锁死该通道:CSRF 必须放行、表单登录必须继续执行。
var csrfToken = new org.springframework.security.web.server.csrf.DefaultCsrfToken(
"X-CSRF-TOKEN", "_csrf", "test-csrf-token");
var csrfProxy = buildChain(csrf -> csrf
// SS 7.1 默认 handler 为 XOR 解码(Halo 沿用默认,表单值即编码后的令牌);
// 本测试聚焦表单参数通道本身,改用原始值比较的 handler 以隔离编码因素
.csrfTokenRequestHandler(
new org.springframework.security.web.server.csrf.ServerCsrfTokenRequestAttributeHandler())
.csrfTokenRepository(new org.springframework.security.web.server.csrf.ServerCsrfTokenRepository() {
@Override
public Mono<org.springframework.security.web.server.csrf.CsrfToken> generateToken(
ServerWebExchange exchange) {
return Mono.just(csrfToken);
}
@Override
public Mono<Void> saveToken(ServerWebExchange exchange,
org.springframework.security.web.server.csrf.CsrfToken token) {
return Mono.empty();
}
@Override
public Mono<org.springframework.security.web.server.csrf.CsrfToken> loadToken(
ServerWebExchange exchange) {
return Mono.just(csrfToken);
}
}));
var body = "username=admin&password=right-password&_csrf=test-csrf-token";
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
.body(body));
csrfProxy.filter(exchange, OUTER_CHAIN).block();
// CSRF 参数通道可用(未 403)且登录已执行:成功重定向
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
verify(recorder, timeout(CALLBACK_TIMEOUT_MS)).record(any(RequestSnapshot.class),
isNull(), eq(302), eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(false));
}
@Test
void shouldRecordLogoutExactlyOnceThroughRealChain() {
// 认证端点移交链首过滤器后,链尾过滤器对认证端点零记录(分治不重叠):
// POST /logout 终止于 LOGOUT 过滤器,全链仅产生一条记录
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/logout")
.build());
proxy.filter(exchange, OUTER_CHAIN).block();
verify(recorder, timeout(CALLBACK_TIMEOUT_MS).times(1))
.record(any(RequestSnapshot.class), any(), any(), any(), any(), anyBoolean());
}
}
@@ -106,10 +106,72 @@ class AuditQueryEndpointTest {
var captor = ArgumentCaptor.forClass(ListOptions.class); var captor = ArgumentCaptor.forClass(ListOptions.class);
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class)); verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
var condition = captor.getValue().toCondition().toString(); var condition = captor.getValue().toCondition().toString();
// failure = statusCode >= 400(无上界) // failure = 登录失败标注(表单登录失败的 HTTP 状态码是 302,仅凭状态码识别不出)
// 或 4xx/5xx;页面访问记录(非 POST 的 /login、/logout)不计成败,予以排除
assertThat(condition) assertThat(condition)
.contains("spec.statusCode") .contains("spec.statusCode")
.contains("400"); .contains("400")
.contains("spec.action")
.contains("login-failure")
.contains("spec.method")
.contains("/login")
.contains("/logout");
}
@Test
void shouldApplySuccessResultFilterExcludingLoginFailure() {
webClient.get()
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?result=success")
.exchange()
.expectStatus().isOk();
var captor = ArgumentCaptor.forClass(ListOptions.class);
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
var condition = captor.getValue().toCondition().toString();
// success = 2xx/3xx 且排除登录失败标注(其状态码可能落在 2xx/3xx 区间)
// 与页面访问记录(升级前落库的 GET /login、GET /logout,HTTP 200)
assertThat(condition)
.contains("spec.statusCode")
.contains("spec.action")
.contains("login-failure")
.contains("spec.method")
.contains("/login")
.contains("/logout");
}
@Test
void shouldExcludePageVisitsWhenFilteringByLoginOrLogoutAction() {
// 升级前落库的页面访问记录带着 login/logout 标注,但展示为「访问登录页/登出页」:
// 按语义动作筛登录/登出操作时不混入
webClient.get()
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
+ "?fieldSelector=spec.action=login")
.exchange()
.expectStatus().isOk();
var captor = ArgumentCaptor.forClass(ListOptions.class);
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
var condition = captor.getValue().toCondition().toString();
assertThat(condition)
.contains("spec.action")
.contains("login")
.contains("spec.method")
.contains("/login");
}
@Test
void shouldKeepPlainEqualityForOtherSemanticActions() {
// 其余语义动作的等值筛选不带页面访问排除条件
webClient.get()
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
+ "?fieldSelector=spec.action=login-failure")
.exchange()
.expectStatus().isOk();
var captor = ArgumentCaptor.forClass(ListOptions.class);
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
var condition = captor.getValue().toCondition().toString();
assertThat(condition).doesNotContain("spec.method");
} }
@Test @Test
@@ -55,7 +55,7 @@ class AuditRecorderTest {
.header("User-Agent", "UA-1") .header("User-Agent", "UA-1")
.build()); .build());
recorder.record(snapshot, new ChangeCapture(), 204, "admin"); recorder.record(snapshot, new ChangeCapture(), 204, "admin", null, false);
var captor = ArgumentCaptor.forClass(AuditLog.class); var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture()); verify(client).create(captor.capture());
@@ -78,22 +78,37 @@ class AuditRecorderTest {
@Test @Test
void shouldUseUnknownUsernameWhenOperatorMissing() { void shouldUseUnknownUsernameWhenOperatorMissing() {
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null); // XHR/JSON 登录失败(401):过滤器判定 loginFailed=true,动作标注登录失败
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null, true);
var captor = ArgumentCaptor.forClass(AuditLog.class); var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture()); verify(client).create(captor.capture());
assertThat(captor.getValue().getSpec().getUsername()) assertThat(captor.getValue().getSpec().getUsername())
.isEqualTo(AuditLogSpec.UNKNOWN_USERNAME); .isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth"); assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth");
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login"); assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login-failure");
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401); assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
} }
@Test
void shouldRecordAttemptedUsernameForLoginAttempt() {
// 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401,
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan", true);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
var spec = captor.getValue().getSpec();
assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
assertThat(spec.getAttemptedUsername()).isEqualTo("zhangsan");
assertThat(spec.getAction()).isEqualTo("login-failure");
}
@Test @Test
void shouldAnnotateSubActionSemanticAction() { void shouldAnnotateSubActionSemanticAction() {
recorder.record(RequestSnapshot.of(MockServerHttpRequest recorder.record(RequestSnapshot.of(MockServerHttpRequest
.put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish") .put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish")
.build()), new ChangeCapture(), 200, "admin"); .build()), new ChangeCapture(), 200, "admin", null, false);
var captor = ArgumentCaptor.forClass(AuditLog.class); var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture()); verify(client).create(captor.capture());
@@ -101,13 +116,53 @@ class AuditRecorderTest {
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("posts"); assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("posts");
} }
// ===== 登录失败标注(LoginOutcome + 语义动作 login-failure) =====
@Test
void shouldAnnotateLoginFailureActionOnFailedLoginAttempt() {
// 表单登录失败(302 重定向回跳登录页):过滤器传入 loginFailed=true,
// 语义动作标注 login-failure;状态码仍如实记录 302
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
AuditLogSpec.UNKNOWN_USERNAME, null, true);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
var spec = captor.getValue().getSpec();
assertThat(spec.getAction()).isEqualTo("login-failure");
assertThat(spec.getStatusCode()).isEqualTo(302);
}
@Test
void shouldAnnotateLogoutWithoutFailureMark() {
// 登出(POST /logout)是认证操作但不是登录尝试:语义动作 logout,不标注登录失败
recorder.record(snapshotOf("/logout"), new ChangeCapture(), 302,
AuditLogSpec.UNKNOWN_USERNAME, null, false);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
var spec = captor.getValue().getSpec();
assertThat(spec.getAction()).isEqualTo("logout");
assertThat(spec.getStatusCode()).isEqualTo(302);
}
@Test
void shouldKeepLoginActionOnSuccessfulLogin() {
// 表单登录成功(302 → /uc):语义动作仍为 login,不标注登录失败
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
AuditLogSpec.UNKNOWN_USERNAME, null, false);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login");
}
@Test @Test
void shouldSkipRecordingWhenAuditDisabled() { void shouldSkipRecordingWhenAuditDisabled() {
when(settingProvider.get()) when(settingProvider.get())
.thenReturn(Mono.just(new AuditSettings(false, 30, null, null))); .thenReturn(Mono.just(new AuditSettings(false, 30, null, null)));
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(), recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
200, "admin"); 200, "admin", null, false);
verify(client, never()).create(any(AuditLog.class)); verify(client, never()).create(any(AuditLog.class));
} }
@@ -117,7 +172,7 @@ class AuditRecorderTest {
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom"))); when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
new ChangeCapture(), 200, "admin")).doesNotThrowAnyException(); new ChangeCapture(), 200, "admin", null, false)).doesNotThrowAnyException();
// 设置读取失败属于降级路径:按默认配置(开启)继续记录 // 设置读取失败属于降级路径:按默认配置(开启)继续记录
verify(client).create(any(AuditLog.class)); verify(client).create(any(AuditLog.class));
@@ -129,7 +184,7 @@ class AuditRecorderTest {
new IllegalStateException("storage unavailable"))); new IllegalStateException("storage unavailable")));
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
new ChangeCapture(), 500, "admin")).doesNotThrowAnyException(); new ChangeCapture(), 500, "admin", null, false)).doesNotThrowAnyException();
} }
@Test @Test
@@ -147,7 +202,7 @@ class AuditRecorderTest {
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678)) .remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.build()); .build());
recorder.record(snapshot, capture, 200, "admin"); recorder.record(snapshot, capture, 200, "admin", null, false);
var captor = ArgumentCaptor.forClass(AuditLog.class); var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture()); verify(client).create(captor.capture());
@@ -172,7 +227,7 @@ class AuditRecorderTest {
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678)) .remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.build()); .build());
recorder.record(snapshot, capture, 403, "admin"); recorder.record(snapshot, capture, 403, "admin", null, false);
var captor = ArgumentCaptor.forClass(AuditLog.class); var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture()); verify(client).create(captor.capture());
@@ -183,7 +238,7 @@ class AuditRecorderTest {
@Test @Test
void shouldNotRecordChangesWhenContextMissing() { void shouldNotRecordChangesWhenContextMissing() {
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"), recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
new ChangeCapture(), 200, "admin"); new ChangeCapture(), 200, "admin", null, false);
var captor = ArgumentCaptor.forClass(AuditLog.class); var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture()); verify(client).create(captor.capture());
@@ -0,0 +1,87 @@
package run.halo.operationaudit.audit;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* 结果语义测试(AuditResult):结果筛选与 CSV 导出共用的成败判定。
* 登录失败不能只看状态码(表单登录失败的 HTTP 状态码与成功相同,均为 302);
* 认证端点的页面访问(升级前落库的 GET 记录)不是操作,不计成败。
*/
class AuditResultTest {
private static AuditLogSpec spec(String method, String path, Integer statusCode,
String action) {
var spec = new AuditLogSpec();
spec.setMethod(method);
spec.setResourceType("auth");
spec.setPath(path);
spec.setStatusCode(statusCode);
spec.setAction(action);
return spec;
}
@Test
void loginFailureIsFailureRegardlessOfStatusCode() {
// 表单登录失败:302(与成功相同的状态码),只能靠落库标注识别
assertThat(AuditResult.of(spec("POST", "/login", 302, "login-failure")))
.isEqualTo(AuditResult.FAILURE);
// XHR 登录失败、CSRF 拦截
assertThat(AuditResult.of(spec("POST", "/login", 401, "login-failure")))
.isEqualTo(AuditResult.FAILURE);
assertThat(AuditResult.of(spec("POST", "/login", 403, "login-failure")))
.isEqualTo(AuditResult.FAILURE);
// 升级前落库的失败回显(GET /login?error=...,HTTP 200):带标注或由路径推导
assertThat(AuditResult.of(spec("GET", "/login?error=invalid-credential", 200,
"login-failure"))).isEqualTo(AuditResult.FAILURE);
assertThat(AuditResult.of(spec("GET", "/login?error=invalid-credential", 200, null)))
.isEqualTo(AuditResult.FAILURE);
}
@Test
void successfulLoginIsSuccess() {
assertThat(AuditResult.of(spec("POST", "/login", 302, "login")))
.isEqualTo(AuditResult.SUCCESS);
assertThat(AuditResult.of(spec("POST", "/login", 200, "login")))
.isEqualTo(AuditResult.SUCCESS);
}
@Test
void authPageVisitsAreNeitherSuccessNorFailure() {
// 升级前落库的页面访问记录:当时带着 login/logout 标注、HTTP 200——
// 原先显示为绿色「登录 200」,看起来像未知用户登录成功
assertThat(AuditResult.of(spec("GET", "/login", 200, "login")))
.isEqualTo(AuditResult.PAGE_VISIT);
assertThat(AuditResult.of(spec("GET", "/login?authentication_required", 200, "login")))
.isEqualTo(AuditResult.PAGE_VISIT);
assertThat(AuditResult.of(spec("GET", "/logout", 200, "logout")))
.isEqualTo(AuditResult.PAGE_VISIT);
// 无标注的历史记录、页面自身出错(5xx)同样不计成败
assertThat(AuditResult.of(spec("GET", "/login", 200, null)))
.isEqualTo(AuditResult.PAGE_VISIT);
assertThat(AuditResult.of(spec("GET", "/login", 500, "login")))
.isEqualTo(AuditResult.PAGE_VISIT);
}
@Test
void ordinaryRecordsFollowStatusCode() {
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 201, "create")))
.isEqualTo(AuditResult.SUCCESS);
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 302, "create")))
.isEqualTo(AuditResult.SUCCESS);
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 403, "create")))
.isEqualTo(AuditResult.FAILURE);
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", 500, "create")))
.isEqualTo(AuditResult.FAILURE);
assertThat(AuditResult.of(spec("POST", "/apis/x/v1/users", null, "create")))
.isEqualTo(AuditResult.FAILURE);
}
@Test
void labelsAreUsedForCsvResultColumn() {
assertThat(AuditResult.SUCCESS.label()).isEqualTo("成功");
assertThat(AuditResult.FAILURE.label()).isEqualTo("失败");
assertThat(AuditResult.PAGE_VISIT.label()).isEqualTo("页面访问");
}
}
@@ -0,0 +1,238 @@
package run.halo.operationaudit.audit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.operationaudit.alert.LoginFailureAlertService;
/**
* 认证端点捕获过滤器行为测试(P0 修复):POST /login、POST /logout 必须产生审计记录
* (真实环境中表单登录/登出过滤器在链尾过滤器之前直接完成响应,因此由本过滤器在
* Security 链之前承接)。登录/登出页面的 GET 访问不是操作,一律透传不记录。
* 操作者统一为未知用户,登录尝试账号由请求体白名单提取;登录失败告警回调仅发生在
* POST /login;非认证端点请求一律透传、零副作用。
*/
class AuthEndpointAuditWebFilterTest {
private AuditRecorder recorder;
private HttpWriteMarker writeMarker;
private LoginFailureAlertService loginFailureAlertService;
private AuthEndpointAuditWebFilter filter;
/** 终止型 chain:模拟正常响应(200)后完成。 */
private static final WebFilterChainStub CHAIN = new WebFilterChainStub();
private static final class WebFilterChainStub implements WebFilterChain {
@Override
public Mono<Void> filter(ServerWebExchange exchange) {
exchange.getResponse().setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
/** 终止型 chain:模拟 302 重定向响应(Halo 表单登录/登出契约)后完成。 */
private static final class RedirectWebFilterChainStub implements WebFilterChain {
private final URI location;
private RedirectWebFilterChainStub(URI location) {
this.location = location;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange) {
exchange.getResponse().setStatusCode(HttpStatus.FOUND);
exchange.getResponse().getHeaders().setLocation(location);
return Mono.empty();
}
}
@BeforeEach
void setUp() {
recorder = mock(AuditRecorder.class);
writeMarker = mock(HttpWriteMarker.class);
loginFailureAlertService = mock(LoginFailureAlertService.class);
// 登录尝试用户名提取为真实实现:过滤器行为测试同时覆盖提取透传
filter = new AuthEndpointAuditWebFilter(recorder, writeMarker,
new LoginAttemptCapture(), loginFailureAlertService);
}
@Test
void shouldRecordFormLoginSuccessWithAttemptedUsername() {
// P0 缺陷回归测试核心断言:POST /login 成功(302 → /uc)必须产生审计记录
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,
new RedirectWebFilterChainStub(URI.create("/uc")))).verifyComplete();
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
verify(recorder).record(captor.capture(), isNull(), eq(302),
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"), eq(false));
assertThat(captor.getValue().getPath()).isEqualTo("/login");
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(true),
eq("admin"));
}
@Test
void shouldRecordFormLoginFailureAndAlert() {
// 表单登录失败:302 → /login?error=invalid-credential&method=local,
// 与成功重定向同状态码,必须按 Location 目标判定(LoginOutcome)
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentLength("username=bob&password=wrong".getBytes(StandardCharsets.UTF_8).length)
.body("username=bob&password=wrong"));
StepVerifier.create(filter.filter(exchange, new RedirectWebFilterChainStub(
URI.create("/login?error=invalid-credential&method=local")))).verifyComplete();
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("bob"), eq(true));
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false),
eq("bob"));
}
@Test
void shouldRecordLogoutWithoutAlert() {
// 登出请求必须产生记录(P0 缺陷回归),但不是登录尝试、不触发告警回调
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/logout")
.build());
StepVerifier.create(filter.filter(exchange,
new RedirectWebFilterChainStub(URI.create("/login?logout")))).verifyComplete();
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
}
@Test
void shouldPassThroughLoginPageVisitsWithoutRecording() {
// 登录页的 GET 访问不是登录操作:打开登录页、匿名访问被弹回登录页
// (/login?authentication_required)、登录失败后的回显(/login?error=...)
// 都只渲染页面(HTTP 200)。原先一律落库为「未知用户 · 登录 · 200」,在列表里
// 与登录成功无法区分(现场反馈:全是成功、登录失败也显示成功)——现在原样透传
for (var path : List.of("/login", "/login?authentication_required",
"/login?error=invalid-credential&method=local", "/login?logout")) {
var exchange = MockServerWebExchange.from(MockServerHttpRequest.get(path).build());
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
}
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
verify(writeMarker, never()).onRequestStart(any());
verify(writeMarker, never()).onRequestComplete(any());
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
}
@Test
void shouldPassThroughLogoutConfirmPageWithoutRecording() {
// 登出确认页(GET /logout)同样只是页面访问,不是登出操作
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.get("/logout")
.build());
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
verify(writeMarker, never()).onRequestStart(any());
}
@Test
void shouldRecordLoginFailureWhenRedirectedBackToLoginWithoutErrorParam() {
// 302 跳回登录页且不带 error 参数:不可能是登录成功(成功只会去 /uc、已保存的
// 原请求或 2FA 页),同样判失败——只有响应明确确认才算成功
var exchange = loginExchange("bob", "wrong");
StepVerifier.create(filter.filter(exchange, new RedirectWebFilterChainStub(
URI.create("/login")))).verifyComplete();
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("bob"), eq(true));
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(false),
eq("bob"));
}
@Test
void shouldRecordLoginFailureWhenRedirectHasNoLocation() {
// 3xx 但缺失 Location:响应异常,无法确认登录成功,不记成功
var exchange = loginExchange("bob", "wrong");
WebFilterChain foundWithoutLocation = ex -> {
ex.getResponse().setStatusCode(HttpStatus.FOUND);
return Mono.empty();
};
StepVerifier.create(filter.filter(exchange, foundWithoutLocation)).verifyComplete();
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(302),
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("bob"), eq(true));
}
private static MockServerWebExchange loginExchange(String username, String password) {
var body = "username=" + username + "&password=" + password;
return MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
.body(body));
}
@Test
void shouldMarkWriteLifecycleForAuthEndpoints() {
// 与原捕获分支行为对齐:认证端点请求登记 HTTP 写标记(内部变更归属)
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.build());
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(writeMarker).onRequestStart(any());
verify(writeMarker).onRequestComplete(any());
}
@Test
void shouldPassThroughNonAuthEndpointsWithoutSideEffects() {
// 非 /login、/logout 一律透传:不记录、不登记标记、不回调告警
var apis = MockServerWebExchange.from(MockServerHttpRequest
.post("/apis/api.content.halo.run/v1alpha1/posts")
.build());
StepVerifier.create(filter.filter(apis, CHAIN)).verifyComplete();
var other = MockServerWebExchange.from(MockServerHttpRequest
.get("/console/")
.build());
StepVerifier.create(filter.filter(other, CHAIN)).verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
verify(writeMarker, never()).onRequestStart(any());
verify(writeMarker, never()).onRequestComplete(any());
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
}
}
@@ -28,10 +28,12 @@ class CaptureRuleTest {
} }
@Test @Test
void shouldCaptureAuthEndpointsRegardlessOfMethod() { void shouldNotCaptureAuthEndpointsInApisRule() {
assertThat(shouldCapture("/login", "POST")).isTrue(); // 认证操作由 AuthEndpointAuditWebFilter 独立捕获(isAuthOperation),
assertThat(shouldCapture("/login", "GET")).isTrue(); // 通用规则不再包含,两个过滤器按规则分治、互不重叠
assertThat(shouldCapture("/logout", "POST")).isTrue(); assertThat(shouldCapture("/login", "POST")).isFalse();
assertThat(shouldCapture("/login", "GET")).isFalse();
assertThat(shouldCapture("/logout", "POST")).isFalse();
} }
@Test @Test
@@ -69,4 +71,21 @@ class CaptureRuleTest {
assertThat(CaptureRule.isLoginAttempt(null, "POST")).isFalse(); assertThat(CaptureRule.isLoginAttempt(null, "POST")).isFalse();
assertThat(CaptureRule.isLoginAttempt("/login", null)).isFalse(); assertThat(CaptureRule.isLoginAttempt("/login", null)).isFalse();
} }
@Test
void shouldTreatOnlyPostAsAuthOperation() {
// 认证操作 = POST /login(登录尝试)+ POST /logout(登出)
assertThat(CaptureRule.isAuthOperation("/login", "POST")).isTrue();
assertThat(CaptureRule.isAuthOperation("/logout", "POST")).isTrue();
// 登录/登出页面的 GET 访问不是操作:打开登录页、被弹回登录页、失败回显、登出确认页
assertThat(CaptureRule.isAuthOperation("/login", "GET")).isFalse();
assertThat(CaptureRule.isAuthOperation("/logout", "GET")).isFalse();
// 其余方法与路径一律不算
assertThat(CaptureRule.isAuthOperation("/login", "HEAD")).isFalse();
assertThat(CaptureRule.isAuthOperation("/login", "PUT")).isFalse();
assertThat(CaptureRule.isAuthOperation("/loginx", "POST")).isFalse();
assertThat(CaptureRule.isAuthOperation("/console/login", "POST")).isFalse();
assertThat(CaptureRule.isAuthOperation(null, "POST")).isFalse();
assertThat(CaptureRule.isAuthOperation("/login", null)).isFalse();
}
} }
@@ -0,0 +1,268 @@
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 java.util.List;
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.core.publisher.Mono;
import reactor.test.StepVerifier;
/**
* 登录尝试用户名提取测试(功能评审 P0-1):表单经 {@code getFormData()} 提取
* (与下游 CSRF/登录转换器共享缓存解析结果,不消费原始 body——真实环境回归实证:
* 缓存原始 body 会让下游 CSRF 读不到 _csrf 参数而拒绝登录)、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;
}
// ===== 表单提取(经 getFormData 共享缓存,不消费原始 body) =====
@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 shouldNotTouchRawBodyForFormRequests() {
// 表单形态绝不缓存原始 body / 装饰 exchange:prepare 后 exchange 原样透传,
// 下游(CSRF 过滤器、表单登录转换器)经同一份 getFormData 缓存读取表单
var exchange = formExchange("username=admin&password=secret");
var attempt = new LoginAttempt();
var prepared = capture.prepare(exchange, attempt).block();
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
assertThat(prepared).isSameAs(exchange);
// 共享缓存可重复订阅:模拟下游 CSRF 过滤器与登录转换器先后读取
var first = exchange.getFormData().block();
var second = exchange.getFormData().block();
assertThat(first).isSameAs(second);
assertThat(first.getFirst("username")).isEqualTo("admin");
assertThat(first.getFirst("password")).isEqualTo("secret");
}
@Test
void shouldExtractFromChunkedFormBody() {
// 分块传输(无 Content-Length):getFormData 为标准解析路径,正常提取
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();
assertThat(prepared).isSameAs(exchange);
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
}
@Test
void shouldSkipOversizedUsernameValue() {
// 超长用户名视为扫描载荷:不提取(保证记录与告警负载卫生)
var longName = "a".repeat(LoginAttemptCapture.MAX_USERNAME_LENGTH + 1);
var attempt = prepare(formExchange("username=" + longName + "&password=x"));
assertThat(attempt.getAttemptedUsername()).isNull();
}
@Test
void shouldPassthroughEmptyFormBody() {
// 空表单体:getFormData 完成为空,defaultIfEmpty 兜底透传(prepare 永不为空)
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();
}
// ===== JSON 体提取(缓存原始 body,装饰后可重复读) =====
@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 shouldKeepJsonBodyReadableDownstream() {
var body = "{\"username\":\"admin\",\"password\":\"secret\"}";
var exchange = jsonExchange(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 shouldPassthroughOversizedJsonBody() {
var oversized = "{\"username\":\"" + "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES)
+ "\"}";
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost/login")
.contentType(MediaType.APPLICATION_JSON)
.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 shouldPassthroughEmptyJsonBody() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost/login")
.contentType(MediaType.APPLICATION_JSON));
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.usernameOfFormValues(List.of("first", "second")))
.isEqualTo("second");
}
@Test
void shouldReturnNullForMissingOrBlankFormValues() {
assertThat(LoginAttemptCapture.usernameOfFormValues(null)).isNull();
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of())).isNull();
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of(" "))).isNull();
}
}
@@ -0,0 +1,103 @@
package run.halo.operationaudit.audit;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import org.junit.jupiter.api.Test;
/**
* 登录结果判定测试(LoginOutcome):Halo 2.26 登录端点表单提交的成功与失败均为
* 302 重定向(成功 → /uc、2FA 页;失败 → /login?error=...&method=...),仅 XHR/JSON
* 请求以 200/401 区分成败,成败判定必须结合重定向目标。
*
* <p>判定原则:只有响应明确确认登录完成才算成功,其余一律按失败记录——审计里把
* 失败登录记成成功,远比把异常响应记成失败更糟。
*/
class LoginOutcomeTest {
// ===== POST /login:状态码 + 重定向目标 =====
@Test
void xhrSuccessIsNotFailure() {
// XHR/JSON 登录成功:200 + 主体 JSON
assertThat(LoginOutcome.isFailure(200, null)).isFalse();
assertThat(LoginOutcome.isFailure(204, null)).isFalse();
}
@Test
void xhrFailureIsFailure() {
// XHR/JSON 登录失败:401 + JSON 错误体
assertThat(LoginOutcome.isFailure(401, null)).isTrue();
}
@Test
void formSuccessRedirectIsNotFailure() {
// 表单登录成功:302 → /uc(无 error 参数)
assertThat(LoginOutcome.isFailure(302, URI.create("/uc"))).isFalse();
// 两步验证:302 → /challenges/two-factor/totp
assertThat(LoginOutcome.isFailure(302,
URI.create("/challenges/two-factor/totp"))).isFalse();
// 登录前被弹回的原请求:302 → 已保存的受保护页面
assertThat(LoginOutcome.isFailure(302, URI.create("/console/posts"))).isFalse();
assertThat(LoginOutcome.isFailure(302,
URI.create("http://blog.guichumo.com/console/posts?page=1"))).isFalse();
}
@Test
void formFailureRedirectWithErrorParamIsFailure() {
// 表单登录失败:302 → /login?error=invalid-credential&method=local
// (Halo 2.26.1 LoginFailureHandler 的四种失败重定向:invalid-credential /
// account-disabled / rate-limit-exceeded / 无值 error)
assertThat(LoginOutcome.isFailure(302,
URI.create("/login?error=invalid-credential&method=local"))).isTrue();
assertThat(LoginOutcome.isFailure(302,
URI.create("/login?error=account-disabled&method=local"))).isTrue();
assertThat(LoginOutcome.isFailure(302,
URI.create("/login?error=rate-limit-exceeded&method=local"))).isTrue();
assertThat(LoginOutcome.isFailure(302, URI.create("/login?error&method=local"))).isTrue();
assertThat(LoginOutcome.isFailure(302,
URI.create("http://blog.guichumo.com/login?error=invalid-credential"))).isTrue();
}
@Test
void redirectBackToLoginPageWithoutErrorParamIsFailure() {
// 跳回登录页必然是失败:成功只会去 /uc、已保存的原请求或 2FA 页。
// 不依赖 error 参数——宿主或第三方登录扩展换了失败重定向格式也不会把失败记成成功
assertThat(LoginOutcome.isFailure(302, URI.create("/login"))).isTrue();
assertThat(LoginOutcome.isFailure(302, URI.create("/login?authentication_required")))
.isTrue();
assertThat(LoginOutcome.isFailure(307, URI.create("/login?logout"))).isTrue();
}
@Test
void redirectWithoutLocationIsFailure() {
// 3xx 但缺失 Location:响应异常,无法确认登录成功,不记成功
assertThat(LoginOutcome.isFailure(302, null)).isTrue();
}
@Test
void missingOrZeroStatusIsFailure() {
// 状态码缺失(响应未写出)按失败处理,宁可多告警不漏报
assertThat(LoginOutcome.isFailure(null, null)).isTrue();
assertThat(LoginOutcome.isFailure(0, null)).isTrue();
}
@Test
void clientAndServerErrorsAreFailure() {
// CSRF 拦截(403)、服务端异常(500)同为失败
assertThat(LoginOutcome.isFailure(403, URI.create("/login"))).isTrue();
assertThat(LoginOutcome.isFailure(500, null)).isTrue();
}
@Test
void errorParamNameMustMatchExactly() {
// 含 error 字样的其他参数(如 errors=1)不算失败标记
assertThat(LoginOutcome.isFailure(302, URI.create("/uc?errors=1"))).isFalse();
}
@Test
void loginPagePathMustMatchExactly() {
// 仅路径恰为 /login 才算跳回登录页;/login-xxx 等前缀相同的路径不算
assertThat(LoginOutcome.isFailure(302, URI.create("/login-callback"))).isFalse();
}
}
@@ -2,9 +2,12 @@ package run.halo.operationaudit.audit;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@@ -20,20 +23,21 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; import reactor.test.StepVerifier;
import run.halo.operationaudit.alert.LoginFailureAlertService;
/** /**
* 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。 * {@code /apis/**} 捕获过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。 * 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。 * 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
* 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(2xx 成功/其余失败)。 *
* <p>认证端点({@code /login}、{@code /logout})不在本过滤器职责内(P0 修复:它们由
* {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,此处透传不记录),
* 其行为见 {@link AuthEndpointAuditWebFilterTest} 与过滤链集成测试。
*/ */
class OperationAuditWebFilterTest { class OperationAuditWebFilterTest {
private AuditRecorder recorder; private AuditRecorder recorder;
private ChangeCaptureManager captureManager; private ChangeCaptureManager captureManager;
private HttpWriteMarker writeMarker; private HttpWriteMarker writeMarker;
private LoginFailureAlertService loginFailureAlertService;
private OperationAuditWebFilter filter; private OperationAuditWebFilter filter;
/** 终止型 chain:模拟正常响应(200)后完成。 */ /** 终止型 chain:模拟正常响应(200)后完成。 */
@@ -48,33 +52,15 @@ class OperationAuditWebFilterTest {
} }
} }
/** 终止型 chain:模拟异常响应(指定状态码)后完成。 */
private static final class FailingWebFilterChainStub implements
org.springframework.web.server.WebFilterChain {
private final org.springframework.http.HttpStatus status;
private FailingWebFilterChainStub(org.springframework.http.HttpStatus status) {
this.status = status;
}
@Override
public Mono<Void> filter(org.springframework.web.server.ServerWebExchange exchange) {
exchange.getResponse().setStatusCode(status);
return Mono.empty();
}
}
@BeforeEach @BeforeEach
void setUp() { void setUp() {
recorder = mock(AuditRecorder.class); recorder = mock(AuditRecorder.class);
captureManager = mock(ChangeCaptureManager.class); captureManager = mock(ChangeCaptureManager.class);
writeMarker = mock(HttpWriteMarker.class); writeMarker = mock(HttpWriteMarker.class);
loginFailureAlertService = mock(LoginFailureAlertService.class);
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class), when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
any(ChangeCapture.class))) any(ChangeCapture.class)))
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0))); .thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker, filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker);
loginFailureAlertService);
} }
@Test @Test
@@ -92,7 +78,7 @@ class OperationAuditWebFilterTest {
.verifyComplete(); .verifyComplete();
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200), verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
eq("admin")); eq("admin"), isNull(), eq(false));
} }
@Test @Test
@@ -103,20 +89,27 @@ class OperationAuditWebFilterTest {
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any()); verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
} }
@Test @Test
void shouldRecordLoginFailureAsUnknownUser() { void shouldPassThroughAuthEndpointsWithoutRecording() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest // P0 修复后认证端点由 AuthEndpointAuditWebFilter 在 Security 链之前捕获,
// 本过滤器不再记录;写方法请求(POST /login、POST /logout)仍按统一语义
// 登记内部变更归属标记(真实链上 POST 请求到不了链尾,GET 由透传处理)
var login = MockServerWebExchange.from(MockServerHttpRequest
.post("/login") .post("/login")
.build()); .build());
StepVerifier.create(filter.filter(login, CHAIN)).verifyComplete();
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); var logout = MockServerWebExchange.from(MockServerHttpRequest
.post("/logout")
.build());
StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete();
// 匿名访问 /login:无 SecurityContext → 操作者为“未知用户”,登录端点仍记录 verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200), verify(writeMarker, times(2)).onRequestStart(any());
eq(AuditLogSpec.UNKNOWN_USERNAME)); verify(writeMarker, times(2)).onRequestComplete(any());
} }
@Test @Test
@@ -128,7 +121,7 @@ class OperationAuditWebFilterTest {
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete(); StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any()); verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
} }
@Test @Test
@@ -145,27 +138,7 @@ class OperationAuditWebFilterTest {
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous))) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
.verifyComplete(); .verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any()); verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
}
@Test
void shouldCaptureLogoutAsAuth() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/logout")
.build());
var authentication = UsernamePasswordAuthenticationToken.authenticated(
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
List.of(() -> "ROLE_ADMIN"));
StepVerifier.create(
filter.filter(exchange, CHAIN)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
.verifyComplete();
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"));
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
.isEqualTo("auth");
} }
@Test @Test
@@ -195,7 +168,7 @@ class OperationAuditWebFilterTest {
// 请求期创建的同一个 capture 实例被透传给记录阶段 // 请求期创建的同一个 capture 实例被透传给记录阶段
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200), verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
eq("admin")); eq("admin"), isNull(), eq(false));
} }
@Test @Test
@@ -222,7 +195,7 @@ class OperationAuditWebFilterTest {
verify(writeMarker).onRequestStart(any()); verify(writeMarker).onRequestStart(any());
verify(writeMarker).onRequestComplete(any()); verify(writeMarker).onRequestComplete(any());
verify(recorder, never()).record(any(), any(), any(), any()); verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
} }
@Test @Test
@@ -236,60 +209,4 @@ class OperationAuditWebFilterTest {
verify(writeMarker, never()).onRequestStart(any()); verify(writeMarker, never()).onRequestStart(any());
verify(writeMarker, never()).onRequestComplete(any()); verify(writeMarker, never()).onRequestComplete(any());
} }
// ===== 登录失败告警(产品设计 V2「告警通知」) =====
@Test
void shouldNotifyLoginResultOnLoginAttempt() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.build());
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200));
}
@Test
void shouldNotifyLoginFailureStatusOnFailedLogin() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.build());
StepVerifier.create(filter.filter(exchange,
new FailingWebFilterChainStub(org.springframework.http.HttpStatus.UNAUTHORIZED)))
.verifyComplete();
// 非常响应(401)同样回调,由告警服务按失败累计
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401));
}
@Test
void shouldNotNotifyLoginResultForLoginPageOrLogout() {
// 登录页 GET 与登出不是登录尝试
var loginPage = MockServerWebExchange.from(MockServerHttpRequest
.get("/login")
.build());
StepVerifier.create(filter.filter(loginPage, CHAIN)).verifyComplete();
var logout = MockServerWebExchange.from(MockServerHttpRequest
.post("/logout")
.build());
StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete();
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), any());
}
@Test
void shouldNotNotifyLoginResultForApisRequests() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/apis/api.content.halo.run/v1alpha1/posts")
.build());
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), any());
}
} }
@@ -12,15 +12,24 @@ class OperationDescriptionTest {
@Test @Test
void shouldDescribeLoginEndpointIncludingQuery() { void shouldDescribeLoginEndpointIncludingQuery() {
// POST /login 是登录操作;GET /login(含任意查询串)只是打开登录页
assertThat(OperationDescription.describe("POST", "auth", "/login")).isEqualTo("登录"); assertThat(OperationDescription.describe("POST", "auth", "/login")).isEqualTo("登录");
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
assertThat(OperationDescription.describe("GET", "auth", assertThat(OperationDescription.describe("GET", "auth",
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("登录"); "/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole"))
.isEqualTo("访问登录页");
assertThat(OperationDescription.describe("GET", "auth", "/login?authentication_required"))
.isEqualTo("访问登录页");
// 升级前落库的失败回显(GET /login?error=...)无标注时由 error 参数现场推导
assertThat(OperationDescription.describe("GET", "auth",
"/login?error=invalid-credential&method=local")).isEqualTo("登录失败");
} }
@Test @Test
void shouldDescribeLogoutEndpoint() { void shouldDescribeLogoutEndpoint() {
assertThat(OperationDescription.describe("POST", "auth", "/logout")).isEqualTo("登出"); assertThat(OperationDescription.describe("POST", "auth", "/logout")).isEqualTo("登出");
// GET /logout 是登出确认页
assertThat(OperationDescription.describe("GET", "auth", "/logout"))
.isEqualTo("访问登出页");
} }
@Test @Test
@@ -104,14 +113,46 @@ class OperationDescriptionTest {
@Test @Test
void shouldDeriveLoginLogoutAuthActions() { void shouldDeriveLoginLogoutAuthActions() {
assertThat(OperationDescription.actionOf("POST", "auth", "/login")).isEqualTo("login"); assertThat(OperationDescription.actionOf("POST", "auth", "/login")).isEqualTo("login");
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
assertThat(OperationDescription.actionOf("GET", "auth",
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("login");
assertThat(OperationDescription.actionOf("POST", "auth", "/logout")).isEqualTo("logout"); assertThat(OperationDescription.actionOf("POST", "auth", "/logout")).isEqualTo("logout");
assertThat(OperationDescription.actionOf("POST", "auth", "/auth/other")) assertThat(OperationDescription.actionOf("POST", "auth", "/auth/other"))
.isEqualTo("auth"); .isEqualTo("auth");
} }
@Test
void shouldDeriveAuthPageVisitsByMethod() {
// 认证端点的页面访问(非 POST):打开登录页、被弹回登录页、登出确认页
assertThat(OperationDescription.actionOf("GET", "auth", "/login"))
.isEqualTo("login-page");
assertThat(OperationDescription.actionOf("GET", "auth",
"/login?authentication_required")).isEqualTo("login-page");
assertThat(OperationDescription.actionOf("GET", "auth", "/logout"))
.isEqualTo("logout-page");
// 失败回显(路径含 error 参数)推导为登录失败
assertThat(OperationDescription.actionOf("GET", "auth",
"/login?error=invalid-credential&method=local"))
.isEqualTo(OperationDescription.LOGIN_FAILURE_ACTION);
assertThat(OperationDescription.actionOf("GET", "auth", "/login?error&method=local"))
.isEqualTo(OperationDescription.LOGIN_FAILURE_ACTION);
// 含 error 字样的其他参数不算失败标记
assertThat(OperationDescription.actionOf("GET", "auth", "/login?errors=1"))
.isEqualTo("login-page");
}
@Test
void shouldDetectAuthPageVisits() {
assertThat(OperationDescription.isAuthPageVisit("GET", "/login")).isTrue();
assertThat(OperationDescription.isAuthPageVisit("GET", "/login?error=x")).isTrue();
assertThat(OperationDescription.isAuthPageVisit("GET", "/logout")).isTrue();
// POST 是真正的登录/登出操作
assertThat(OperationDescription.isAuthPageVisit("POST", "/login")).isFalse();
assertThat(OperationDescription.isAuthPageVisit("POST", "/logout")).isFalse();
// 其余路径一律不算
assertThat(OperationDescription.isAuthPageVisit("GET", "/apis/core.halo.run/v1alpha1/posts"))
.isFalse();
assertThat(OperationDescription.isAuthPageVisit("GET", "/loginx")).isFalse();
assertThat(OperationDescription.isAuthPageVisit("GET", null)).isFalse();
}
@Test @Test
void shouldDeriveMethodActions() { void shouldDeriveMethodActions() {
assertThat(OperationDescription.actionOf("POST", "users", assertThat(OperationDescription.actionOf("POST", "users",
@@ -197,7 +238,15 @@ class OperationDescriptionTest {
@Test @Test
void shouldDescribeFromActionKey() { void shouldDescribeFromActionKey() {
assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录"); assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录");
// 登录失败语义动作(POST /login 失败,或升级前落库的 GET /login?error=... 失败回显)
assertThat(OperationDescription.describeAction("login-failure", "auth"))
.isEqualTo("登录失败");
assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出"); assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出");
// 认证端点的页面访问(升级前落库的历史 GET 记录)
assertThat(OperationDescription.describeAction("login-page", "auth"))
.isEqualTo("访问登录页");
assertThat(OperationDescription.describeAction("logout-page", "auth"))
.isEqualTo("访问登出页");
assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作"); assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作");
assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户"); assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户");
assertThat(OperationDescription.describeAction("update", "posts")).isEqualTo("修改文章"); assertThat(OperationDescription.describeAction("update", "posts")).isEqualTo("修改文章");
@@ -215,4 +264,83 @@ class OperationDescriptionTest {
assertThat(OperationDescription.describeAction(null, "posts")).isNull(); assertThat(OperationDescription.describeAction(null, "posts")).isNull();
assertThat(OperationDescription.describeAction("bogus", "posts")).isNull(); assertThat(OperationDescription.describeAction("bogus", "posts")).isNull();
} }
@Test
void shouldDescribeSpecPreferingStoredAction() {
// 落库语义动作优先:登录失败标注(回显页 HTTP 200 无法由路径重新推导出失败)
var spec = new AuditLogSpec();
spec.setMethod("GET");
spec.setResourceType("auth");
spec.setPath("/login?error=invalid-credential&method=local");
spec.setAction("login-failure");
assertThat(OperationDescription.describe(spec)).isEqualTo("登录失败");
// 无标注(历史记录)回退 method/path 现场推导
var legacy = new AuditLogSpec();
legacy.setMethod("POST");
legacy.setResourceType("auth");
legacy.setPath("/login");
assertThat(OperationDescription.describe(legacy)).isEqualTo("登录");
// 落库标注未识别时同样回退现场推导
var bogus = new AuditLogSpec();
bogus.setMethod("PUT");
bogus.setResourceType("posts");
bogus.setPath("/apis/content.halo.run/v1alpha1/posts/abc");
bogus.setAction("bogus");
assertThat(OperationDescription.describe(bogus)).isEqualTo("修改文章");
}
@Test
void shouldCorrectAuthPageVisitsRegardlessOfStoredAction() {
// 升级前落库的页面访问记录带着 login/logout 标注(当时 GET 也被当成登录/登出记录):
// 展示必须按方法纠正为页面访问,否则这些记录继续显示成「未知用户 · 登录」
var loginPage = new AuditLogSpec();
loginPage.setMethod("GET");
loginPage.setResourceType("auth");
loginPage.setPath("/login?authentication_required");
loginPage.setAction("login");
assertThat(OperationDescription.semanticAction(loginPage)).isEqualTo("login-page");
assertThat(OperationDescription.describe(loginPage)).isEqualTo("访问登录页");
var logoutPage = new AuditLogSpec();
logoutPage.setMethod("GET");
logoutPage.setResourceType("auth");
logoutPage.setPath("/logout");
logoutPage.setAction("logout");
assertThat(OperationDescription.semanticAction(logoutPage)).isEqualTo("logout-page");
assertThat(OperationDescription.describe(logoutPage)).isEqualTo("访问登出页");
// 无标注的页面访问记录同样推导为页面访问
var unannotated = new AuditLogSpec();
unannotated.setMethod("GET");
unannotated.setResourceType("auth");
unannotated.setPath("/login");
assertThat(OperationDescription.describe(unannotated)).isEqualTo("访问登录页");
}
@Test
void shouldKeepStoredActionForAuthOperations() {
// POST 是真正的认证操作:落库标注优先(成功 login / 失败 login-failure / 登出 logout)
var success = new AuditLogSpec();
success.setMethod("POST");
success.setResourceType("auth");
success.setPath("/login");
success.setAction("login");
assertThat(OperationDescription.semanticAction(success)).isEqualTo("login");
var failure = new AuditLogSpec();
failure.setMethod("POST");
failure.setResourceType("auth");
failure.setPath("/login");
failure.setAction("login-failure");
assertThat(OperationDescription.semanticAction(failure)).isEqualTo("login-failure");
var logout = new AuditLogSpec();
logout.setMethod("POST");
logout.setResourceType("auth");
logout.setPath("/logout");
logout.setAction("logout");
assertThat(OperationDescription.semanticAction(logout)).isEqualTo("logout");
}
} }
+307
View File
@@ -6,6 +6,7 @@
"": { "": {
"name": "plugin-operation-audit-ui", "name": "plugin-operation-audit-ui",
"dependencies": { "dependencies": {
"@formkit/vue": "^1.7.2",
"@halo-dev/api-client": "2.26.0", "@halo-dev/api-client": "2.26.0",
"@halo-dev/components": "2.26.0", "@halo-dev/components": "2.26.0",
"@halo-dev/console-shared": "^2.21.0", "@halo-dev/console-shared": "^2.21.0",
@@ -16,6 +17,7 @@
"@types/node": "^20.19.1", "@types/node": "^20.19.1",
"@vitejs/plugin-vue": "^5.2.4", "@vitejs/plugin-vue": "^5.2.4",
"@vue/tsconfig": "^0.7.0", "@vue/tsconfig": "^0.7.0",
"axios": "^1.21.1",
"typescript": "~5.8.3", "typescript": "~5.8.3",
"vite": "^6.0.0", "vite": "^6.0.0",
"vitest": "^5.1.1", "vitest": "^5.1.1",
@@ -535,6 +537,113 @@
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT" "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": { "node_modules/@halo-dev/api-client": {
"version": "2.26.0", "version": "2.26.0",
"resolved": "https://registry.npmjs.org/@halo-dev/api-client/-/api-client-2.26.0.tgz", "resolved": "https://registry.npmjs.org/@halo-dev/api-client/-/api-client-2.26.0.tgz",
@@ -1328,6 +1437,19 @@
} }
} }
}, },
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "4"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/alien-signals": { "node_modules/alien-signals": {
"version": "1.0.13", "version": "1.0.13",
"resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-1.0.13.tgz", "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-1.0.13.tgz",
@@ -1352,6 +1474,26 @@
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"dev": true,
"license": "MIT"
},
"node_modules/axios": {
"version": "1.21.1",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz",
"integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.16.2",
"form-data": "^4.0.6",
"https-proxy-agent": "^5.0.1",
"proxy-from-env": "^2.1.0"
}
},
"node_modules/balanced-match": { "node_modules/balanced-match": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -1408,6 +1550,19 @@
"node": ">=18" "node": ">=18"
} }
}, },
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dev": true,
"license": "MIT",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/confbox": { "node_modules/confbox": {
"version": "0.3.2", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz", "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz",
@@ -1428,6 +1583,34 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/dunder-proto": { "node_modules/dunder-proto": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -1491,6 +1674,22 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/es-set-tostringtag": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/esbuild": { "node_modules/esbuild": {
"version": "0.25.12", "version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
@@ -1592,6 +1791,44 @@
} }
} }
}, },
"node_modules/follow-redirects": {
"version": "1.16.3",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz",
"integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==",
"dev": true,
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"license": "MIT",
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
"integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.4",
"mime-types": "^2.1.35"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/fsevents": { "node_modules/fsevents": {
"version": "2.3.3", "version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -1677,6 +1914,22 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/has-tostringtag": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": { "node_modules/hasown": {
"version": "2.0.4", "version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
@@ -1699,6 +1952,20 @@
"he": "bin/he" "he": "bin/he"
} }
}, },
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "6",
"debug": "4"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/js-yaml": { "node_modules/js-yaml": {
"version": "4.3.2", "version": "4.3.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
@@ -1740,6 +2007,29 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dev": true,
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/minimatch": { "node_modules/minimatch": {
"version": "9.0.9", "version": "9.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
@@ -1756,6 +2046,13 @@
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/muggle-string": { "node_modules/muggle-string": {
"version": "0.4.1", "version": "0.4.1",
"resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz",
@@ -1880,6 +2177,16 @@
"node": "^10 || ^12 || >=14" "node": "^10 || ^12 || >=14"
} }
}, },
"node_modules/proxy-from-env": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
"integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/qs": { "node_modules/qs": {
"version": "6.17.1", "version": "6.17.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz",
+2
View File
@@ -10,6 +10,7 @@
"test": "vitest run" "test": "vitest run"
}, },
"dependencies": { "dependencies": {
"@formkit/vue": "^1.7.2",
"@halo-dev/api-client": "2.26.0", "@halo-dev/api-client": "2.26.0",
"@halo-dev/components": "2.26.0", "@halo-dev/components": "2.26.0",
"@halo-dev/console-shared": "^2.21.0", "@halo-dev/console-shared": "^2.21.0",
@@ -20,6 +21,7 @@
"@types/node": "^20.19.1", "@types/node": "^20.19.1",
"@vitejs/plugin-vue": "^5.2.4", "@vitejs/plugin-vue": "^5.2.4",
"@vue/tsconfig": "^0.7.0", "@vue/tsconfig": "^0.7.0",
"axios": "^1.21.1",
"typescript": "~5.8.3", "typescript": "~5.8.3",
"vite": "^6.0.0", "vite": "^6.0.0",
"vitest": "^5.1.1", "vitest": "^5.1.1",
@@ -0,0 +1,4 @@
wwwroot/*.js
node_modules
typings
dist
@@ -0,0 +1 @@
# empty npmignore to ensure all required files (e.g., in the dist folder) are published by npm
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
@@ -0,0 +1,18 @@
.gitignore
.npmignore
.openapi-generator-ignore
api.ts
api/audit-v1alpha1-console-api.ts
base.ts
common.ts
configuration.ts
git_push.sh
index.ts
models/alert-send-result.ts
models/audit-log-list.ts
models/audit-log-spec.ts
models/audit-log.ts
models/change-entry.ts
models/change-type.ts
models/index.ts
models/metadata.ts
@@ -0,0 +1 @@
7.7.0
@@ -0,0 +1,18 @@
/* tslint:disable */
/* eslint-disable */
/**
* Operation Audit Extension API
* 操作审计插件自有子资源端点(query/export/test)的 OpenAPI 契约。本文件为 bootstrap 契约(与 SpringdocRouteBuilder 声明一一对应手工对齐),供 devtools generateApiClient 离线生成 TS 客户端;待有可用的 Halo 实例(Docker haloServer 或 useExistingServer)时,运行 ./gradlew generateOpenApiDocs 将以运行时 springdoc 输出覆盖本文件,再重新生成客户端即可(generateApiClient 每次先清空 outputDir)。版本号与插件版本保持同步。
*
* The version of the OpenAPI document: 0.1.0-SNAPSHOT
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export * from './api/audit-v1alpha1-console-api';
@@ -0,0 +1,433 @@
/* tslint:disable */
/* eslint-disable */
/**
* Operation Audit Extension API
* 操作审计插件自有子资源端点(query/export/test)的 OpenAPI 契约。本文件为 bootstrap 契约(与 SpringdocRouteBuilder 声明一一对应手工对齐),供 devtools generateApiClient 离线生成 TS 客户端;待有可用的 Halo 实例(Docker haloServer 或 useExistingServer)时,运行 ./gradlew generateOpenApiDocs 将以运行时 springdoc 输出覆盖本文件,再重新生成客户端即可(generateApiClient 每次先清空 outputDir)。版本号与插件版本保持同步。
*
* The version of the OpenAPI document: 0.1.0-SNAPSHOT
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from '../configuration';
import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, type RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../base';
// @ts-ignore
import type { AlertSendResult } from '../models';
// @ts-ignore
import type { AuditLogList } from '../models';
/**
* AuditV1alpha1ConsoleApi - axios parameter creator
* @export
*/
export const AuditV1alpha1ConsoleApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* 按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS 可直接打开):筛选参数与 query 完全一致,不分页全量导出,按时间升序输出
* @param {Array<string>} [fieldSelector] 等值筛选,可重复(与 query 一致)
* @param {string} [result] 结果筛选(success/failure)
* @param {string} [keyword] 关键字(resourceName/path 模糊匹配)
* @param {string} [startTime] 开始时间(ISO-8601,含边界)
* @param {string} [endTime] 结束时间(ISO-8601,含边界)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
exportAuditLogs: async (fieldSelector?: Array<string>, result?: string, keyword?: string, startTime?: string, endTime?: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/audit.guichumo.com/v1alpha1/auditlogs/-/export`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (fieldSelector) {
localVarQueryParameter['fieldSelector'] = fieldSelector;
}
if (result !== undefined) {
localVarQueryParameter['result'] = result;
}
if (keyword !== undefined) {
localVarQueryParameter['keyword'] = keyword;
}
if (startTime !== undefined) {
localVarQueryParameter['startTime'] = (startTime as any instanceof Date) ?
(startTime as any).toISOString() :
startTime;
}
if (endTime !== undefined) {
localVarQueryParameter['endTime'] = (endTime as any instanceof Date) ?
(endTime as any).toISOString() :
endTime;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* 分页查询审计日志:支持等值筛选(fieldSelector,含 spec.action 语义动作)、关键字(resourceName/path 模糊)、结果(success/failure)、时间区间(含边界)
* @param {number} [page] 页码(从 1 开始)
* @param {number} [size] 每页大小(1-100)
* @param {string} [sort] 排序(field,(asc|desc)),仅支持 metadata.creationTimestamp
* @param {Array<string>} [fieldSelector] 等值筛选,可重复(spec.username/spec.resourceType/spec.method/spec.action)
* @param {string} [result] 结果筛选(success/failure)
* @param {string} [keyword] 关键字(resourceName/path 模糊匹配)
* @param {string} [startTime] 开始时间(ISO-8601,含边界)
* @param {string} [endTime] 结束时间(ISO-8601,含边界)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listAuditLogs: async (page?: number, size?: number, sort?: string, fieldSelector?: Array<string>, result?: string, keyword?: string, startTime?: string, endTime?: string, options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (page !== undefined) {
localVarQueryParameter['page'] = page;
}
if (size !== undefined) {
localVarQueryParameter['size'] = size;
}
if (sort !== undefined) {
localVarQueryParameter['sort'] = sort;
}
if (fieldSelector) {
localVarQueryParameter['fieldSelector'] = fieldSelector;
}
if (result !== undefined) {
localVarQueryParameter['result'] = result;
}
if (keyword !== undefined) {
localVarQueryParameter['keyword'] = keyword;
}
if (startTime !== undefined) {
localVarQueryParameter['startTime'] = (startTime as any instanceof Date) ?
(startTime as any).toISOString() :
startTime;
}
if (endTime !== undefined) {
localVarQueryParameter['endTime'] = (endTime as any instanceof Date) ?
(endTime as any).toISOString() :
endTime;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* 向当前配置的 Webhook 地址推送一条测试告警(type=test)并返回推送结果:success 为是否送达(接收方 2xx),message 为状态/原因摘要;Webhook 未配置或非法时返回 400
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testAlertWebhook: async (options: RawAxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/apis/audit.guichumo.com/v1alpha1/alerts/-/test`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* AuditV1alpha1ConsoleApi - functional programming interface
* @export
*/
export const AuditV1alpha1ConsoleApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = AuditV1alpha1ConsoleApiAxiosParamCreator(configuration)
return {
/**
* 按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS 可直接打开):筛选参数与 query 完全一致,不分页全量导出,按时间升序输出
* @param {Array<string>} [fieldSelector] 等值筛选,可重复(与 query 一致)
* @param {string} [result] 结果筛选(success/failure)
* @param {string} [keyword] 关键字(resourceName/path 模糊匹配)
* @param {string} [startTime] 开始时间(ISO-8601,含边界)
* @param {string} [endTime] 结束时间(ISO-8601,含边界)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async exportAuditLogs(fieldSelector?: Array<string>, result?: string, keyword?: string, startTime?: string, endTime?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<File>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.exportAuditLogs(fieldSelector, result, keyword, startTime, endTime, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['AuditV1alpha1ConsoleApi.exportAuditLogs']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* 分页查询审计日志:支持等值筛选(fieldSelector,含 spec.action 语义动作)、关键字(resourceName/path 模糊)、结果(success/failure)、时间区间(含边界)
* @param {number} [page] 页码(从 1 开始)
* @param {number} [size] 每页大小(1-100)
* @param {string} [sort] 排序(field,(asc|desc)),仅支持 metadata.creationTimestamp
* @param {Array<string>} [fieldSelector] 等值筛选,可重复(spec.username/spec.resourceType/spec.method/spec.action)
* @param {string} [result] 结果筛选(success/failure)
* @param {string} [keyword] 关键字(resourceName/path 模糊匹配)
* @param {string} [startTime] 开始时间(ISO-8601,含边界)
* @param {string} [endTime] 结束时间(ISO-8601,含边界)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listAuditLogs(page?: number, size?: number, sort?: string, fieldSelector?: Array<string>, result?: string, keyword?: string, startTime?: string, endTime?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<AuditLogList>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listAuditLogs(page, size, sort, fieldSelector, result, keyword, startTime, endTime, options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['AuditV1alpha1ConsoleApi.listAuditLogs']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
/**
* 向当前配置的 Webhook 地址推送一条测试告警(type=test)并返回推送结果:success 为是否送达(接收方 2xx),message 为状态/原因摘要;Webhook 未配置或非法时返回 400
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testAlertWebhook(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<AlertSendResult>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testAlertWebhook(options);
const localVarOperationServerIndex = configuration?.serverIndex ?? 0;
const localVarOperationServerBasePath = operationServerMap['AuditV1alpha1ConsoleApi.testAlertWebhook']?.[localVarOperationServerIndex]?.url;
return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
},
}
};
/**
* AuditV1alpha1ConsoleApi - factory interface
* @export
*/
export const AuditV1alpha1ConsoleApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = AuditV1alpha1ConsoleApiFp(configuration)
return {
/**
* 按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS 可直接打开):筛选参数与 query 完全一致,不分页全量导出,按时间升序输出
* @param {AuditV1alpha1ConsoleApiExportAuditLogsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
exportAuditLogs(requestParameters: AuditV1alpha1ConsoleApiExportAuditLogsRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise<File> {
return localVarFp.exportAuditLogs(requestParameters.fieldSelector, requestParameters.result, requestParameters.keyword, requestParameters.startTime, requestParameters.endTime, options).then((request) => request(axios, basePath));
},
/**
* 分页查询审计日志:支持等值筛选(fieldSelector,含 spec.action 语义动作)、关键字(resourceName/path 模糊)、结果(success/failure)、时间区间(含边界)
* @param {AuditV1alpha1ConsoleApiListAuditLogsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listAuditLogs(requestParameters: AuditV1alpha1ConsoleApiListAuditLogsRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise<AuditLogList> {
return localVarFp.listAuditLogs(requestParameters.page, requestParameters.size, requestParameters.sort, requestParameters.fieldSelector, requestParameters.result, requestParameters.keyword, requestParameters.startTime, requestParameters.endTime, options).then((request) => request(axios, basePath));
},
/**
* 向当前配置的 Webhook 地址推送一条测试告警(type=test)并返回推送结果:success 为是否送达(接收方 2xx),message 为状态/原因摘要;Webhook 未配置或非法时返回 400
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testAlertWebhook(options?: RawAxiosRequestConfig): AxiosPromise<AlertSendResult> {
return localVarFp.testAlertWebhook(options).then((request) => request(axios, basePath));
},
};
};
/**
* Request parameters for exportAuditLogs operation in AuditV1alpha1ConsoleApi.
* @export
* @interface AuditV1alpha1ConsoleApiExportAuditLogsRequest
*/
export interface AuditV1alpha1ConsoleApiExportAuditLogsRequest {
/**
* 等值筛选,可重复(与 query 一致)
* @type {Array<string>}
* @memberof AuditV1alpha1ConsoleApiExportAuditLogs
*/
readonly fieldSelector?: Array<string>
/**
* 结果筛选(success/failure)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiExportAuditLogs
*/
readonly result?: string
/**
* 关键字(resourceName/path 模糊匹配)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiExportAuditLogs
*/
readonly keyword?: string
/**
* 开始时间(ISO-8601,含边界)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiExportAuditLogs
*/
readonly startTime?: string
/**
* 结束时间(ISO-8601,含边界)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiExportAuditLogs
*/
readonly endTime?: string
}
/**
* Request parameters for listAuditLogs operation in AuditV1alpha1ConsoleApi.
* @export
* @interface AuditV1alpha1ConsoleApiListAuditLogsRequest
*/
export interface AuditV1alpha1ConsoleApiListAuditLogsRequest {
/**
* 页码(从 1 开始)
* @type {number}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly page?: number
/**
* 每页大小(1-100)
* @type {number}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly size?: number
/**
* 排序(field,(asc|desc)),仅支持 metadata.creationTimestamp
* @type {string}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly sort?: string
/**
* 等值筛选,可重复(spec.username/spec.resourceType/spec.method/spec.action)
* @type {Array<string>}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly fieldSelector?: Array<string>
/**
* 结果筛选(success/failure)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly result?: string
/**
* 关键字(resourceName/path 模糊匹配)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly keyword?: string
/**
* 开始时间(ISO-8601,含边界)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly startTime?: string
/**
* 结束时间(ISO-8601,含边界)
* @type {string}
* @memberof AuditV1alpha1ConsoleApiListAuditLogs
*/
readonly endTime?: string
}
/**
* AuditV1alpha1ConsoleApi - object-oriented interface
* @export
* @class AuditV1alpha1ConsoleApi
* @extends {BaseAPI}
*/
export class AuditV1alpha1ConsoleApi extends BaseAPI {
/**
* 按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS 可直接打开):筛选参数与 query 完全一致,不分页全量导出,按时间升序输出
* @param {AuditV1alpha1ConsoleApiExportAuditLogsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuditV1alpha1ConsoleApi
*/
public exportAuditLogs(requestParameters: AuditV1alpha1ConsoleApiExportAuditLogsRequest = {}, options?: RawAxiosRequestConfig) {
return AuditV1alpha1ConsoleApiFp(this.configuration).exportAuditLogs(requestParameters.fieldSelector, requestParameters.result, requestParameters.keyword, requestParameters.startTime, requestParameters.endTime, options).then((request) => request(this.axios, this.basePath));
}
/**
* 分页查询审计日志:支持等值筛选(fieldSelector,含 spec.action 语义动作)、关键字(resourceName/path 模糊)、结果(success/failure)、时间区间(含边界)
* @param {AuditV1alpha1ConsoleApiListAuditLogsRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuditV1alpha1ConsoleApi
*/
public listAuditLogs(requestParameters: AuditV1alpha1ConsoleApiListAuditLogsRequest = {}, options?: RawAxiosRequestConfig) {
return AuditV1alpha1ConsoleApiFp(this.configuration).listAuditLogs(requestParameters.page, requestParameters.size, requestParameters.sort, requestParameters.fieldSelector, requestParameters.result, requestParameters.keyword, requestParameters.startTime, requestParameters.endTime, options).then((request) => request(this.axios, this.basePath));
}
/**
* 向当前配置的 Webhook 地址推送一条测试告警(type=test)并返回推送结果:success 为是否送达(接收方 2xx),message 为状态/原因摘要;Webhook 未配置或非法时返回 400
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuditV1alpha1ConsoleApi
*/
public testAlertWebhook(options?: RawAxiosRequestConfig) {
return AuditV1alpha1ConsoleApiFp(this.configuration).testAlertWebhook(options).then((request) => request(this.axios, this.basePath));
}
}
@@ -0,0 +1,86 @@
/* tslint:disable */
/* eslint-disable */
/**
* Operation Audit Extension API
* 操作审计插件自有子资源端点(query/export/test)的 OpenAPI 契约。本文件为 bootstrap 契约(与 SpringdocRouteBuilder 声明一一对应手工对齐),供 devtools generateApiClient 离线生成 TS 客户端;待有可用的 Halo 实例(Docker haloServer 或 useExistingServer)时,运行 ./gradlew generateOpenApiDocs 将以运行时 springdoc 输出覆盖本文件,再重新生成客户端即可(generateApiClient 每次先清空 outputDir)。版本号与插件版本保持同步。
*
* The version of the OpenAPI document: 0.1.0-SNAPSHOT
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from './configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
export const BASE_PATH = "http://localhost".replace(/\/+$/, "");
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @interface RequestArgs
*/
export interface RequestArgs {
url: string;
options: RawAxiosRequestConfig;
}
/**
*
* @export
* @class BaseAPI
*/
export class BaseAPI {
protected configuration: Configuration | undefined;
constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
if (configuration) {
this.configuration = configuration;
this.basePath = configuration.basePath ?? basePath;
}
}
};
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
constructor(public field: string, msg?: string) {
super(msg);
this.name = "RequiredError"
}
}
interface ServerMap {
[key: string]: {
url: string,
description: string,
}[];
}
/**
*
* @export
*/
export const operationServerMap: ServerMap = {
}
@@ -0,0 +1,150 @@
/* tslint:disable */
/* eslint-disable */
/**
* Operation Audit Extension API
* 操作审计插件自有子资源端点(query/export/test)的 OpenAPI 契约。本文件为 bootstrap 契约(与 SpringdocRouteBuilder 声明一一对应手工对齐),供 devtools generateApiClient 离线生成 TS 客户端;待有可用的 Halo 实例(Docker haloServer 或 useExistingServer)时,运行 ./gradlew generateOpenApiDocs 将以运行时 springdoc 输出覆盖本文件,再重新生成客户端即可(generateApiClient 每次先清空 outputDir)。版本号与插件版本保持同步。
*
* The version of the OpenAPI document: 0.1.0-SNAPSHOT
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from "./configuration";
import type { RequestArgs } from "./base";
import type { AxiosInstance, AxiosResponse } from 'axios';
import { RequiredError } from "./base";
/**
*
* @export
*/
export const DUMMY_BASE_URL = 'https://example.com'
/**
*
* @throws {RequiredError}
* @export
*/
export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) {
if (paramValue === null || paramValue === undefined) {
throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
}
}
/**
*
* @export
*/
export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) {
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? await configuration.apiKey(keyParamName)
: await configuration.apiKey;
object[keyParamName] = localVarApiKeyValue;
}
}
/**
*
* @export
*/
export const setBasicAuthToObject = function (object: any, configuration?: Configuration) {
if (configuration && (configuration.username || configuration.password)) {
object["auth"] = { username: configuration.username, password: configuration.password };
}
}
/**
*
* @export
*/
export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const accessToken = typeof configuration.accessToken === 'function'
? await configuration.accessToken()
: await configuration.accessToken;
object["Authorization"] = "Bearer " + accessToken;
}
}
/**
*
* @export
*/
export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? await configuration.accessToken(name, scopes)
: await configuration.accessToken;
object["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
}
function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void {
if (parameter == null) return;
if (typeof parameter === "object") {
if (Array.isArray(parameter)) {
(parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
}
else {
Object.keys(parameter).forEach(currentKey =>
setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`)
);
}
}
else {
if (urlSearchParams.has(key)) {
urlSearchParams.append(key, parameter);
}
else {
urlSearchParams.set(key, parameter);
}
}
}
/**
*
* @export
*/
export const setSearchParams = function (url: URL, ...objects: any[]) {
const searchParams = new URLSearchParams(url.search);
setFlattenedQueryParams(searchParams, objects);
url.search = searchParams.toString();
}
/**
*
* @export
*/
export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) {
const nonString = typeof value !== 'string';
const needsSerialization = nonString && configuration && configuration.isJsonMime
? configuration.isJsonMime(requestOptions.headers['Content-Type'])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
}
/**
*
* @export
*/
export const toPathString = function (url: URL) {
return url.pathname + url.search + url.hash
}
/**
*
* @export
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) {
return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url};
return axios.request<T, R>(axiosRequestArgs);
};
}

Some files were not shown because too many files have changed in this diff Show More