Compare commits
42
Commits
a488360d46
..
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d05d63b8e | ||
|
|
753de51f7b | ||
|
|
44eca75e6e | ||
|
|
81693e4778 | ||
|
|
b6a21dfaa7 | ||
|
|
1987412e07 | ||
|
|
fd3ea71e31 | ||
|
|
99bd109e80 | ||
|
|
f4d1200d46 | ||
|
|
cc2c618fe7 | ||
|
|
34764c7641 | ||
|
|
87ae0c79bb | ||
|
|
9e89ed75ed | ||
|
|
9865149ab3 | ||
|
|
7257008af3 | ||
|
|
f59cab95a0 | ||
|
|
197c5a3830 | ||
|
|
a38cb4a3b5 | ||
|
|
19dc0da1eb | ||
|
|
cb3ff6ef17 | ||
|
|
3269bafbc4 | ||
|
|
08e7bd8a12 | ||
|
|
cb86a3d305 | ||
|
|
8c2f781230 | ||
|
|
20a4db5119 | ||
|
|
3d1128c254 | ||
|
|
3d31c84b48 | ||
|
|
a56bf2b9de | ||
|
|
648893b34a | ||
|
|
058596c0ea | ||
|
|
3abd79a65f | ||
|
|
7cca63b9d9 | ||
|
|
8aae68c95c | ||
|
|
55c50706b5 | ||
|
|
7280ccb5f3 | ||
|
|
cdbea79ba6 | ||
|
|
8cc66a5693 | ||
|
|
c2e38d7c44 | ||
|
|
68f362cb42 | ||
|
|
f4be39d065 | ||
|
|
bf7573034a | ||
|
|
67d9745cd1 |
@@ -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"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
+12
@@ -3,3 +3,15 @@
|
||||
.v2c/
|
||||
.video_agent/
|
||||
.zcode/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
|
||||
# 系统
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# 日志
|
||||
*.log
|
||||
|
||||
@@ -1,19 +1,42 @@
|
||||
# halo-ops-audit
|
||||
|
||||
Halo 2.x 操作审计插件仓库:回答"**谁、在什么时候、对什么资源、做了什么操作、结果如何**"。
|
||||
主项目位于 [`plugin-operation-audit/`](plugin-operation-audit/README.md),其 README 覆盖功能、安装、设置与已知局限。
|
||||
Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资源、做了什么操作、结果如何、改了什么**"。
|
||||
|
||||
## 目录结构
|
||||
一条通用捕获规则覆盖后台全部写操作——文章、页面、评论、用户、设置、主题、插件启停、附件,
|
||||
以及登录 / 登出——无需逐资源配置;审计记录只增不改,Console 中不提供任何删除 / 修改入口。
|
||||
|
||||
| 路径 | 说明 |
|
||||
## 功能一览
|
||||
|
||||
| 能力 | 说明 |
|
||||
|---|---|
|
||||
| `plugin-operation-audit/` | 插件主项目:Java 服务端(捕获过滤器、审计模型、查询端点、保留期清理)+ Console UI(Vue)+ 单元测试 |
|
||||
| `demo/` | Console UI 静态演示页(纯前端、模拟数据,无构建依赖),开发真实插件前用于验证界面布局与操作流程;含独立 Node 测试 |
|
||||
| `docs/` | 设计文档:[产品设计](docs/operation-audit-design.md) · [技术方案](docs/operation-audit-tech-design.md) |
|
||||
| `AGENTS.md` | AI 协作约定(每次改动需 commit、测试全绿后交付) |
|
||||
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
||||
| 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 |
|
||||
| 语义动作标注 | 捕获时标注语义动作键(登录/登录失败/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
|
||||
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成败均为 302 重定向,以重定向目标 `error` 参数区分):失败尝试与失败回显页(`GET /login?error=...`)在列表/详情/CSV 中显示红色「失败」,而非被页面渲染的绿色 HTTP 200 掩盖 |
|
||||
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 |
|
||||
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) |
|
||||
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) |
|
||||
| 登录失败告警 | 统计窗口内登录失败达到阈值时向 Webhook 地址异步推送通用 JSON 告警(默认 5 分钟 / 5 次,告警后窗口重开,登录成功清零;独立于审计开关,默认关闭) |
|
||||
| 保留与清理 | 可配置保留天数(7 ~ ∞,默认 90),每日凌晨自动清理过期记录 |
|
||||
| 权限 | 默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`(verbs 仅 `get`/`list`) |
|
||||
|
||||
## 仓库结构
|
||||
|
||||
```
|
||||
.
|
||||
├── plugin-operation-audit/ # 插件主项目:Java 服务端 + Console UI(Vue)+ 单元测试
|
||||
│ ├── src/ # 捕获过滤器、审计模型、查询端点、保留期清理
|
||||
│ └── ui/ # Console 前端(Vue 3 + vitest)
|
||||
├── demo/ # Console UI 静态演示页(纯前端、模拟数据、零构建依赖)
|
||||
├── docs/ # 设计文档:产品设计 · 技术方案
|
||||
└── AGENTS.md # AI 协作约定(每次改动需 commit、测试全绿后交付)
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
环境要求:**JDK 21**(构建插件)、**Docker**(仅 `./gradlew haloServer` 本地起开发用 Halo 需要)。
|
||||
目标平台 Halo 2.26.1。
|
||||
|
||||
### 构建与测试插件
|
||||
|
||||
```bash
|
||||
@@ -23,17 +46,22 @@ cd plugin-operation-audit
|
||||
./gradlew haloServer # 启动开发用 Halo(devtools,需 Docker)
|
||||
```
|
||||
|
||||
要求 JDK 21,目标平台 Halo 2.26.1。前端独立开发:`cd ui && npm install && npm run dev`。
|
||||
前端独立开发:`cd ui && npm install && npm run dev`。
|
||||
|
||||
安装到真实站点:把 `build/libs/plugin-operation-audit-<version>.jar` 上传到
|
||||
Halo Console「插件 → 安装」并启用,左侧菜单即出现"操作审计"。
|
||||
|
||||
### 查看 UI 演示
|
||||
|
||||
直接双击打开 `demo/index.html`,或:
|
||||
|
||||
```bash
|
||||
cd demo
|
||||
python -m http.server 8721 # 访问 http://127.0.0.1:8721/
|
||||
```
|
||||
|
||||
也可直接双击打开 `demo/index.html`(`file://` 下可运行)。演示页内置若干故事线,
|
||||
可体验"排查这篇文章谁改过""登录爆破回溯""误操作定位"等典型场景,
|
||||
并通过"模拟一次操作"按钮验证捕获规则的边界。
|
||||
|
||||
### 运行演示测试
|
||||
|
||||
```bash
|
||||
@@ -42,6 +70,9 @@ node --test demo/test/audit-core.test.mjs
|
||||
|
||||
## 相关文档
|
||||
|
||||
- 功能、安装、设置、已知局限:[plugin-operation-audit/README.md](plugin-operation-audit/README.md)
|
||||
- 产品设计(MVP 范围、设计原则):[docs/operation-audit-design.md](docs/operation-audit-design.md)
|
||||
- 技术方案(架构、数据模型、风险预案):[docs/operation-audit-tech-design.md](docs/operation-audit-tech-design.md)
|
||||
| 文档 | 内容 |
|
||||
|---|---|
|
||||
| [plugin-operation-audit/README.md](plugin-operation-audit/README.md) | 插件详情:功能、安装、设置、模型 group 与已知局限 |
|
||||
| [demo/README.md](demo/README.md) | 演示页说明:演示了什么、与真实实现的差异 |
|
||||
| [docs/operation-audit-design.md](docs/operation-audit-design.md) | 产品设计:MVP 范围、设计原则 |
|
||||
| [docs/operation-audit-tech-design.md](docs/operation-audit-tech-design.md) | 技术方案:架构、数据模型、风险预案 |
|
||||
|
||||
@@ -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)完成自动化检查、构建及安装/启停验证后再用于生产环境。
|
||||
@@ -9,7 +9,7 @@ Halo 博客后台缺少操作追溯能力:文章被改、设置被动、评论
|
||||
|
||||
## 2. 产品定位
|
||||
|
||||
一句话:**回答"谁、在什么时候、对什么资源、做了什么操作、结果如何"**。
|
||||
一句话:**回答"谁、在什么时候、对什么资源、做了什么操作、结果如何、改了什么"**。
|
||||
|
||||
- 面向:站长(自用为主,验证稳定后考虑上架应用市场)
|
||||
- 形态:Halo 2.x 插件(Java 服务端 + Console 管理页)
|
||||
@@ -31,26 +31,28 @@ Halo 博客后台缺少操作追溯能力:文章被改、设置被动、评论
|
||||
### 4.1 操作记录(核心)
|
||||
|
||||
- **捕获范围**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH)。一条通用规则天然覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作,Halo 新增资源类型也自动纳入。匿名访客请求不记录。
|
||||
> 注:登录端点不在 `/apis/**` 下,捕获规则将其作为唯一必要例外精确匹配 `/login`、`/logout`(技术方案 D1)。
|
||||
> 注:登录端点不在 `/apis/**` 下,且表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),由独立的认证端点过滤器在 Security 过滤链**之前**精确匹配捕获 `/login`、`/logout`(技术方案 D1)。
|
||||
- **系统内部变更(V2)**:定时发布等非页面操作触发的资源变更不经过 HTTP,由扩展模型 Watcher 通道补记(技术方案 D8):仅记录用户可写面有实际变化的更新/删除;设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物不重复记录;插件自身配置写入排除。
|
||||
- 每条记录字段:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| 时间 | 操作发生时间 |
|
||||
| 操作者 | 用户名(登录失败暂记"未知用户") |
|
||||
| 动作 | HTTP 方法 |
|
||||
| 操作者 | 用户名(登录失败暂记"未知用户";系统内部变更记 "system",Console 展示"系统") |
|
||||
| 动作 | HTTP 方法(系统内部变更按事件类型记 PUT/DELETE) |
|
||||
| 语义动作 | 捕获时由方法与路径推导的语义动作键(如 `publish`),支持按其筛选 |
|
||||
| 资源 | 从路径解析出的资源类型与名称(如 `Posts/xxx`) |
|
||||
| 路径 | 完整请求路径 |
|
||||
| 结果 | 响应状态码(成功/失败) |
|
||||
| 来源 | IP、User-Agent |
|
||||
| 路径 | 完整请求路径(系统内部变更记资源规范 API 路径) |
|
||||
| 结果 | 响应状态码(成功/失败;系统内部变更恒记 200,事件在写入成功后派发) |
|
||||
| 来源 | IP、User-Agent(系统内部变更无 IP/UA) |
|
||||
|
||||
### 4.2 审计日志查看(核心)
|
||||
|
||||
Console 左侧菜单新增"操作审计"页:
|
||||
|
||||
- 列表:时间、操作者、动作、资源、结果、IP,索引分页查询
|
||||
- 筛选:按操作者、资源类型、动作、结果、时间范围;关键字可模糊匹配资源名称/路径
|
||||
- 详情:单条记录完整字段
|
||||
- 列表:时间、操作者、动作、资源、描述、结果、IP,索引分页查询
|
||||
- 筛选:按操作者、资源类型、动作、语义动作、结果、时间范围;关键字可模糊匹配资源名称/路径
|
||||
- 详情:单条记录完整字段,含字段级变更(改了什么:字段路径 + 新旧值)
|
||||
- 只读:不提供任何删除/修改入口
|
||||
|
||||
### 4.3 保留与清理
|
||||
@@ -69,31 +71,40 @@ Console 左侧菜单新增"操作审计"页:
|
||||
审计日志作为 Halo 自定义模型(Extension)存储,注册后自动获得存储与查询 API。
|
||||
|
||||
- 模型:`AuditLog`(group 用自有域名反写,如 `audit.<你的域名>`)
|
||||
- 索引:操作者、资源类型、动作、结果、创建时间(支撑筛选与分页,避免内存分页);另含资源名称、完整路径两个索引,支撑关键字模糊筛选(4.2)
|
||||
- 索引:操作者、资源类型、动作、语义动作、结果、创建时间(支撑筛选与分页,避免内存分页);另含资源名称、完整路径两个索引,支撑关键字模糊筛选(4.2)
|
||||
- 字段级变更:`spec.changes`(字段路径、变更类型、新旧值),仅成功的建/改/删操作落库,不建索引(不参与筛选)
|
||||
- 存储由 Halo 统一管理
|
||||
|
||||
## 6. 非目标(V2+ 展望)
|
||||
|
||||
| 功能 | 说明 | 阶段 |
|
||||
|---|---|---|
|
||||
| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作 | V2 |
|
||||
| 字段级变更 diff | 记录改了什么(需缓存请求体) | V2 |
|
||||
| 系统内部变更 | 定时发布等非 HTTP 触发的变更,执行者记"system" | V2 |
|
||||
| 导出 CSV | 按筛选条件导出 | V2 |
|
||||
| 告警通知 | 登录失败告警、webhook | V2+ |
|
||||
| 语义动作标注 | 区分"发布/编辑/恢复/登录失败"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 |
|
||||
| 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 |
|
||||
| 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 |
|
||||
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
|
||||
| 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 |
|
||||
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成功与失败均为 302 重定向,以重定向目标是否含 `error` 参数区分,见 `LoginOutcome`):失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)标注语义动作 `login-failure`,列表/详情/CSV 显示红色「失败」而非裸状态码,避免绿色 200/302 误读为登录成功;HTTP 状态码仍如实记录 | V2+ 已实现 |
|
||||
| 操作回滚 | 不在产品范围内 | 不做 |
|
||||
|
||||
## 7. 已知局限
|
||||
|
||||
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2)
|
||||
- 系统内部触发的资源变更(如定时发布)暂不记录
|
||||
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)不记录(几乎均伴随页面/API 操作,已被 HTTP 通道捕获);操作描述由事件类型推导(更新/删除),具体语义以字段级 diff 为准
|
||||
- 系统内部变更的归属降噪为通用规则:设置类资源(ConfigMap/Secret)在写请求活动宽限窗内的变更视为 HTTP 副产物跳过;极少数"路径与实际写入资源不一致"的非设置类端点,其副产物可能记为 system(已知取舍,完整性优先)
|
||||
- reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见)
|
||||
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中
|
||||
- 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更
|
||||
- 登录成败判定依赖 Halo 登录端点契约(表单登录成败均为 302 重定向,失败目标含 `error` 参数):Halo 若调整失败重定向格式或引入新的登录方式,需同步调整 `LoginOutcome`;告警仅覆盖 POST /login,登录页 GET 与登出不算尝试;告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
|
||||
- 升级前落库的历史记录无法补标注登录失败:表单登录失败(POST /login,302)在列表中仍显示数字状态码,仅失败回显页(GET,路径含 `error` 参数)可现场推导;升级后新记录由捕获时标注(`spec.action = login-failure`),不再有此局限
|
||||
- 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******`
|
||||
- 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中
|
||||
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口)
|
||||
- 审计写入失败静默降级为运行日志,不阻塞业务操作
|
||||
|
||||
## 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
|
||||
- 捕获通道:`AfterSecurityWebFilter` 扩展点——位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码
|
||||
- 捕获通道:双过滤器分治——`/apis/**` 写操作由 `AfterSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最后、认证之后执行,可获取当前登录用户,`doFinally` 可读最终响应状态码);认证端点 `/login`、`/logout` 由 `BeforeSecurityWebFilter` 扩展点捕获(位于 Security 过滤链最前,先于表单登录/登出终止过滤器,操作者记"未知用户")。P0 缺陷实证:链尾过滤器永远看不到表单登录/登出请求(命中即 302 终止,不向下游传递),认证端点必须在链首承接
|
||||
- 为何走 HTTP 层:AOP 拦截核心 API、资源元数据自带操作者两条路在 2.26.1 上均被源码验证不可行
|
||||
- 存储:自定义 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)(事件监听与稳定性模式)
|
||||
|
||||
@@ -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,150 @@
|
||||
# 操作审计插件发布验收清单确认报告
|
||||
|
||||
> 依据 [plugin-release-checklist.md](./plugin-release-checklist.md) 对本插件做发布前逐项确认。
|
||||
>
|
||||
> - 确认日期:2026-11-22(首轮确认 + 同日待办补齐复测)
|
||||
> - 被测制品:**正式版干净构建产物**
|
||||
> `plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar`
|
||||
> - 源码基线:commit `81693e4`(master,工作区干净)
|
||||
> - 结论速览:**发布就绪**——首轮确认的 2 项 P0、2 项 P1、2 项 P2 待办已全部补齐
|
||||
> 并复测通过(正式版本号构建、CI/CD 工作流、卸载测试、2.26.0 下探、SHA-256
|
||||
> 证据块、manifest 元数据与 ui/ 迁移),见文末[结论与待办](#结论与待办)。
|
||||
> 首轮确认时的历史状态以"首轮确认"标注保留在正文。
|
||||
|
||||
## 一、构建发布制品 — ✅ 通过(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/src/api/index.ts`)复用宿主 `axiosInstance`;全量检索确认无手写同资源类型/路径 |
|
||||
| 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 — ✅ 已配置(本轮补齐)
|
||||
|
||||
[.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 插件完成前端构建。
|
||||
|
||||
## 五、记录发布证据 — ✅ 就绪(本轮补齐)
|
||||
|
||||
发布证据块(正式版制品,构建于 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 与测试)。
|
||||
|
||||
## 结论与待办
|
||||
|
||||
**发布就绪**:原 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
|
||||
资产 → (审核通过后)配置应用市场同步。
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [插件发布验收清单(本地存档)](./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,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 节(已知局限,落地后需同步更新)
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
| # | 决策 | 结论 | 理由 |
|
||||
|---|---|---|---|
|
||||
| D1 | 捕获通道 | 单一 `AfterSecurityWebFilter`,路径规则为 `/apis/**` 写操作 + `/login` + `/logout` | 登录端点不在 `/apis/**` 下,扩路径匹配而非引入第二套机制 |
|
||||
| D1 | 捕获通道 | 双过滤器分治:`/apis/**` 写操作走 `AfterSecurityWebFilter`;认证端点 `/login`、`/logout` 走 `BeforeSecurityWebFilter`(Security 链之前) | 表单登录/登出过滤器命中请求后直接完成 302 响应、不再向下游传递(P0 缺陷实测),链尾过滤器永远看不到认证端点请求,必须在链首承接 |
|
||||
| D2 | 审计写入方式 | 响应式直写(fire-and-forget),失败静默降级 | WebFlux event loop 上不得阻塞主流程;自用量级无需队列 |
|
||||
| D3 | 列表查询 | 优先 Halo 原生列表 API + 索引;时间区间不支持时再开自有查询端点 | 避免内存分页,符合产品设计第 5 节 |
|
||||
|
||||
@@ -21,14 +21,14 @@
|
||||
| 服务端 | Java 21 + Spring WebFlux(与 Halo 同构) | 由平台 BOM 锁定;保持 Java,与参考插件生态一致 |
|
||||
| 构建 | Gradle(Groovy DSL,跟随官方 starter)+ `run.halo.plugin.devtools` 0.8.0 + 平台 BOM 2.26.0 | 以 `plugin-starter` 模板初始化 |
|
||||
| 存储 | 自定义 Extension(`AuditLog`)+ 索引查询 | 不接外部数据库,建表/备份/连接池问题全部消失 |
|
||||
| 捕获通道 | `AfterSecurityWebFilter` 扩展点(实现 `WebFilter`,注册在 Security 链之后) | 产品文档第 8 节已源码级验证 |
|
||||
| 捕获通道 | `AfterSecurityWebFilter` + `BeforeSecurityWebFilter` 扩展点(实现 `WebFilter`,分别注册在 Security 链最后与最前) | 产品文档第 8 节已源码级验证;P0 缺陷实证双通道必要性 |
|
||||
| 客户端 | `ReactiveExtensionClient` | 全程非阻塞,符合设计原则 4 |
|
||||
| Console UI | Vue 3 + TypeScript + Vite + `@halo-dev/components` | 官方插件前端模板即此;不引入额外状态管理,组件内 `ref` 足够 |
|
||||
| 设置页 | `settings.yaml` 声明式声明 | Console 自动渲染,零前端代码 |
|
||||
| 权限 | 角色 YAML(role template)+ `@GVK` 注解 | Halo 标准做法 |
|
||||
| 测试 | JUnit 5 + Mockito + reactor-test(`StepVerifier`) | 对应 AGENTS.md"每里程碑测试全绿"要求 |
|
||||
|
||||
文中 `audit.example.com` 均为 group 占位,落地前替换为自有域名反写。
|
||||
文中 `audit.example.com` 均为 group 占位示例;实现已按自有域名反写约定落定为 `audit.guichumo.com`(唯一事实来源:`AuditLog.GROUP`)。
|
||||
|
||||
## 3. 工程结构
|
||||
|
||||
@@ -43,11 +43,22 @@ plugin-operation-audit/
|
||||
│ │ ├── OperationAuditPlugin.java # BasePlugin:注册/注销 Scheme 与索引
|
||||
│ │ ├── audit/
|
||||
│ │ │ ├── AuditLog.java # Extension + @GVK
|
||||
│ │ │ ├── AuditLogSpec.java
|
||||
│ │ │ ├── CaptureRule.java # 路径/方法/匿名判断(纯函数,便于测试)
|
||||
│ │ │ ├── AuditLogSpec.java # 含 changes 字段级变更列表
|
||||
│ │ │ ├── ChangeType.java # 变更类型 ADDED/UPDATED/REMOVED
|
||||
│ │ │ ├── ChangeEntry.java # 单条字段变更(field/type/old/new)
|
||||
│ │ │ ├── ExtensionTargets.java # 路径 → GVK+name(/apis 与 /api 两种形态,纯函数)
|
||||
│ │ │ ├── HttpWriteMarker.java # 写请求目标标记 + 活动宽限窗(归属区分)
|
||||
│ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8)
|
||||
│ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName)
|
||||
│ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试)
|
||||
│ │ │ ├── LoginOutcome.java # 登录成败判定:状态码 + 重定向目标 error 参数(纯函数)
|
||||
│ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数)
|
||||
│ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照
|
||||
│ │ │ ├── OperationAuditWebFilter.java
|
||||
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
|
||||
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
|
||||
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
|
||||
│ │ │ ├── AuthEndpointAuditWebFilter.java # 认证端点捕获(BeforeSecurityWebFilter,链首)
|
||||
│ │ │ ├── OperationAuditWebFilter.java # /apis/** 捕获(AfterSecurityWebFilter,链尾)
|
||||
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
|
||||
│ │ └── housekeeping/
|
||||
│ │ └── RetentionCleaner.java # 定时清理
|
||||
@@ -68,14 +79,17 @@ plugin-operation-audit/
|
||||
|
||||
## 4. 核心设计决策
|
||||
|
||||
### D1 捕获通道与路径规则
|
||||
### D1 捕获通道与路径规则(P0 修订)
|
||||
|
||||
- 实现一个 `WebFilter`,以 `AfterSecurityWebFilter` 扩展点方式注册(位于 Security 过滤链最后、认证之后,`doFinally` 可读最终响应状态码)。
|
||||
- 双过滤器分治(P0 缺陷实证后修订):
|
||||
- **`/apis/**` 写操作**:`AfterSecurityWebFilter` 扩展点(位于 Security 过滤链最后、认证之后,可获取当前登录用户,`doFinally` 可读最终响应状态码)。
|
||||
- **认证端点 `/login`、`/logout`**:`BeforeSecurityWebFilter` 扩展点(位于 Security 过滤链最前,`SecurityWebFiltersOrder.FIRST`)。P0 根因:表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求——POST /login、/logout 曾永不产生审计记录,登录失败告警生产路径随之失效。
|
||||
- 捕获规则(`CaptureRule`,纯函数):
|
||||
- `POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`
|
||||
- 或路径精确匹配 `/login`、`/logout`
|
||||
- 匿名判断**不在请求期做,而在记录时做**:登录请求开始时用户必然匿名,只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致。
|
||||
- 该规则是产品设计"一条通用规则覆盖全部管理面操作"的唯一必要例外(登录端点不在 `/apis/**` 下),需在产品文档中同步注明。
|
||||
- `shouldCapture`:`POST/PUT/DELETE/PATCH` + 路径前缀 `/apis/`(链尾过滤器消费)
|
||||
- `isAuthEndpoint`:路径精确匹配 `/login`、`/logout`(链首过滤器消费)——两个过滤器按规则分治、互不重叠,不会重复记录
|
||||
- 操作者归属:`/apis/**` 请求从认证上下文解析;认证端点在链首无认证上下文(SecurityContext 由链内更晚位置写入),统一记"未知用户",登录尝试的账号由请求体白名单提取落库 `spec.attemptedUsername`。
|
||||
- 匿名判断**不在请求期做,而在记录时做**(技术方案 D1):只有 `/apis/**` 下认证后仍为匿名主体(401/403 场景)的请求跳过不记——与产品文档"匿名访客请求不记录"一致;认证端点记录不判匿名。
|
||||
- 回归防线:真实 Spring Security 过滤链集成测试(`AuditFilterChainIntegrationTest`,按 Halo `SecurityWebFiltersConfigurer` 的组装方式构建),断言 POST /login(成败)、POST /logout 必产生记录且链尾过滤器不重复记录。
|
||||
|
||||
### D2 审计写入:响应式直写
|
||||
|
||||
@@ -106,6 +120,7 @@ public class AuditLog extends AbstractExtension {
|
||||
| `spec.username` | 按操作者筛选 |
|
||||
| `spec.resourceType` | 按资源类型筛选 |
|
||||
| `spec.method` | 按动作筛选(POST/PUT/DELETE/PATCH) |
|
||||
| `spec.action` | 按语义动作筛选(语义动作标注,捕获时由 method/path 推导落库,如 publish/restore) |
|
||||
| `spec.statusCode` | 按结果筛选 |
|
||||
|
||||
### D4 权限:只读 verbs 收紧
|
||||
@@ -131,8 +146,55 @@ rules:
|
||||
|
||||
### D6 插件设置读取
|
||||
|
||||
- `settings.yaml` 声明两个配置项:审计开关(默认开)、保留天数(默认 90,最小 7)。
|
||||
- 存储于插件关联 ConfigMap,`CaptureRule`/`RetentionCleaner` 经短 TTL 缓存(60s)读取,开关变更最多延迟 1 分钟生效——自用场景可接受,避免为实时生效引入 ConfigMap 监听器。
|
||||
- `settings.yaml` 声明配置项:审计开关(默认开)、保留天数(默认 90,最小 7)、记录字段变更(默认开)。
|
||||
- 存储于插件关联 ConfigMap,`CaptureRule`/`RetentionCleaner`/`ChangeCaptureManager` 经短 TTL 缓存(60s)读取,开关变更最多延迟 1 分钟生效——自用场景可接受,避免为实时生效引入 ConfigMap 监听器。
|
||||
|
||||
### D7 字段级变更捕获(产品设计 V2)
|
||||
|
||||
- 通道复用 D1 过滤器:命中捕获规则的请求经 `ChangeCaptureManager` 在请求期补充两类数据——
|
||||
JSON 请求体(`Content-Length ≤ 256KB`,经 `ServerHttpRequestDecorator` 缓存重建,下游可重复读)
|
||||
与写入前资源状态(`ReactiveExtensionClient.fetch(gvk, name)` 原始 JSON,plural → GVK 经
|
||||
`SchemeManager` 映射)。分块传输/超限/非 JSON 不缓存请求体;DELETE 无请求体也抓旧状态。
|
||||
- diff 语义(`ChangeDiffEngine`,纯函数):PUT 全量 diff;PATCH 双形态——数组 body 按
|
||||
JSON Patch(RFC 6902 ops + JSON Pointer,Halo 扩展路由标准 PATCH)展开,对象 body 按
|
||||
JSON Merge Patch(仅比较 body 字段、显式 null 视为删除);POST 全部记新增;DELETE 全部记移除。
|
||||
- 范围降噪:只比较用户可写面——根级 `apiVersion/kind/status` 跳过,`metadata` 仅保留
|
||||
`name/labels/annotations`;数组与超深子树整体叶子比较。空 group 的核心模型(ConfigMap 等)
|
||||
经源码级验证走 `/api/{version}/{plural}`,本就不在 `/apis/**` 捕获范围。
|
||||
- 输出约束:仅 2xx 落库(失败请求资源未实际变更);单值截断 200 字符、单条记录最多 30 条
|
||||
(汇总条兜底);字段名含 password/secret/token/credential 的值脱敏;捕获全程任何异常
|
||||
静默降级为"仅操作元信息",不影响业务(设计原则 4)。
|
||||
- 存储:`spec.changes`(`ChangeEntry` 列表:field/changeType/oldValue/newValue),
|
||||
不建索引(不参与筛选);升级前历史记录无此字段,详情展示不受影响。
|
||||
|
||||
### D8 系统内部变更(产品设计 V2)
|
||||
|
||||
- 通道(v2.26.1 源码级验证):`ReactiveExtensionClient.watch(Watcher)` 注册到全局
|
||||
Watcher 组合(`ReactiveExtensionClientImpl` 内部 `Watcher.WatcherComposite`),扩展模型
|
||||
create/update/delete 成功落库后同步派发 `onAdd/onUpdate(old, new)/onDelete`(回调在写入
|
||||
链内、boundedElastic 执行)。Halo 自带两层降噪:仅 status 变化或无实际变化的更新
|
||||
不派发事件;GC 真实移除走存储层不产生事件。仅处理 update/delete:内部新建几乎均由
|
||||
HTTP 触发(已被过滤器捕获),不记录以避免重复。
|
||||
- 安全边界:回调运行在业务写入链内,任何异常都会导致业务写入失败,故全程捕获、绝不抛出
|
||||
(设计原则 4);diff 序列化失败降级为跳过该条。
|
||||
- 归属与噪音过滤(依次):
|
||||
1. `AuditLog` 自身(插件写入与保留期清理均排除);
|
||||
2. 模型未注册(无 plural)跳过;
|
||||
3. 插件自身配置 ConfigMap 排除(保存插件设置走 `/apis/plugin.halo.run/v1alpha1/plugins/
|
||||
{name}/json-config`,实际写本插件 ConfigMap,路径无法归属——已按源码验证);
|
||||
4. HTTP 写请求生命周期内的目标资源(`HttpWriteMarker` 目标标记,过滤器对**所有**写方法
|
||||
请求登记,含 `/api/**` 与登录端点):由该请求归属,跳过避免重复记录;
|
||||
5. 设置类资源(ConfigMap/Secret)在写请求活动宽限窗(5s,活动含请求开始与完成)内:
|
||||
设置型端点(保存系统设置 `/apis/console.halo.run/v1alpha1/systemconfigs/{group}`、
|
||||
主题激活等)路径与实际写入资源不一致,无法经目标标记归属,按 HTTP 副产物跳过;
|
||||
6. diff 为空(用户可写面无实际变化,如 reconciler 增删 finalizer 簿记)跳过。
|
||||
- 记录形态:username=`system`;method 取事件类型(PUT=更新/DELETE=删除);action 由方法
|
||||
与规范路径推导(update/delete);resourceType=模型 plural;path 为规范 API 路径
|
||||
(`/apis/{group}/{version}/{plural}/{name}`,空 group 核心模型为
|
||||
`/api/{version}/{plural}/{name}`);statusCode 恒 200(事件在写入成功后派发);无 IP/UA;
|
||||
`spec.changes` 为 PUT/DELETE 语义的全量新旧 diff(复用 D7 引擎的降噪/脱敏/截断规则)。
|
||||
- 开关:`recordSystemChanges`(默认开,随审计总开关),与 HTTP 字段级变更开关
|
||||
(`recordChanges`)相互独立。
|
||||
|
||||
## 5. 关键流程
|
||||
|
||||
@@ -154,6 +216,7 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
```
|
||||
|
||||
- `operatorOf(ctx)`:从订阅上下文读 `SecurityContext`;主体为匿名且路径非登录端点 → 不记录;登录失败 → 记"未知用户"。
|
||||
- 登录成败判定(`LoginOutcome`,纯函数):Halo 2.26 登录端点**表单提交的成功与失败均为 302 重定向**(成功 → `/uc` 或 2FA 页,失败 → `/login?error=invalid-credential&method=...`),仅 XHR/JSON 请求以 200/401 区分成败——不能只看状态码。规则:2xx 成功;3xx 以重定向目标查询串是否含 `error` 参数判定(含无值形式 `error`);其余(401、状态码缺失)失败。失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)的记录标注语义动作 `login-failure`(`spec.action`),列表/详情/CSV 据此显示红色「失败」;HTTP 状态码仍如实记录。告警服务(`LoginFailureAlertService`)按同一判定结果清零/累计,修复了旧版「2xx 即成功」把表单成功登录误计为失败的问题。
|
||||
- 注意 WebFlux 无 ThreadLocal:用户名提取必须经 `transformDeferredContextual` 在订阅上下文完成,不能在 `doFinally` 里直接读 `SecurityContextHolder`。
|
||||
|
||||
### 5.2 资源解析规则(通用,不追求语义完美)
|
||||
@@ -165,7 +228,7 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
| 更深层子资源 | 取前两段,完整路径由 `path` 字段兜底 |
|
||||
| `/login`、`/logout` | `resourceType = "auth"` |
|
||||
|
||||
例:`/apis/api.content.halo.run/v1alpha1/posts/xyz` → `Posts / xyz`。完整性靠 `path` 字段保证,语义化标注留待 V2。
|
||||
例:`/apis/api.content.halo.run/v1alpha1/posts/xyz` → `Posts / xyz`。完整性靠 `path` 字段保证;语义化标注已按 V2 规划实现——捕获时由 method/path 推导语义动作键落库(`spec.action`,`OperationDescription.actionOf`,与前端 `deriveAction` 同一套映射规则),展示描述(`describe`)与语义动作键共用同一推导,历史记录无标注时现场推导不受影响。
|
||||
|
||||
### 5.3 查询链路
|
||||
|
||||
@@ -186,8 +249,13 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
|---|---|
|
||||
| `CaptureRule` | 纯函数单测:路径/方法/登录端点/匿名组合用例 |
|
||||
| `ResourceResolver` | 纯函数单测:典型路径、深层子资源、非 `/apis` 路径 |
|
||||
| `OperationAuditWebFilter` | WebTestClient + 桩 chain(mock `ReactiveExtensionClient`,`StepVerifier`/verify):验证状态码捕获、操作者提取、匿名跳过 |
|
||||
| `AuditRecorder` | mock client:成功直写、失败降级为 warn 且不抛出 |
|
||||
| `ExtensionTargets` | 纯函数单测:`/apis` 与 `/api` 两种形态、子资源、集合级、未注册模型 |
|
||||
| `HttpWriteMarker` | 目标标记登记/解除与引用计数、宽限窗时间语义、设置类资源判定 |
|
||||
| `InternalChangeWatcher` | mock client/SchemeManager/marker/recorder:update/delete 落库与 diff 透传、AuditLog/标记/宽限窗/自身配置/簿记噪音跳过、onAdd 不记录、disposed 跳过、回调异常不外抛 |
|
||||
| `OperationAuditWebFilter` | WebTestClient + 桩 chain(mock `ReactiveExtensionClient`,`StepVerifier`/verify):验证状态码捕获、操作者提取、匿名跳过、捕获上下文透传、写方法请求标记登记(含非捕获路径) |
|
||||
| `ChangeDiffEngine` | 纯函数单测:PUT/PATCH(JSON Patch 与 Merge Patch)/POST/DELETE 语义、范围降噪、脱敏、截断、封顶与空结果 |
|
||||
| `ChangeCaptureManager` | mock client/SchemeManager/设置:请求体缓存与装饰(下游可重复读)、旧状态抓取、开关降级、适用性判定 |
|
||||
| `AuditRecorder` | mock client:成功直写、失败降级为 warn 且不抛出、字段变更落库/跳过条件 |
|
||||
| `RetentionCleaner` | mock client + 固定时钟:过期批量删除、空批终止 |
|
||||
| 构建与回归 | 每里程碑 `./gradlew build` 全绿(AGENTS.md 约定) |
|
||||
| UI | MVP 仅保证构建通过,不引入组件测试(页面为标准实体列表,逻辑薄) |
|
||||
@@ -219,8 +287,18 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
|
||||
> **落地结论(2026-11-21 实现)**:
|
||||
> - #2 已按 v2.26.1 源码证实(`FieldSelectorConverter` 仅支持 =/!=/IN)→ 已启用自有查询端点
|
||||
> `GET /apis/audit.example.com/v1alpha1/auditlogs/-/query`(`AuditQueryEndpoint`,索引 Query + 分页,无内存分页)。
|
||||
> `GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/query`(`AuditQueryEndpoint`,索引 Query + 分页,无内存分页)。
|
||||
> - #3 直接采用 Reactor 调度预案(`RetentionCleaner`),不赌 `@Scheduled` 可用性。
|
||||
> - #4 已按源码确认:实现 `AfterSecurityWebFilter`(`WebFilter` + `ExtensionPoint`)并以 `@Component` 注册即可。
|
||||
> - 2.26.1 的索引注册 API 为 `SchemeManager.register(Class, Consumer<IndexSpecs>)` + `IndexSpecs.single(...)`;
|
||||
> `QueryFactory`/`IndexAttributeFactory` 已 @Deprecated,实现使用 `Queries`/`Condition` 新体系。
|
||||
> - 字段级变更(D7):源码级证实空 group 核心模型路由为 `/api/{version}/{plural}`
|
||||
> (`ExtensionRouterFunctionFactory.PathPatternGenerator.buildExtensionPathPattern`),
|
||||
> 不在 `/apis/**` 捕获范围;扩展路由自带 PATCH(JSON Patch)与 PUT(整体替换),
|
||||
> diff 引擎按 body 形态分别处理;旧状态获取用 `fetch(gvk, name)`(`getJsonExtension` 已弃用)。
|
||||
> - 系统内部变更(D8):源码级证实 `ReactiveExtensionClientImpl` 经内部
|
||||
> `Watcher.WatcherComposite` 派发事件(create/update/delete 成功后、仅 status 变化或
|
||||
> 无变化不派发、GC 走存储层无事件);`addWatcher` 拒绝 disposed 监听并按 equals 去重,
|
||||
> dispose hook 用于插件停止时自行移除;插件配置保存端点
|
||||
> `json-config` / 系统设置端点 `systemconfigs` 内部实际写 ConfigMap(空 group),
|
||||
> 是宽限窗规则的直接依据。
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
# 操作审计插件测试报告
|
||||
|
||||
> 依据 [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)。
|
||||
|
||||
## 可复核结果
|
||||
|
||||
```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 逐项检查,截图存于仓库 `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-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` 的实测验证完成。
|
||||
|
||||
## 附:测试环境残留与清理
|
||||
|
||||
- 测试实例保留运行于 `http://127.0.0.1:8099`(admin / Sm0keTest2026,
|
||||
数据目录 `C:/Users/Windows11/.halo-smoke-test/workdir`,可丢弃,与生产数据无任何关联);
|
||||
- 第三轮联调中将 auditor3 密码重置为 `AuditR3.2026`(供只读角色矩阵复测),
|
||||
残留测试用户 auditor3(role-template-audit-view)保留于实例中;
|
||||
- 已恢复干净版插件 JAR 并确认无诊断日志残留(重启后 0 条 AUDIT-DIAG);
|
||||
- 源码工作区干净,仅新增截图证据目录 `gui-test-screenshots/`(未纳入版本控制)。
|
||||
@@ -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)准备版本说明、截图、许可证和应用市场资料。
|
||||
@@ -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:
|
||||
```
|
||||
|
||||
命令失败、测试被跳过或环境与声明兼容范围不一致时,应明确记录,不能用“构建成功”概括未执行的验证。
|
||||
@@ -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
@@ -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" %*
|
||||
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 |
@@ -9,9 +9,30 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
|
||||
|
||||
- **操作记录**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH),
|
||||
一条通用规则覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作;
|
||||
另捕获 `/login`、`/logout`(登录成功/失败/登出)。
|
||||
- **审计日志查看**:Console 左侧菜单"操作审计"——列表 + 七维筛选(操作者/资源类型/动作/结果/
|
||||
时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。
|
||||
另捕获 `/login`、`/logout`(登录成功/失败/登出),登录请求白名单提取尝试的用户名落库
|
||||
(`spec.attemptedUsername`,密码等其余字段绝不落库,登录失败时操作者记"未知用户")。
|
||||
- **系统内部变更**:定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,
|
||||
执行者记为 "system"(Console 展示为"系统");只记录用户可写面有实际变化的更新/删除,
|
||||
并附字段级新旧值,与页面/API 操作区分归属、不重复记录。
|
||||
- **语义动作标注**:捕获时由方法/路径推导语义动作键落库(`spec.action`,如
|
||||
登录/新建/修改/删除/发布/恢复/启用),注册索引后支持按语义动作筛选;
|
||||
中文操作描述由同一套推导生成,贯穿列表、详情与导出 CSV,历史记录同样适用。
|
||||
- **审计日志查看**:Console 左侧菜单"操作审计"——列表 + 八维筛选(操作者/资源类型/动作/
|
||||
语义动作/结果/时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。
|
||||
有资源名称的记录行内提供「历史」快捷动作:一键预填资源类型 + 资源名关键字并刷新列表,
|
||||
直接回答"这个资源被谁改过"(功能评审 P1-1)。
|
||||
- **导出 CSV**:列表页「导出」按钮按当前筛选条件导出全部记录——后端全量流式生成
|
||||
(UTF-8 BOM + `\r\n`,Excel/WPS 双击打开中文不乱码),列与界面一致(操作时间、操作者、
|
||||
尝试用户、动作、资源类型、资源名称、路径、操作描述、变更、结果、状态码、来源 IP、
|
||||
User-Agent),含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。
|
||||
- **登录失败告警**:统计窗口内登录失败达到阈值时向 Webhook 地址异步推送 JSON 告警
|
||||
(默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零;内容含尝试的用户名,
|
||||
可区分定向撞库与无差别扫描);独立于审计开关,在插件设置「告警通知」中配置(默认关闭)。
|
||||
Webhook 地址凭据存于 Halo `Secret`(设置仅保存 Secret 引用,支持含 `access_token` 等
|
||||
凭据的地址);发送前对地址做 SSRF 防护校验(http(s) 白名单、拒绝内网/环回/链路本地/
|
||||
云元数据等受限地址段,并钉定校验通过的地址建连以防范 DNS rebinding)。
|
||||
该区提供「发送测试告警」入口:以 `type: "test"` 测试消息向已保存的 Webhook 地址推送并
|
||||
同步反馈发送结果,无需等待真实告警即可验证配置是否可用。
|
||||
- **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录,
|
||||
启动时补跑一次。
|
||||
- **权限**:默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`
|
||||
@@ -35,41 +56,147 @@ Console「插件 → 操作审计 → 设置」:
|
||||
| 配置项 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| 启用审计 | 开 | 关闭后不再记录新日志,已有记录仍可查询 |
|
||||
| 记录字段变更 | 开 | 对成功的新建/修改/删除操作记录字段级新旧值(敏感字段自动脱敏) |
|
||||
| 记录系统内部变更 | 开 | 记录定时发布等非页面操作触发的资源变更(执行者记为 system) |
|
||||
| 保留天数 | 90 | 最小 7 天;过期记录每日自动清理 |
|
||||
| 启用登录失败告警 | 关 | 统计窗口内失败达到阈值时推送 Webhook 告警(独立于审计开关) |
|
||||
| Webhook 地址(Secret) | 空 | 选择或创建存放 Webhook 地址的 Secret(键 `webhookUrl`);地址仅存于 Secret,可含 access_token 等凭据,JSON POST 异步推送 |
|
||||
| 发送测试告警(按钮) | - | 向已保存的 Webhook 地址推送 `type: "test"` 测试消息并直接反馈发送结果(不保存配置值,仅超级管理员可用) |
|
||||
| 触发阈值(次) | 5 | 统计窗口内累计登录失败达到该次数即触发一次告警 |
|
||||
| 统计窗口(分钟) | 5 | 失败次数的累计窗口;告警后窗口重开,登录成功立即清零 |
|
||||
|
||||
设置经 60 秒 TTL 缓存读取,变更最多延迟 1 分钟生效。
|
||||
|
||||
## 落地前需要修改的占位
|
||||
**告警负载**:通用 JSON 结构(`type` / `title` / `content` / `timestamp` / `data`),
|
||||
以 JSON POST 异步推送,超时 10 秒、失败不重试仅记日志;发送前经 SSRF 防护校验,
|
||||
受限地址(内网/环回/元数据等)在建立连接前即拒绝,校验失败与推送失败同样只记日志
|
||||
(日志只记主机名,不记可能含凭据的完整地址):
|
||||
|
||||
- **group 占位**:`audit.example.com` 为 group 占位(技术方案),落地前请全局替换为自有
|
||||
域名反写(如 `audit.example.com` → `audit.<你的域名>`)。涉及位置:
|
||||
`AuditLog.GROUP`、`AuditQueryEndpoint`、`role-template.yaml`、`ui/src/views/AuditLogList.vue`
|
||||
的 `QUERY_ENDPOINT`。
|
||||
```json
|
||||
{
|
||||
"type": "login-failure",
|
||||
"title": "操作审计告警:登录失败",
|
||||
"content": "5 分钟内出现 5 次登录失败,最近一次来自 1.2.3.4(Mozilla/5.0 ...),
|
||||
尝试的账号:admin。可在 Console「操作审计」查看详情。",
|
||||
"timestamp": "2026-11-21T12:34:56Z",
|
||||
"data": {
|
||||
"failures": 5,
|
||||
"windowMinutes": 5,
|
||||
"remoteIp": "1.2.3.4",
|
||||
"userAgent": "...",
|
||||
"attemptedUsername": "admin"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`attemptedUsername` 为登录请求体中白名单提取的尝试用户名,提取失败时为 `null`。
|
||||
|
||||
「发送测试告警」以相同结构推送 `type: "test"` 的测试消息(接收方可识别为测试消息),
|
||||
推送结果同步返回并提示到设置页(成功/失败 + 原因摘要),同时反馈到运行日志;
|
||||
Webhook Secret 未配置、Secret 缺少 `webhookUrl` 键时提示先完成配置。
|
||||
|
||||
不内置钉钉、企业微信、飞书等平台的专属消息格式适配,需要时可在中转服务侧转换
|
||||
(地址凭据已可安全存于 Secret,直连含 token 的地址在传输层可行,消息格式仍需接收方兼容通用 JSON)。
|
||||
|
||||
## 模型 group 与权限标识
|
||||
|
||||
- **group**:已按"自有域名反写(`audit.<你的域名>`)"约定定为 `audit.guichumo.com`。
|
||||
唯一事实来源是 `AuditLog.GROUP` 常量(查询端点、测试挂载路径均引用它);
|
||||
`role-template.yaml` 的 `apiGroups` 与 build.gradle `openApi.groupingRules.pathsToMatch`
|
||||
需与其保持一致。⚠️ group 是已落库数据的身份标识,一旦插件启用并
|
||||
产生审计记录,再改 group 会导致旧记录不可见,届时请勿随意变更。
|
||||
- **UI 权限标识**:`plugin:operation-audit:view`(role-template.yaml 与 `ui/src/index.ts`
|
||||
保持一致即可,如需改名请两处同步)。
|
||||
|
||||
## 已知局限(对应产品设计第 7 节)
|
||||
|
||||
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2),记为"未知用户"。
|
||||
- 系统内部触发的资源变更(如定时发布)暂不记录。
|
||||
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)
|
||||
不记录(几乎均伴随页面/API 操作,已被过滤器捕获)。
|
||||
- 系统内部变更的描述由事件类型推导(更新/删除),无法像页面操作那样区分"定时发布/恢复"
|
||||
等具体语义;具体改了什么以字段级 diff 为准。
|
||||
- 部分 Console 端点(保存系统设置、插件配置、主题激活等)的路径指向端点本身、实际写入
|
||||
ConfigMap/Secret,此类写入由宽限窗按 HTTP 副产物处理,不再重复记录为 system;
|
||||
其他极少数"路径与实际写入资源不一致"的端点,其副产物可能记为 system(已知取舍)。
|
||||
- reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不会产生记录(用户可写面
|
||||
无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见)。
|
||||
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),
|
||||
但不会被语义动作筛选命中。
|
||||
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口;角色模板已对普通授权
|
||||
角色收紧到 `get`/`list`)。
|
||||
- 审计写入失败静默降级为运行日志,不阻塞业务操作。
|
||||
- 来源 IP 取自 Halo HTTP 服务器解析后的地址(含 forwarding 配置):
|
||||
反向代理未配置 forwarded header 时,记录到的是代理 IP。
|
||||
反向代理未配置 forwarded header 时,记录到的是代理 IP;系统内部变更记录无 IP/UA。
|
||||
- **Windows 升级注意事项**:插件运行期间其 JAR 被进程锁定(Windows 文件锁),
|
||||
`upgrade` API 报 500(`FileSystemException: 另一个程序正在使用此文件`),停用插件后
|
||||
句柄也不释放。Windows 站点升级本插件需停服换 JAR 后重启;Linux/macOS 无此限制。
|
||||
|
||||
## 技术说明
|
||||
|
||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经 `AfterSecurityWebFilter` 扩展点(认证之后,
|
||||
`doFinally` 读最终状态码);存储为自定义 Extension + 索引查询,全程响应式非阻塞。
|
||||
- 查询走插件自有端点 `GET /apis/audit.example.com/v1alpha1/auditlogs/-/query`——
|
||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经双过滤器扩展点分治:`/apis/**` 写操作走
|
||||
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证端点 `/login`、
|
||||
`/logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器命中
|
||||
请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求,认证端点
|
||||
必须在链首承接(操作者记"未知用户",登录尝试账号由请求体白名单提取)。存储为自定义
|
||||
Extension + 索引查询,全程响应式非阻塞。
|
||||
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
|
||||
扩展模型写入(回调在写入链内执行,全程捕获异常不影响业务):Halo 对仅 status 变化
|
||||
或无实际变化的更新不派发事件,回收站清理走存储层不产生事件,天然降噪;HTTP 写请求
|
||||
经 `HttpWriteMarker` 登记目标资源与活动时间,用于区分归属。
|
||||
- 查询走插件自有端点 `GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/query`——
|
||||
经源码验证,Halo 原生列表 API 的 fieldSelector 仅支持等值操作符,不支持时间区间与
|
||||
模糊匹配(技术方案风险项 #2 证实并按预案启用自有端点)。
|
||||
模糊匹配(技术方案风险项 #2 证实并按预案启用自有端点)。导出走同端点类的
|
||||
`GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/export`:筛选参数与 query 完全一致
|
||||
(共用 `AuditLogFilters`),按时间升序分批(每批 200,与保留期清理同款迭代模式)
|
||||
遍历全量,流式输出 CSV——升序保证导出期间并发写入不打乱分页边界。
|
||||
- 定时清理采用 Reactor 调度方案(技术方案风险项 #3 预案),不依赖 `@Scheduled`
|
||||
在插件上下文的可用性。
|
||||
- 关于测试:`./gradlew test`(当前 50 个用例)覆盖捕获规则、资源解析、快照、直写降级、
|
||||
过滤器行为、查询端点参数校验、设置缓存与保留期清理;Console UI 以类型检查 + 构建通过
|
||||
为准(技术方案 §7,MVP 不引入组件测试)。
|
||||
- **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` 结束,
|
||||
经 `CaptureRule.isLoginAttempt` 判定),`LoginFailureAlertService` 维护阈值窗口状态
|
||||
(告警后重开窗口防轰炸,登录成功清零;状态为单例计数,无内存队列),设置经
|
||||
`AlertSettingProvider`(60s TTL 缓存)读取、独立于审计开关;Webhook 地址存于
|
||||
Halo `Secret`(键 `webhookUrl`,设置仅存引用名,fail closed:引用缺失/Secret 缺键
|
||||
绝不发送);`AlertWebhookSender` 以 JSON POST 异步推送(fire-and-forget,超时
|
||||
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`(当前 244 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
|
||||
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、登录尝试用户名提取
|
||||
(表单/JSON/白名单/脱敏兜底/降级)、查询端点参数校验、导出 CSV
|
||||
(BOM/表头/转义/注入防护/分批取数)、操作描述与语义动作标注推导(与前端
|
||||
describeOperation / deriveAction 用例一一对应)、设置缓存与保留期清理、登录失败告警
|
||||
(阈值窗口推进/告警防轰炸/成功清零/设置归一/Secret 地址解析 fail closed/真实 HTTP
|
||||
推送与静默降级/建连钉定证明/Webhook 结果化推送与测试端点反馈/测试负载结构)、
|
||||
出站地址守卫(结构校验/危险地址段枚举/IPv4 映射内嵌/日志主机名卫生);
|
||||
Console UI 以 vitest 断言路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)、
|
||||
生成客户端链路形态(不手写端点/不裸 fetch)、导出下载链路 + 类型检查 + 构建通过为准
|
||||
(技术方案 §7,MVP 不引入组件测试)。
|
||||
|
||||
## 开发
|
||||
|
||||
@@ -80,4 +207,16 @@ cd plugin-operation-audit
|
||||
./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 构建)。
|
||||
|
||||
@@ -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) {
|
||||
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')
|
||||
shouldRunAfter tasks.named('processResources')
|
||||
// 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar
|
||||
// 前端产物带 hash 文件名,先清空目标目录避免历史版本残留进 jar;
|
||||
// 同时清掉旧构建可能残留的 console/ 目录,防止过期产物被打进 jar
|
||||
doFirst {
|
||||
delete layout.buildDirectory.dir('resources/main/ui')
|
||||
delete layout.buildDirectory.dir('resources/main/console')
|
||||
}
|
||||
}
|
||||
@@ -61,3 +64,45 @@ tasks.named('generatePluginComponentsIdx') {
|
||||
halo {
|
||||
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'
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-4
@@ -6,6 +6,7 @@ import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.index.IndexSpecs;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
import run.halo.operationaudit.audit.InternalChangeWatcher;
|
||||
import run.halo.operationaudit.housekeeping.RetentionCleaner;
|
||||
import run.halo.app.plugin.BasePlugin;
|
||||
import run.halo.app.plugin.PluginContext;
|
||||
@@ -15,9 +16,10 @@ import run.halo.app.plugin.PluginContext;
|
||||
*
|
||||
* <p>负责插件生命周期:
|
||||
* <ul>
|
||||
* <li>启动时注册 {@code AuditLog} 模型与索引(操作者/资源类型/动作/结果/资源名称/路径,
|
||||
* 时间索引由 Halo 为所有模型自动注册),并启动保留期清理调度;</li>
|
||||
* <li>停止时注销模型、取消清理调度。</li>
|
||||
* <li>启动时注册 {@code AuditLog} 模型与索引(操作者/资源类型/动作/语义动作/结果/
|
||||
* 资源名称/路径,时间索引由 Halo 为所有模型自动注册),启动保留期清理调度,
|
||||
* 并注册系统内部变更监听(定时发布等非 HTTP 触发的变更,执行者记 "system");</li>
|
||||
* <li>停止时注销模型、取消清理调度、移除内部变更监听。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Component
|
||||
@@ -25,12 +27,14 @@ public class OperationAuditPlugin extends BasePlugin {
|
||||
|
||||
private final SchemeManager schemeManager;
|
||||
private final RetentionCleaner retentionCleaner;
|
||||
private final InternalChangeWatcher internalChangeWatcher;
|
||||
|
||||
public OperationAuditPlugin(PluginContext pluginContext, SchemeManager schemeManager,
|
||||
RetentionCleaner retentionCleaner) {
|
||||
RetentionCleaner retentionCleaner, InternalChangeWatcher internalChangeWatcher) {
|
||||
super(pluginContext);
|
||||
this.schemeManager = schemeManager;
|
||||
this.retentionCleaner = retentionCleaner;
|
||||
this.internalChangeWatcher = internalChangeWatcher;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -39,15 +43,18 @@ public class OperationAuditPlugin extends BasePlugin {
|
||||
addIndex(indexSpecs, "spec.username", String.class, log -> log.getSpec().getUsername());
|
||||
addIndex(indexSpecs, "spec.resourceType", String.class, log -> log.getSpec().getResourceType());
|
||||
addIndex(indexSpecs, "spec.method", String.class, log -> log.getSpec().getMethod());
|
||||
addIndex(indexSpecs, "spec.action", String.class, log -> log.getSpec().getAction());
|
||||
addIndex(indexSpecs, "spec.statusCode", Integer.class, log -> log.getSpec().getStatusCode());
|
||||
addIndex(indexSpecs, "spec.resourceName", String.class, log -> log.getSpec().getResourceName());
|
||||
addIndex(indexSpecs, "spec.path", String.class, log -> log.getSpec().getPath());
|
||||
});
|
||||
retentionCleaner.start();
|
||||
internalChangeWatcher.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
internalChangeWatcher.stop();
|
||||
retentionCleaner.stop();
|
||||
var gvk = gvkOf();
|
||||
schemeManager.fetch(gvk).ifPresent(schemeManager::unregister);
|
||||
|
||||
+31
@@ -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);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import java.time.Duration;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.Secret;
|
||||
import run.halo.app.plugin.ReactiveSettingFetcher;
|
||||
|
||||
/**
|
||||
* 告警设置的短 TTL 缓存读取(与审计设置 {@code AuditSettingProvider} 同款模式,技术方案 D6),
|
||||
* 以及 Webhook 地址的 Secret 解析。
|
||||
*
|
||||
* <p>凭据安全(官方《敏感数据与出站请求》指南):Setting 只存 Secret 引用名,
|
||||
* 真实 Webhook 地址(可能内嵌 access_token)存于 Halo {@code Secret},经
|
||||
* {@link ReactiveExtensionClient} 按需读取;解析失败以错误信号报出(调用方决定
|
||||
* 降级方式:真实告警路径静默跳过,测试告警端点转为 400 提示),消息只含引用名
|
||||
* 与键名,绝不携带 Secret 内容。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AlertSettingProvider {
|
||||
|
||||
/** 缓存有效期(与审计设置缓存一致)。 */
|
||||
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 ReactiveExtensionClient client;
|
||||
|
||||
/** TTL 缓存条目;包内可见以便测试构造过期条目。 */
|
||||
record CacheEntry(AlertSettings value, long expireAtNanos) {
|
||||
boolean expiredAt(long nowNanos) {
|
||||
return nowNanos >= expireAtNanos;
|
||||
}
|
||||
}
|
||||
|
||||
volatile CacheEntry cache;
|
||||
|
||||
/**
|
||||
* 获取当前告警设置(TTL 内直接命中缓存)。
|
||||
*
|
||||
* <p>返回的 Mono 永不为空、永不报错:任何异常均回退默认值(告警关闭)。
|
||||
*/
|
||||
public Mono<AlertSettings> get() {
|
||||
var entry = cache;
|
||||
if (entry != null && !entry.expiredAt(System.nanoTime())) {
|
||||
return Mono.just(entry.value());
|
||||
}
|
||||
return fetcher.fetch(AlertSettings.GROUP, AlertSettings.class)
|
||||
.onErrorResume(e -> {
|
||||
log.warn("Failed to load alert settings, fall back to defaults", e);
|
||||
return Mono.just(AlertSettings.defaults());
|
||||
})
|
||||
.defaultIfEmpty(AlertSettings.defaults())
|
||||
.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")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
/**
|
||||
* 告警通知设置(存储于插件 ConfigMap 的 {@code alerts} 组,独立于审计设置组)。
|
||||
*
|
||||
* <p>凭据安全(官方《敏感数据与出站请求》指南):Webhook 地址可能内嵌 access_token
|
||||
* 等凭据,本记录只持有 Halo {@code Secret} 的引用名({@code webhookSecretName}),
|
||||
* 真实地址存于 Secret 的 {@code webhookUrl} 键,由
|
||||
* {@link AlertSettingProvider#webhookUrl()} 按需解析,绝不落 ConfigMap、日志或状态。
|
||||
*
|
||||
* <p>取值经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值。
|
||||
*/
|
||||
public record AlertSettings(Boolean enabled, String webhookSecretName, Integer thresholdCount,
|
||||
Integer windowMinutes) {
|
||||
|
||||
/** ConfigMap 中的配置组名(settings.yaml 的告警通知表单组)。 */
|
||||
public static final String GROUP = "alerts";
|
||||
|
||||
/** 告警开关默认值:默认关闭,配置 Webhook 后显式开启(告警属可选旁路功能)。 */
|
||||
public static final boolean DEFAULT_ENABLED = false;
|
||||
|
||||
/** 默认触发阈值:统计窗口内登录失败次数。 */
|
||||
public static final int DEFAULT_THRESHOLD_COUNT = 5;
|
||||
|
||||
/** 默认统计窗口(分钟)。 */
|
||||
public static final int DEFAULT_WINDOW_MINUTES = 5;
|
||||
|
||||
public boolean enabledOrDefault() {
|
||||
return enabled != null && enabled;
|
||||
}
|
||||
|
||||
/** 归一 Secret 引用名:空白返回 null(未配置,调用方静默跳过发送)。 */
|
||||
public String webhookSecretNameOrDefault() {
|
||||
if (webhookSecretName == null || webhookSecretName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return webhookSecretName.trim();
|
||||
}
|
||||
|
||||
/** 触发阈值:小于 1 视为非法回退默认。 */
|
||||
public int thresholdCountOrDefault() {
|
||||
if (thresholdCount == null || thresholdCount < 1) {
|
||||
return DEFAULT_THRESHOLD_COUNT;
|
||||
}
|
||||
return thresholdCount;
|
||||
}
|
||||
|
||||
/** 统计窗口(分钟):小于 1 视为非法回退默认。 */
|
||||
public int windowMinutesOrDefault() {
|
||||
if (windowMinutes == null || windowMinutes < 1) {
|
||||
return DEFAULT_WINDOW_MINUTES;
|
||||
}
|
||||
return windowMinutes;
|
||||
}
|
||||
|
||||
public static AlertSettings defaults() {
|
||||
return new AlertSettings(DEFAULT_ENABLED, null, DEFAULT_THRESHOLD_COUNT,
|
||||
DEFAULT_WINDOW_MINUTES);
|
||||
}
|
||||
}
|
||||
+106
@@ -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";
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.netty.http.client.HttpClient;
|
||||
|
||||
/**
|
||||
* 告警 Webhook 推送器:向配置地址异步 POST JSON 负载。
|
||||
*
|
||||
* <p>fire-and-forget(产品设计原则 4):超时 10 秒后放弃,失败(网络错误、非 2xx 响应、
|
||||
* 地址非法)仅记 warn 日志,不重试、不抛出,绝不影响登录与审计主流程。
|
||||
*
|
||||
* <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
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AlertWebhookSender {
|
||||
|
||||
/** 发送超时:告警为旁路功能,超时即放弃(不重试)。 */
|
||||
private static final Duration TIMEOUT = Duration.ofSeconds(10);
|
||||
|
||||
private final OutboundUrlGuard guard;
|
||||
|
||||
/** 异步推送 JSON 负载;任何失败仅记 warn 日志(只记主机名,不记可能含凭据的地址)。 */
|
||||
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 负载并返回结果(功能评审 P0-2):成功为接收方 2xx;超时、网络错误、
|
||||
* 非 2xx、地址校验失败等任何失败均归一为失败结果,绝不抛出、绝不重试。
|
||||
*
|
||||
* <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)
|
||||
.bodyValue(payload)
|
||||
.retrieve()
|
||||
.toBodilessEntity())
|
||||
.timeout(TIMEOUT)
|
||||
.map(response -> AlertSendResult.ok(response.getStatusCode().value()))
|
||||
.onErrorResume(e -> Mono.just(AlertSendResult.failure(e)));
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import java.time.Duration;
|
||||
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 reactor.core.publisher.Mono;
|
||||
import run.halo.operationaudit.audit.RequestSnapshot;
|
||||
|
||||
/**
|
||||
* 登录失败告警(产品设计 V2+「告警通知」):统计窗口内登录失败达到阈值时向 Webhook
|
||||
* 推送一次 JSON 告警。
|
||||
*
|
||||
* <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}):
|
||||
* 登录成功立即清零计数,失败累计。成败由过滤器经 {@code LoginOutcome} 判定后传入——
|
||||
* 表单登录的成功与失败均为 302 重定向,以重定向目标是否含 {@code error} 参数区分,
|
||||
* 不能只看状态码。告警后重开窗口(同一攻击波次不会连环轰炸,下次告警需再次达到阈值);
|
||||
* 窗口过期同样重开,无失败时不累计。
|
||||
*
|
||||
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
|
||||
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
|
||||
*
|
||||
* <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关
|
||||
* 相互独立;Webhook 地址凭据存于 Halo Secret(Setting 只存引用),解析失败静默跳过。
|
||||
* 任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class LoginFailureAlertService {
|
||||
|
||||
private final AlertSettingProvider settingProvider;
|
||||
private final AlertWebhookSender sender;
|
||||
|
||||
private final Object stateLock = new Object();
|
||||
|
||||
/** 阈值窗口状态(窗口起点与累计失败数);包内可见以便测试直接构造状态。 */
|
||||
Instant windowStart;
|
||||
int failureCount;
|
||||
|
||||
/**
|
||||
* 登录结果回调:仅处理 POST /login 请求(成功清零计数,失败累计告警)。
|
||||
* 成败由调用方(捕获过滤器)经 {@code LoginOutcome} 判定后传入,本服务不做
|
||||
* 状态码推断。任何失败静默降级,不影响调用方。
|
||||
*
|
||||
* @param success 登录是否成功(表单登录 302 重定向目标含 error 参数或
|
||||
* 响应 4xx/5xx 为失败;2xx 与成功重定向为成功)
|
||||
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
|
||||
* 提取失败为 null)
|
||||
*/
|
||||
public void onLoginResult(RequestSnapshot snapshot, boolean success,
|
||||
String attemptedUsername) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> handle(settings, snapshot, success, attemptedUsername, Instant.now()),
|
||||
e -> log.warn("Failed to load alert settings, skip login alert for {}",
|
||||
snapshot.getFullPath(), e));
|
||||
}
|
||||
|
||||
/**
|
||||
* 告警入口:开关开启时先解析 Webhook 地址(凭据存于 Halo Secret,见
|
||||
* {@link AlertSettingProvider#webhookUrl(AlertSettings)}),未配置/读取失败则
|
||||
* 静默跳过(既不计数也不告警,与旧版"无地址不计数"语义一致);地址可用后进入
|
||||
* 阈值窗口判定。now 由调用方传入(测试可控)。
|
||||
*
|
||||
* <p>handle 包内可见以便测试直接驱动。
|
||||
*/
|
||||
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success,
|
||||
String attemptedUsername, Instant now) {
|
||||
try {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
return;
|
||||
}
|
||||
settingProvider.webhookUrl(settings)
|
||||
.onErrorResume(e -> {
|
||||
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());
|
||||
int failures;
|
||||
synchronized (stateLock) {
|
||||
if (success) {
|
||||
// 登录成功立即清零:零星输错密码不应累积
|
||||
windowStart = null;
|
||||
failureCount = 0;
|
||||
return;
|
||||
}
|
||||
if (windowStart == null || now.isAfter(windowStart.plus(window))) {
|
||||
windowStart = now;
|
||||
failureCount = 0;
|
||||
}
|
||||
failureCount++;
|
||||
if (failureCount < settings.thresholdCountOrDefault()) {
|
||||
return;
|
||||
}
|
||||
failures = failureCount;
|
||||
// 达到阈值:触发告警并重开窗口,下次告警需再次达到阈值(防轰炸)
|
||||
windowStart = now;
|
||||
failureCount = 0;
|
||||
}
|
||||
sender.send(url, buildPayload(failures, settings.windowMinutesOrDefault(),
|
||||
snapshot.getRemoteIp(), snapshot.getUserAgent(), attemptedUsername, now));
|
||||
} catch (Exception e) {
|
||||
// 告警为旁路功能,任何异常静默降级,绝不影响登录主流程
|
||||
log.warn("Failed to handle login failure alert for {}",
|
||||
snapshot.getFullPath(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装通用 JSON 告警负载:type/title/content 供消息类接收方直接展示,
|
||||
* data 供程序化消费方取结构化字段。
|
||||
*/
|
||||
static Map<String, Object> buildPayload(int failures, int windowMinutes, String remoteIp,
|
||||
String userAgent, String attemptedUsername, Instant timestamp) {
|
||||
var content = windowMinutes + " 分钟内出现 " + failures + " 次登录失败,最近一次来自 "
|
||||
+ remoteIp + (userAgent != null && !userAgent.isBlank()
|
||||
? "(" + userAgent + ")" : "")
|
||||
+ (attemptedUsername != null && !attemptedUsername.isBlank()
|
||||
? ",尝试的账号:" + attemptedUsername : "")
|
||||
+ "。可在 Console「操作审计」查看详情。";
|
||||
var data = new LinkedHashMap<String, Object>();
|
||||
data.put("failures", failures);
|
||||
data.put("windowMinutes", windowMinutes);
|
||||
data.put("remoteIp", remoteIp);
|
||||
data.put("userAgent", userAgent);
|
||||
data.put("attemptedUsername", attemptedUsername);
|
||||
var payload = new LinkedHashMap<String, Object>();
|
||||
payload.put("type", "login-failure");
|
||||
payload.put("title", "操作审计告警:登录失败");
|
||||
payload.put("content", content);
|
||||
payload.put("timestamp", timestamp.toString());
|
||||
payload.put("data", data);
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
+246
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
@@ -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());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,8 @@ import run.halo.app.extension.GVK;
|
||||
plural = "auditlogs", singular = "auditlog")
|
||||
public class AuditLog extends AbstractExtension {
|
||||
|
||||
/** 模型 group(占位域名反写,落地时替换为自有域名,见 README)。 */
|
||||
public static final String GROUP = "audit.example.com";
|
||||
/** 模型 group(自有域名反写约定:audit.<你的域名>,见 README)。 */
|
||||
public static final String GROUP = "audit.guichumo.com";
|
||||
|
||||
private AuditLogSpec spec;
|
||||
}
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.PageRequestImpl;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
|
||||
/**
|
||||
* 审计日志 CSV 导出(按筛选条件导出,设计文档 V2 规划项)。
|
||||
*
|
||||
* <p>按时间升序分批遍历(每批 {@value #EXPORT_BATCH_SIZE} 条,循环至不足一批,
|
||||
* 与 {@code RetentionCleaner} 的分批模式一致)拉取筛选命中的全部记录,
|
||||
* 流式拼接 CSV 行输出,内存仅保留当前批。升序的原因:新记录时间戳更大、
|
||||
* 总是排在末尾,导出期间并发写入不会打乱分页边界。
|
||||
*
|
||||
* <p>CSV 采用 UTF-8 BOM + \r\n 行结束符,Excel/WPS 双击打开中文不乱码;
|
||||
* 字段做引号转义与公式注入防护(见 {@link #escape})。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuditLogCsvExporter {
|
||||
|
||||
/** 每批查询条数。 */
|
||||
static final int EXPORT_BATCH_SIZE = 200;
|
||||
|
||||
/**
|
||||
* CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要,
|
||||
* "尝试用户"列为登录尝试的用户名,功能评审 P0-1)。
|
||||
*/
|
||||
private static final String CSV_HEADER =
|
||||
"操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
|
||||
private static final DataBufferFactory BUFFER_FACTORY =
|
||||
DefaultDataBufferFactory.sharedInstance;
|
||||
|
||||
/** 操作时间列格式(服务器时区,与 UI 列表展示格式一致)。 */
|
||||
private static final DateTimeFormatter TIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
|
||||
|
||||
/** 导出文件名中的时间戳(不能含冒号/空格等文件名非法字符)。 */
|
||||
private static final DateTimeFormatter FILENAME_TIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault());
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
|
||||
/** 导出为 CSV 附件下载响应(流式输出)。 */
|
||||
public Mono<ServerResponse> exportResponse(ListOptions options) {
|
||||
var filename = "audit-logs-" + FILENAME_TIME_FORMATTER.format(Instant.now()) + ".csv";
|
||||
return ServerResponse.ok()
|
||||
.contentType(MediaType.parseMediaType("text/csv;charset=UTF-8"))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
|
||||
.body(csvLines(options)
|
||||
.map(line -> BUFFER_FACTORY.wrap(line.getBytes(StandardCharsets.UTF_8))),
|
||||
DataBuffer.class);
|
||||
}
|
||||
|
||||
private Flux<String> csvLines(ListOptions options) {
|
||||
// 首行带 UTF-8 BOM;每行统一以 \r\n 结束(Excel/WPS 友好)
|
||||
return Flux.concat(
|
||||
Flux.just("\uFEFF" + CSV_HEADER),
|
||||
fetchAll(options).map(this::toCsvLine))
|
||||
.map(line -> line + "\r\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 按时间升序分批遍历筛选命中的全部记录:每批 {@value #EXPORT_BATCH_SIZE} 条,
|
||||
* 不足一批说明已取完(满一批时可能恰好取尽,多做一次空页查询,无害)。
|
||||
*/
|
||||
Flux<AuditLog> fetchAll(ListOptions options) {
|
||||
return fetchBatch(options, 1);
|
||||
}
|
||||
|
||||
private Flux<AuditLog> fetchBatch(ListOptions options, int page) {
|
||||
var pageable = PageRequestImpl.of(page, EXPORT_BATCH_SIZE,
|
||||
Sort.by(Sort.Order.asc("metadata.creationTimestamp")));
|
||||
return client.listBy(AuditLog.class, options, pageable)
|
||||
.flatMapMany(result -> {
|
||||
var items = result.getItems() != null
|
||||
? result.getItems()
|
||||
: List.<AuditLog>of();
|
||||
if (items.size() < EXPORT_BATCH_SIZE) {
|
||||
return Flux.fromIterable(items);
|
||||
}
|
||||
return Flux.fromIterable(items).concatWith(fetchBatch(options, page + 1));
|
||||
});
|
||||
}
|
||||
|
||||
private String toCsvLine(AuditLog log) {
|
||||
var spec = log.getSpec();
|
||||
var statusCode = spec.getStatusCode();
|
||||
// 结果语义与前端一致:登录失败标注(HTTP 状态码可能为 200/302——失败回显页
|
||||
// 渲染/失败重定向)一律失败,其余 2xx/3xx 成功
|
||||
var failedLogin = OperationDescription.LOGIN_FAILURE_ACTION.equals(spec.getAction());
|
||||
var success = !failedLogin && statusCode != null && statusCode >= 200
|
||||
&& statusCode < 400;
|
||||
return String.join(",",
|
||||
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||
escape(spec.getUsername()),
|
||||
escape(spec.getAttemptedUsername()),
|
||||
escape(spec.getMethod()),
|
||||
escape(spec.getResourceType()),
|
||||
escape(spec.getResourceName()),
|
||||
escape(spec.getPath()),
|
||||
// 优先落库语义动作(含登录失败标注),历史记录回退 method/path 现场推导
|
||||
escape(OperationDescription.describe(spec)),
|
||||
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
||||
escape(success ? "成功" : "失败"),
|
||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||
escape(spec.getRemoteIp()),
|
||||
escape(spec.getUserAgent()));
|
||||
}
|
||||
|
||||
private static String formatTime(Instant instant) {
|
||||
return instant == null ? "" : TIME_FORMATTER.format(instant);
|
||||
}
|
||||
|
||||
/**
|
||||
* CSV 字段转义:含逗号/引号/换行的字段加引号、内部引号翻倍;
|
||||
* 以 =、+、-、@、Tab、CR 开头的字段加单引号前缀(公式注入防护,Excel/WPS 显示时忽略)。
|
||||
*/
|
||||
static String escape(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
var first = value.charAt(0);
|
||||
var safe = first == '=' || first == '+' || first == '-' || first == '@'
|
||||
|| first == '\t' || first == '\r'
|
||||
? "'" + value
|
||||
: value;
|
||||
if (safe.indexOf(',') >= 0 || safe.indexOf('"') >= 0
|
||||
|| safe.indexOf('\n') >= 0 || safe.indexOf('\r') >= 0) {
|
||||
return '"' + safe.replace("\"", "\"\"") + '"';
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.util.StringUtils;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.router.selector.FieldSelector;
|
||||
import run.halo.app.extension.index.query.Condition;
|
||||
import run.halo.app.extension.index.query.Queries;
|
||||
|
||||
/**
|
||||
* 审计日志查询/导出共用的筛选条件构造(技术方案 5.3):
|
||||
* fieldSelector 等值筛选、关键字、结果、时间区间 → {@link ListOptions}。
|
||||
*
|
||||
* <p>由查询端点与导出端点共用,非法参数抛 {@link IllegalArgumentException},
|
||||
* 由端点层统一转 400(错误消息与拆分前保持一致)。
|
||||
*/
|
||||
final class AuditLogFilters {
|
||||
|
||||
/** fieldSelector 支持等值筛选的字段白名单(与已注册索引一一对应)。 */
|
||||
static final Set<String> FILTERABLE_FIELDS = Set.of("spec.username", "spec.resourceType",
|
||||
"spec.method", "spec.action", "spec.statusCode");
|
||||
|
||||
private AuditLogFilters() {
|
||||
}
|
||||
|
||||
/** 从查询参数构造筛选条件,非法参数抛 {@link IllegalArgumentException}。 */
|
||||
static ListOptions fromQueryParams(MultiValueMap<String, String> params) {
|
||||
var conditions = new ArrayList<Condition>();
|
||||
|
||||
// fieldSelector 等值筛选:field=value(多个 fieldSelector 参数叠加 AND)
|
||||
for (var term : params.getOrDefault("fieldSelector", List.of())) {
|
||||
var idx = term.indexOf('=');
|
||||
if (idx <= 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid fieldSelector term, expect field=value: " + term);
|
||||
}
|
||||
var field = term.substring(0, idx).trim();
|
||||
var value = term.substring(idx + 1).trim();
|
||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||
throw new IllegalArgumentException("Field not filterable: " + field);
|
||||
}
|
||||
conditions.add(Queries.equal(field, value));
|
||||
}
|
||||
|
||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||
var keyword = params.getFirst("keyword");
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
var kw = keyword.trim();
|
||||
conditions.add(Queries.or(
|
||||
Queries.contains("spec.resourceName", kw),
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx 且非登录失败标注,failure = 4xx/5xx 或登录失败
|
||||
// (登录失败的 HTTP 状态码可能为 200/302——失败回显页渲染/失败重定向,
|
||||
// 已由语义动作 login-failure 标注,见 LoginOutcome)
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
var loginFailure = Queries.equal("spec.action",
|
||||
OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
switch (resultFilter.trim().toLowerCase()) {
|
||||
case "success" -> {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
conditions.add(Queries.not(loginFailure));
|
||||
}
|
||||
case "failure" -> conditions.add(Queries.or(
|
||||
Queries.greaterThan("spec.statusCode", "400", true),
|
||||
loginFailure));
|
||||
default -> throw new IllegalArgumentException(
|
||||
"Invalid result, expect success or failure: " + resultFilter);
|
||||
}
|
||||
}
|
||||
|
||||
// 时间区间(含边界,ISO-8601 Instant)
|
||||
try {
|
||||
var start = parseInstant(params.getFirst("startTime"));
|
||||
var end = parseInstant(params.getFirst("endTime"));
|
||||
if (start != null) {
|
||||
conditions.add(Queries.greaterThan("metadata.creationTimestamp",
|
||||
start.toString(), true));
|
||||
}
|
||||
if (end != null) {
|
||||
conditions.add(Queries.lessThan("metadata.creationTimestamp",
|
||||
end.toString(), true));
|
||||
}
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid time format, expect ISO-8601 instant: " + e.getMessage());
|
||||
}
|
||||
|
||||
return conditions.isEmpty()
|
||||
? new ListOptions().setFieldSelector(FieldSelector.all())
|
||||
: new ListOptions().setFieldSelector(
|
||||
FieldSelector.of(conditions.size() == 1 ? conditions.get(0)
|
||||
: Queries.and(conditions.get(0),
|
||||
conditions.subList(1, conditions.size())
|
||||
.toArray(Condition[]::new))));
|
||||
}
|
||||
|
||||
private static Instant parseInstant(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return Instant.parse(value.trim());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
@@ -13,9 +14,24 @@ public class AuditLogSpec {
|
||||
/** 操作者用户名;登录失败记 {@link #UNKNOWN_USERNAME}。 */
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 登录尝试的用户名(功能评审 P0-1):仅 POST {@code /login} 请求从表单/JSON 请求体
|
||||
* 白名单提取落库(密码等其余字段绝不提取);登录失败时操作者为
|
||||
* {@link #UNKNOWN_USERNAME},本字段用于区分定向撞库与无差别扫描。
|
||||
* 提取失败或非登录请求为 null;不建索引(无需按其筛选)。
|
||||
*/
|
||||
private String attemptedUsername;
|
||||
|
||||
/** HTTP 方法(动作),如 POST/PUT/DELETE/PATCH。 */
|
||||
private String method;
|
||||
|
||||
/**
|
||||
* 语义动作键(语义动作标注,产品设计 V2):捕获时由 method/path 推导落库
|
||||
* (如 login/logout/create/update/delete/publish/restore),注册索引后支持
|
||||
* 按语义动作筛选。升级前写入的历史记录无此字段,展示不受影响(现场推导)。
|
||||
*/
|
||||
private String action;
|
||||
|
||||
/** 资源类型(复数形式,如 posts/comments/users/auth)。 */
|
||||
private String resourceType;
|
||||
|
||||
@@ -34,6 +50,15 @@ public class AuditLogSpec {
|
||||
/** User-Agent。 */
|
||||
private String userAgent;
|
||||
|
||||
/**
|
||||
* 字段级变更列表(字段级变更 diff,产品设计 V2):仅成功的改/删/建操作且变更
|
||||
* 可捕获时落库;历史记录(升级前写入)与本项不可捕获时为 null。
|
||||
*/
|
||||
private List<ChangeEntry> changes;
|
||||
|
||||
/** 登录失败等无法确定操作者时的占位用户名。 */
|
||||
public static final String UNKNOWN_USERNAME = "unknown";
|
||||
|
||||
/** 系统内部变更(定时发布等非 HTTP 触发,产品设计 V2)的操作者用户名。 */
|
||||
public static final String SYSTEM_USERNAME = "system";
|
||||
}
|
||||
|
||||
+105
-84
@@ -1,13 +1,16 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
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.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
@@ -17,33 +20,37 @@ import reactor.core.publisher.Mono;
|
||||
import run.halo.app.core.extension.endpoint.CustomEndpoint;
|
||||
import run.halo.app.extension.GroupVersion;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.ListResult;
|
||||
import run.halo.app.extension.PageRequestImpl;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.router.selector.FieldSelector;
|
||||
import run.halo.app.extension.index.query.Condition;
|
||||
import run.halo.app.extension.index.query.Queries;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
|
||||
/**
|
||||
* 自有查询端点(技术方案 5.3 / 风险项 #2):
|
||||
* 自有查询/导出端点(技术方案 5.3 / 风险项 #2):
|
||||
*
|
||||
* <p>经源码级验证(v2.26.1 FieldSelectorConverter),Halo 原生列表 API 的 fieldSelector
|
||||
* 仅支持 =/!=/IN 等值操作符,不支持时间区间与模糊匹配,因此按技术方案预案启用插件自有
|
||||
* 查询端点,内部走索引 Query 实现(无内存分页),UI 调用方式不变。
|
||||
*
|
||||
* <p>筛选条件构造抽到 {@link AuditLogFilters} 供查询(分页 JSON)与导出(全量 CSV,
|
||||
* 见 {@link AuditLogCsvExporter})共用。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
|
||||
/** fieldSelector 支持等值筛选的字段白名单(与已注册索引一一对应)。 */
|
||||
private static final Set<String> FILTERABLE_FIELDS =
|
||||
Set.of("spec.username", "spec.resourceType", "spec.method", "spec.statusCode");
|
||||
|
||||
/** 每页大小上限,防止误用拖垮查询。 */
|
||||
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 AuditLogCsvExporter csvExporter;
|
||||
|
||||
@Override
|
||||
public GroupVersion groupVersion() {
|
||||
@@ -55,9 +62,78 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
return org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route()
|
||||
.GET("auditlogs/-/query", this::query, builder -> builder
|
||||
.operationId("ListAuditLogs")
|
||||
.description("分页查询审计日志:支持等值筛选(fieldSelector)、"
|
||||
+ "关键字(resourceName/path 模糊)、结果(success/failure)、"
|
||||
.tag(TAG)
|
||||
.description("分页查询审计日志:支持等值筛选(fieldSelector,含 spec.action "
|
||||
+ "语义动作)、关键字(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())
|
||||
.GET("auditlogs/-/export", this::export, builder -> builder
|
||||
.operationId("ExportAuditLogs")
|
||||
.tag(TAG)
|
||||
.description("按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS "
|
||||
+ "可直接打开):筛选参数与 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();
|
||||
}
|
||||
@@ -69,77 +145,29 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
var size = Math.min(Math.max(parseInt(params.getFirst("size"), 20), 1), MAX_PAGE_SIZE);
|
||||
var sort = parseSort(params.getFirst("sort"));
|
||||
|
||||
var conditions = new ArrayList<Condition>();
|
||||
|
||||
// fieldSelector 等值筛选:field=value(多个 fieldSelector 参数叠加 AND)
|
||||
for (var term : params.getOrDefault("fieldSelector", List.of())) {
|
||||
var idx = term.indexOf('=');
|
||||
if (idx <= 0) {
|
||||
return badRequest("Invalid fieldSelector term, expect field=value: " + term);
|
||||
}
|
||||
var field = term.substring(0, idx).trim();
|
||||
var value = term.substring(idx + 1).trim();
|
||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||
return badRequest("Field not filterable: " + field);
|
||||
}
|
||||
conditions.add(Queries.equal(field, value));
|
||||
}
|
||||
|
||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||
var keyword = params.getFirst("keyword");
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
var kw = keyword.trim();
|
||||
conditions.add(Queries.or(
|
||||
Queries.contains("spec.resourceName", kw),
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
switch (resultFilter.trim().toLowerCase()) {
|
||||
case "success" -> {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
}
|
||||
case "failure" -> conditions.add(Queries.greaterThan("spec.statusCode", "400", true));
|
||||
default -> {
|
||||
return badRequest("Invalid result, expect success or failure: "
|
||||
+ resultFilter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 时间区间(含边界,ISO-8601 Instant)
|
||||
ListOptions options;
|
||||
try {
|
||||
var start = parseInstant(params.getFirst("startTime"));
|
||||
var end = parseInstant(params.getFirst("endTime"));
|
||||
if (start != null) {
|
||||
conditions.add(Queries.greaterThan("metadata.creationTimestamp",
|
||||
start.toString(), true));
|
||||
options = AuditLogFilters.fromQueryParams(params);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return badRequest(e.getMessage());
|
||||
}
|
||||
if (end != null) {
|
||||
conditions.add(Queries.lessThan("metadata.creationTimestamp",
|
||||
end.toString(), true));
|
||||
}
|
||||
} catch (DateTimeParseException e) {
|
||||
return badRequest("Invalid time format, expect ISO-8601 instant: "
|
||||
+ e.getMessage());
|
||||
}
|
||||
|
||||
var options = conditions.isEmpty()
|
||||
? new ListOptions().setFieldSelector(FieldSelector.all())
|
||||
: new ListOptions().setFieldSelector(
|
||||
FieldSelector.of(conditions.size() == 1 ? conditions.get(0)
|
||||
: Queries.and(conditions.get(0),
|
||||
conditions.subList(1, conditions.size())
|
||||
.toArray(Condition[]::new))));
|
||||
|
||||
var pageable = PageRequestImpl.of(page, size, sort);
|
||||
return client.listBy(AuditLog.class, options, pageable)
|
||||
.flatMap(result -> ServerResponse.ok().bodyValue(result));
|
||||
}
|
||||
|
||||
/** 导出端点:筛选参数与 query 一致,全量流式 CSV 附件下载。 */
|
||||
private Mono<ServerResponse> export(ServerRequest request) {
|
||||
ListOptions options;
|
||||
try {
|
||||
options = AuditLogFilters.fromQueryParams(request.queryParams());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return badRequest(e.getMessage());
|
||||
}
|
||||
return csvExporter.exportResponse(options);
|
||||
}
|
||||
|
||||
private static Mono<ServerResponse> badRequest(String message) {
|
||||
return ServerResponse.badRequest().bodyValue(java.util.Map.of("message", message));
|
||||
}
|
||||
@@ -169,11 +197,4 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
var descending = parts.length < 2 || !"asc".equalsIgnoreCase(parts[1].trim());
|
||||
return Sort.by(descending ? Sort.Order.desc(field) : Sort.Order.asc(field));
|
||||
}
|
||||
|
||||
private static Instant parseInstant(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return Instant.parse(value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
+123
-15
@@ -1,6 +1,7 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -17,6 +18,9 @@ import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
* 失败静默降级为 warn 日志:不重试、不阻塞、不抛出(产品设计原则 4)。
|
||||
* 不引入内存队列:Extension 存储底层为响应式(R2DBC),连接池天然提供背压;
|
||||
* 若后续压测发现写入积压,在 Recorder 内部替换为有界队列 + worker,接口不变。
|
||||
*
|
||||
* <p>字段级变更(产品设计 V2):仅在操作成功(2xx)且 {@link ChangeCaptureManager}
|
||||
* 已捕获请求体/旧状态时,经 {@link ChangeDiffEngine} 计算 {@code spec.changes} 落库。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -31,8 +35,16 @@ public class AuditRecorder {
|
||||
*
|
||||
* <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值,
|
||||
* 此处为防御性兜底,保证审计设置故障不影响捕获链路。
|
||||
*
|
||||
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
|
||||
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
|
||||
* @param loginFailed 登录失败标注:POST /login 结果失败(表单登录失败为
|
||||
* 302 重定向且目标含 error 参数)或失败回显
|
||||
* (GET /login?error=...,HTTP 200),语义动作标注
|
||||
* login-failure;其余请求为 false
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
@@ -40,18 +52,20 @@ public class AuditRecorder {
|
||||
snapshot.getMethod(), snapshot.getFullPath());
|
||||
return;
|
||||
}
|
||||
write(snapshot, statusCode, username);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||
},
|
||||
e -> {
|
||||
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
write(snapshot, statusCode, username);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||
});
|
||||
}
|
||||
|
||||
private void write(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
try {
|
||||
var auditLog = assemble(snapshot, statusCode, username);
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername,
|
||||
loginFailed);
|
||||
client.create(auditLog)
|
||||
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e));
|
||||
@@ -62,19 +76,71 @@ public class AuditRecorder {
|
||||
}
|
||||
}
|
||||
|
||||
private AuditLog assemble(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||
/**
|
||||
* 记录一次系统内部变更(产品设计 V2"系统内部变更"):定时发布等非 HTTP 触发的
|
||||
* 资源变更,执行者记 "system"。
|
||||
*
|
||||
* <p>门控:审计总开关与系统内部变更开关(设置读取失败按默认开启继续,与 HTTP
|
||||
* 记录的兜底策略一致)。方法取事件类型(PUT=更新 / DELETE=删除),语义动作由
|
||||
* 方法与规范路径推导,状态码恒为 200——事件在 Halo 写入成功后才派发,变更必然
|
||||
* 已落库。
|
||||
*
|
||||
* @param method 事件类型映射的伪方法(PUT/DELETE)
|
||||
* @param plural 资源类型(模型 plural)
|
||||
* @param resourceName 资源名称
|
||||
* @param path 资源的规范 API 路径(/apis/... 或 /api/...)
|
||||
* @param changes 字段级变更(内部变更通道已按用户可写面降噪,非空才调用)
|
||||
*/
|
||||
public void recordSystemChange(String method, String plural, String resourceName,
|
||||
String path, List<ChangeEntry> changes) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> {
|
||||
if (!settings.enabledOrDefault() || !settings.recordSystemChangesOrDefault()) {
|
||||
log.debug("System change recording disabled, skip recording {} {}",
|
||||
method, path);
|
||||
return;
|
||||
}
|
||||
writeSystemChange(method, plural, resourceName, path, changes);
|
||||
},
|
||||
e -> {
|
||||
log.warn("Failed to load audit settings, record system change with defaults "
|
||||
+ "for {} {}", method, path, e);
|
||||
writeSystemChange(method, plural, resourceName, path, changes);
|
||||
});
|
||||
}
|
||||
|
||||
private void writeSystemChange(String method, String plural, String resourceName,
|
||||
String path, List<ChangeEntry> changes) {
|
||||
try {
|
||||
var auditLog = assembleSystemChange(method, plural, resourceName, path, changes);
|
||||
client.create(auditLog)
|
||||
.subscribe(null, e -> log.warn("Failed to write audit log for system change "
|
||||
+ "{} {}", method, path, e));
|
||||
} catch (Exception e) {
|
||||
// 组装失败同样静默降级,绝不让审计影响业务主流程
|
||||
log.warn("Failed to assemble audit log for system change {} {}", method, path, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static AuditLog assembleSystemChange(String method, String plural,
|
||||
String resourceName, String path, List<ChangeEntry> changes) {
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME);
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
spec.setResourceName(resolved.optionalName().orElse(null));
|
||||
spec.setPath(snapshot.getFullPath());
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||
spec.setUserAgent(snapshot.getUserAgent());
|
||||
spec.setUsername(AuditLogSpec.SYSTEM_USERNAME);
|
||||
spec.setMethod(method);
|
||||
spec.setAction(OperationDescription.actionOf(method, plural, path));
|
||||
spec.setResourceType(plural);
|
||||
spec.setResourceName(resourceName);
|
||||
spec.setPath(path);
|
||||
// 内部变更无响应码语义;事件在写入成功后派发,恒记 200(成功)
|
||||
spec.setStatusCode(200);
|
||||
spec.setRemoteIp(null);
|
||||
spec.setUserAgent(null);
|
||||
spec.setChanges(changes);
|
||||
return newAuditLog(spec);
|
||||
}
|
||||
|
||||
/** 统一组装 metadata 与包装对象。 */
|
||||
private static AuditLog newAuditLog(AuditLogSpec spec) {
|
||||
var metadata = new Metadata();
|
||||
metadata.setName("auditlog-" + UUID.randomUUID());
|
||||
metadata.setCreationTimestamp(Instant.now());
|
||||
@@ -84,4 +150,46 @@ public class AuditRecorder {
|
||||
auditLog.setSpec(spec);
|
||||
return auditLog;
|
||||
}
|
||||
|
||||
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME);
|
||||
// 登录尝试用户名(功能评审 P0-1):仅登录请求由捕获器提取,其余请求为 null
|
||||
spec.setAttemptedUsername(attemptedUsername);
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选;
|
||||
// 登录失败(POST /login 失败或 GET /login?error=... 失败回显)标注
|
||||
// login-failure——回显页 HTTP 200 无法由路径重新推导,必须落库标注
|
||||
spec.setAction(loginFailed ? OperationDescription.LOGIN_FAILURE_ACTION
|
||||
: OperationDescription.actionOf(
|
||||
snapshot.getMethod(), resolved.resourceType(), snapshot.getPath()));
|
||||
spec.setResourceName(resolved.optionalName().orElse(null));
|
||||
spec.setPath(snapshot.getFullPath());
|
||||
// 状态码如实记录(失败回显页为 200、表单登录失败为 302),登录成败看语义动作标注
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||
spec.setUserAgent(snapshot.getUserAgent());
|
||||
spec.setChanges(changesOf(snapshot, capture, statusCode));
|
||||
return newAuditLog(spec);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段级变更(产品设计 V2):仅成功操作(2xx,此时资源已实际变更)落库 diff;
|
||||
* 失败请求、未捕获变更上下文(capture 为 null 或 body/旧状态缺失)不记。
|
||||
*/
|
||||
private static List<ChangeEntry> changesOf(RequestSnapshot snapshot, ChangeCapture capture,
|
||||
Integer statusCode) {
|
||||
if (statusCode == null || statusCode < 200 || statusCode >= 300) {
|
||||
return null;
|
||||
}
|
||||
if (capture == null) {
|
||||
return null;
|
||||
}
|
||||
return ChangeDiffEngine.compute(snapshot.getMethod(), capture.getOldNode(),
|
||||
capture.getBodyNode());
|
||||
}
|
||||
}
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.plugin.PluginContext;
|
||||
|
||||
/**
|
||||
* 系统内部变更监听装配:以插件自身的配置 ConfigMap 名构建 {@link InternalChangeWatcher}
|
||||
* (保存插件设置走 json-config 端点时实际写的是该 ConfigMap,监听需排除避免误归属)。
|
||||
*/
|
||||
@Configuration
|
||||
class AuditWatchConfiguration {
|
||||
|
||||
@Bean
|
||||
InternalChangeWatcher internalChangeWatcher(ReactiveExtensionClient client,
|
||||
SchemeManager schemeManager, HttpWriteMarker writeMarker, AuditRecorder recorder,
|
||||
PluginContext pluginContext) {
|
||||
return new InternalChangeWatcher(client, schemeManager, writeMarker, recorder,
|
||||
pluginContext.getConfigMapName());
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isAuthEndpoint;
|
||||
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 /login}、{@code /logout})审计捕获过滤器(P0 修复,见测试报告)。
|
||||
*
|
||||
* <p>以 {@link BeforeSecurityWebFilter} 扩展点注册:位于 Security 过滤链最前
|
||||
* ({@code SecurityWebFiltersOrder.FIRST})。原先认证端点由
|
||||
* {@code AfterSecurityWebFilter} 扩展点注册的 {@link OperationAuditWebFilter} 捕获,
|
||||
* 但该扩展点位于认证环节之后——表单登录(FORM_LOGIN)与登出(LOGOUT)过滤器命中
|
||||
* 请求后直接完成 302 响应、不再向下游传递,POST /login 与 POST /logout 永远到不了
|
||||
* 链尾的审计过滤器(真实环境实测,登录失败告警生产路径随之失效)。因此认证端点整体
|
||||
* 移交本过滤器,在 Security 链之前承接捕获与记录。
|
||||
*
|
||||
* <p>操作者归属:Security 链最前无认证上下文(SecurityContext 由链内更晚位置的
|
||||
* ReactorContextWebFilter 写入订阅上下文,对链首过滤器不可见),统一记
|
||||
* {@link AuditLogSpec#UNKNOWN_USERNAME 未知用户}(既有兜底路径);登录尝试的账号
|
||||
* 由 {@link LoginAttemptCapture} 从请求体白名单提取,落库 {@code spec.attemptedUsername}
|
||||
* 并进入告警负载(功能评审 P0-1),账号归属信息不受影响。
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* 回调给 {@code LoginFailureAlertService},按阈值窗口推送 Webhook;与审计开关相互独立。
|
||||
* 结果由 {@link LoginOutcome} 判定(表单登录成败均为 302 重定向,以重定向目标是否含
|
||||
* {@code error} 参数区分,不能只看状态码)。
|
||||
*
|
||||
* <p>登录失败标注(语义动作 {@code login-failure}):登录尝试失败与失败回显
|
||||
* ({@code GET /login?error=...},HTTP 200)的审计记录标注登录失败,供列表红色标记
|
||||
* 与筛选;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 (!isAuthEndpoint(path)) {
|
||||
// 非 /login、/logout 一律原样透传:不触碰请求体、不读会话,零附加开销
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
writeMarker.onRequestStart(request);
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
var loginAttempt = new LoginAttempt();
|
||||
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
||||
// 登出与登录页 GET 原样透传
|
||||
var bodyPrepared = isLoginAttempt(path, method)
|
||||
? loginAttemptCapture.prepare(exchange, loginAttempt)
|
||||
: Mono.just(exchange);
|
||||
return bodyPrepared
|
||||
.flatMap(chain::filter)
|
||||
.doFinally(signal -> {
|
||||
writeMarker.onRequestComplete(request);
|
||||
var statusCode = statusOf(exchange);
|
||||
// 登录结果判定(LoginOutcome):表单登录成败均为 302 重定向,
|
||||
// 以重定向目标是否含 error 参数区分;GET /login?error=... 为失败回显
|
||||
var loginFailed = isLoginFailed(path, method, statusCode, exchange, snapshot);
|
||||
if (isLoginAttempt(path, method)) {
|
||||
// 登录失败告警(产品设计 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败判定(LoginOutcome):POST {@code /login} 按状态码 + 重定向目标判定
|
||||
* (表单登录成败均为 302,以 Location 是否含 {@code error} 参数区分);
|
||||
* 登出与登录页 GET 仅失败回显({@code GET /login?error=...},HTTP 200)判为失败。
|
||||
*/
|
||||
private static boolean isLoginFailed(String path, String method, Integer statusCode,
|
||||
ServerWebExchange exchange, RequestSnapshot snapshot) {
|
||||
if (isLoginAttempt(path, method)) {
|
||||
return LoginOutcome.isFailure(statusCode,
|
||||
exchange.getResponse().getHeaders().getLocation());
|
||||
}
|
||||
if ("GET".equals(method)) {
|
||||
return LoginOutcome.isFailureEcho(snapshot.getFullPath());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+28
-8
@@ -6,9 +6,14 @@ import java.util.Set;
|
||||
* 捕获规则(纯函数,技术方案 D1):
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code POST/PUT/DELETE/PATCH} + 路径前缀 {@code /apis/}</li>
|
||||
* <li>或路径精确匹配 {@code /login}、{@code /logout}(登录端点不在 /apis/** 下,
|
||||
* 是“一条通用规则覆盖全部管理面操作”的唯一必要例外,需在产品文档同步注明)</li>
|
||||
* <li>{@code /apis/**} 下的 {@code POST/PUT/DELETE/PATCH} 写操作({@link #shouldCapture},
|
||||
* 由 {@code AfterSecurityWebFilter} 注册的 {@link OperationAuditWebFilter} 消费,
|
||||
* 可获得认证用户上下文);</li>
|
||||
* <li>认证端点 {@code /login}、{@code /logout} 精确匹配({@link #isAuthEndpoint},
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 消费)——登录端点不在 /apis/** 下,且
|
||||
* 表单登录/登出过滤器命中请求后直接完成响应、不再向下游传递,链尾的
|
||||
* AfterSecurityWebFilter 永远看不到(P0 缺陷实测),因此必须在 Security 链之前
|
||||
* 独立捕获。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
|
||||
@@ -19,22 +24,37 @@ public final class CaptureRule {
|
||||
public static final Set<String> AUTH_ENDPOINTS = Set.of("/login", "/logout");
|
||||
public static final String APIS_PREFIX = "/apis/";
|
||||
|
||||
/** 登录端点(告警通道唯一触发路径;登出与登录页 GET 不算登录尝试)。 */
|
||||
public static final String LOGIN_ENDPOINT = "/login";
|
||||
|
||||
private CaptureRule() {
|
||||
}
|
||||
|
||||
/** 是否命中捕获规则。path 为不含查询串的请求路径。 */
|
||||
/**
|
||||
* 是否命中捕获规则。path 为不含查询串的请求路径。
|
||||
*
|
||||
* <p>仅覆盖 {@code /apis/**} 写操作;认证端点由 {@link #isAuthEndpoint} 单独判定、
|
||||
* 由 {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,两个过滤器按此分治、
|
||||
* 互不重叠,不会重复记录。
|
||||
*/
|
||||
public static boolean shouldCapture(String path, String method) {
|
||||
if (isAuthEndpoint(path)) {
|
||||
return true;
|
||||
}
|
||||
if (path == null || !path.startsWith(APIS_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
return method != null && WRITE_METHODS.contains(method);
|
||||
}
|
||||
|
||||
/** 是否为登录/登出端点。 */
|
||||
/** 是否为登录/登出端点(由 {@link AuthEndpointAuditWebFilter} 捕获)。 */
|
||||
public static boolean isAuthEndpoint(String path) {
|
||||
return path != null && AUTH_ENDPOINTS.contains(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为登录尝试(POST {@value #LOGIN_ENDPOINT},产品设计 V2「告警通知」):
|
||||
* 登录失败告警的触发条件——结果由 {@link LoginOutcome} 判定(表单登录成败均为
|
||||
* 302 重定向,不能只看状态码);登录页 GET 与登出不算。
|
||||
*/
|
||||
public static boolean isLoginAttempt(String path, String method) {
|
||||
return "POST".equals(method) && LOGIN_ENDPOINT.equals(path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 请求期捕获的字段变更上下文(产品设计 V2"字段级变更 diff")。
|
||||
*
|
||||
* <p>由 {@link ChangeCaptureManager} 在请求期填充:请求体 JSON 与(改/删时的)
|
||||
* 写入前资源状态;响应完成后由 {@link AuditRecorder} 据此计算 diff 落库。
|
||||
* 每请求一个实例,写入与读取位于不同的响应式线程,字段用 volatile 保证可见性。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public final class ChangeCapture {
|
||||
|
||||
/** 请求体解析出的 JSON;未缓存(非 JSON/空/超限)时为 null。 */
|
||||
private volatile JsonNode bodyNode;
|
||||
|
||||
/** 写入前的资源状态 JSON;POST 或获取失败时为 null。 */
|
||||
private volatile JsonNode oldNode;
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static run.halo.operationaudit.audit.CaptureRule.APIS_PREFIX;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.WRITE_METHODS;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isAuthEndpoint;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.Unstructured;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettingProvider;
|
||||
|
||||
/**
|
||||
* 字段级变更捕获(产品设计 V2"字段级变更 diff"):
|
||||
* 在请求期缓存 JSON 请求体,并在改/删操作落库前抓取写入前的资源状态,
|
||||
* 供 {@link AuditRecorder} 在响应成功后计算字段级 diff。
|
||||
*
|
||||
* <p>捕获条件({@link #eligible}):{@code /apis/**} 写操作(登录端点排除);
|
||||
* 设置开关({@code recordChanges},随审计总开关)关闭时不捕获。其中请求体仅在
|
||||
* JSON 内容类型且大小可控时缓存(改/删的旧状态不依赖请求体,DELETE 无请求体也可抓取)。
|
||||
*
|
||||
* <p>安全边界:请求体经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存
|
||||
* (分块传输/超限/非 JSON 一律不缓存,仅记操作元信息),绝不中断流式请求;
|
||||
* 旧状态经 {@code fetch(gvk, name)} 原始 JSON 获取,失败静默跳过 diff。
|
||||
* 整个捕获过程任何异常均降级为"不记变更",不影响业务主流程(设计原则 4)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ChangeCaptureManager {
|
||||
|
||||
/** 请求体缓存上限(字节):超过不缓存、不记录字段变更。 */
|
||||
static final int MAX_BODY_BYTES = 256 * 1024;
|
||||
|
||||
private final AuditSettingProvider settingProvider;
|
||||
private final SchemeManager schemeManager;
|
||||
private final ReactiveExtensionClient client;
|
||||
|
||||
/**
|
||||
* 捕获变更上下文,返回(可能包装了缓存请求体的)交换对象供后续链路继续处理。
|
||||
* 返回的 Mono 永不报错、永不为空:任何失败均回退原 exchange(仅不记字段变更)。
|
||||
*/
|
||||
public Mono<ServerWebExchange> prepare(ServerWebExchange exchange, RequestSnapshot snapshot,
|
||||
ChangeCapture capture) {
|
||||
if (!eligible(snapshot)) {
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
return settingProvider.get()
|
||||
.flatMap(settings -> {
|
||||
if (!settings.enabledOrDefault() || !settings.recordChangesOrDefault()) {
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
return captureContext(exchange, snapshot, capture);
|
||||
})
|
||||
.onErrorResume(e -> {
|
||||
log.warn("Failed to capture change context for {} {}, skip field diff",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
return Mono.just(exchange);
|
||||
});
|
||||
}
|
||||
|
||||
/** 变更捕获适用性:{@code /apis/**} 写操作(登录端点排除)。 */
|
||||
static boolean eligible(RequestSnapshot snapshot) {
|
||||
var path = snapshot.getPath();
|
||||
if (isAuthEndpoint(path) || !path.startsWith(APIS_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
return WRITE_METHODS.contains(snapshot.getMethod());
|
||||
}
|
||||
|
||||
/** application/json 或 application/*+json(含 merge-patch+json)。 */
|
||||
static boolean isJson(MediaType contentType) {
|
||||
if (contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
|
||||
return true;
|
||||
}
|
||||
var subtype = contentType.getSubtype();
|
||||
return subtype != null && subtype.toLowerCase(java.util.Locale.ROOT).endsWith("+json");
|
||||
}
|
||||
|
||||
private Mono<ServerWebExchange> captureContext(ServerWebExchange exchange,
|
||||
RequestSnapshot snapshot, ChangeCapture capture) {
|
||||
var contentType = exchange.getRequest().getHeaders().getContentType();
|
||||
var jsonBody = contentType != null && isJson(contentType);
|
||||
var prepared = jsonBody ? cacheBody(exchange, capture) : Mono.just(exchange);
|
||||
return prepared.flatMap(decorated -> {
|
||||
if (needsOldState(snapshot.getMethod(), jsonBody)) {
|
||||
return fetchOldState(snapshot, capture).thenReturn(decorated);
|
||||
}
|
||||
return Mono.just(decorated);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否需要写入前状态:DELETE 无请求体(记录被删内容);PUT/PATCH 仅在 JSON
|
||||
* 请求体可缓存时才有 diff 意义;POST(新建)无旧值。
|
||||
*/
|
||||
private static boolean needsOldState(String method, boolean jsonBody) {
|
||||
return switch (method) {
|
||||
case "DELETE" -> true;
|
||||
case "PUT", "PATCH" -> jsonBody;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存 JSON 请求体并返回装饰后的 exchange(下游可重复读 body);仅在调用方已判定
|
||||
* 请求体为 JSON 时进入。无 Content-Length(分块传输)或超限:不缓存,避免中断流式请求。
|
||||
*/
|
||||
private Mono<ServerWebExchange> cacheBody(ServerWebExchange exchange, ChangeCapture capture) {
|
||||
var request = exchange.getRequest();
|
||||
var contentLength = request.getHeaders().getContentLength();
|
||||
if (contentLength <= 0 || contentLength > MAX_BODY_BYTES) {
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
return DataBufferUtils.join(request.getBody(), MAX_BODY_BYTES)
|
||||
.map(joined -> {
|
||||
var bytes = new byte[joined.readableByteCount()];
|
||||
joined.read(bytes);
|
||||
DataBufferUtils.release(joined);
|
||||
capture.setBodyNode(parseJson(bytes));
|
||||
return decorate(exchange, bytes);
|
||||
})
|
||||
.defaultIfEmpty(exchange);
|
||||
}
|
||||
|
||||
private JsonNode parseJson(byte[] bytes) {
|
||||
// 用 Halo 提供的 Unstructured 静态 mapper(Jackson 2,与 diff 树类型一致),
|
||||
// 不注入 ObjectMapper bean:插件上下文(Spring Boot 4)中无该类型
|
||||
try {
|
||||
return Unstructured.OBJECT_MAPPER.readTree(bytes);
|
||||
} catch (java.io.IOException e) {
|
||||
// 非 JSON 内容或超限(StreamReadConstraints):不记字段变更,不影响记录
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游 handler 可正常读取。 */
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 改/删操作在落库前抓取写入前的资源状态;POST(新建)无旧值。
|
||||
* 仅当路径可解析出资源名且模型已注册(可定位 GVK)时获取,失败静默跳过。
|
||||
*/
|
||||
private Mono<Void> fetchOldState(RequestSnapshot snapshot, ChangeCapture capture) {
|
||||
var method = snapshot.getMethod();
|
||||
if (!"PUT".equals(method) && !"PATCH".equals(method) && !"DELETE".equals(method)) {
|
||||
return Mono.empty();
|
||||
}
|
||||
var target = ExtensionTargets.resolve(schemeManager, snapshot.getPath());
|
||||
if (target == null) {
|
||||
return Mono.empty();
|
||||
}
|
||||
// defer 包裹组装期与订阅期:client 异常(含极端情况下返回 null)一并静默降级
|
||||
return Mono.defer(() -> client.fetch(target.gvk(), target.name())
|
||||
.map(ChangeCaptureManager::toOldStateNode)
|
||||
.doOnNext(capture::setOldNode))
|
||||
.onErrorResume(e -> {
|
||||
log.debug("Failed to fetch old state for {} {}, skip field diff",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.then();
|
||||
}
|
||||
|
||||
/** Unstructured → 完整资源 JSON 树(含自定义序列化器,往返无损)。 */
|
||||
private static JsonNode toOldStateNode(Unstructured unstructured) {
|
||||
return Unstructured.OBJECT_MAPPER.valueToTree(unstructured);
|
||||
}
|
||||
}
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 字段级变更 diff(纯函数,产品设计 V2"字段级变更 diff")。
|
||||
*
|
||||
* <p>输入为写入前的资源状态(存储原始 JSON,可空)与请求体 JSON(可空),
|
||||
* 按 HTTP 方法取语义:
|
||||
*
|
||||
* <table>
|
||||
* <caption>方法 → diff 语义</caption>
|
||||
* <tr><th>方法</th><th>语义</th></tr>
|
||||
* <tr><td>PUT</td><td>整体替换:新增 / 修改 / 删除全量计算</td></tr>
|
||||
* <tr><td>PATCH(数组 body)</td><td>JSON Patch(RFC 6902 ops,Halo 扩展路由的标准 PATCH):按 op 与 JSON Pointer 展开</td></tr>
|
||||
* <tr><td>PATCH(对象 body)</td><td>JSON Merge Patch:仅比较 body 中出现的字段,显式 null 视为删除该字段</td></tr>
|
||||
* <tr><td>POST</td><td>新建:所有字段记为新增(oldNode 忽略)</td></tr>
|
||||
* <tr><td>DELETE</td><td>删除:所有字段记为移除(newNode 忽略)</td></tr>
|
||||
* </table>
|
||||
*
|
||||
* <p>范围与降噪:只比较用户可写面——根级跳过 {@code apiVersion/kind/status},
|
||||
* {@code metadata} 仅保留 {@code name/labels/annotations}(version/managedFields/时间戳等
|
||||
* 服务端管理字段不参与);数组与超深子树作为整体叶子比较。
|
||||
* 输出经脱敏(敏感字段名)、截断(单值 200 字符)与封顶(30 条,超出以汇总条兜底)。
|
||||
*/
|
||||
final class ChangeDiffEngine {
|
||||
|
||||
/** 单条记录最多记录的变更条数(超出部分以汇总条兜底,保证完整性可感知)。 */
|
||||
static final int MAX_CHANGES = 30;
|
||||
|
||||
/** 单个字段值的最大记录长度,超出截断。 */
|
||||
static final int MAX_VALUE_LENGTH = 200;
|
||||
|
||||
/** 截断标记。 */
|
||||
static final String TRUNCATION_SUFFIX = "…(截断)";
|
||||
|
||||
/** 敏感字段的脱敏值。 */
|
||||
static final String REDACTED_VALUE = "******";
|
||||
|
||||
/** 对象递归比较的最大深度,超过视为叶子整体比较(防超深构造)。 */
|
||||
private static final int MAX_DEPTH = 16;
|
||||
|
||||
/** 敏感字段名片段:字段路径任一段命中即脱敏,避免密码/密钥明文落库。 */
|
||||
private static final Pattern SENSITIVE_FIELD =
|
||||
Pattern.compile("(?i)password|passwd|secret|token|credential");
|
||||
|
||||
/** 根级不参与 diff 的键:apiVersion/kind 恒定,status 由服务端管理。 */
|
||||
private static final Set<String> ROOT_SKIPPED_KEYS = Set.of("apiVersion", "kind", "status");
|
||||
|
||||
/** metadata 仅保留用户可写子键,其余(version/managedFields/时间戳等)为服务端管理。 */
|
||||
private static final Set<String> METADATA_INCLUDED_KEYS =
|
||||
Set.of("name", "labels", "annotations");
|
||||
|
||||
/** 汇总兜底条的字段名。 */
|
||||
static final String OVERFLOW_FIELD = "…";
|
||||
|
||||
/** 单侧整体缺失(新增/删除整棵子树)且另一侧非对象时,叶子条目的字段占位名。 */
|
||||
private static final String ROOT_PLACEHOLDER_FIELD = "(请求体)";
|
||||
|
||||
private ChangeDiffEngine() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算字段级变更列表。
|
||||
*
|
||||
* @param method HTTP 方法;仅 PUT/PATCH/POST/DELETE 参与计算
|
||||
* @param oldNode 写入前资源状态(POST 传 null);获取失败时 PUT/PATCH/DELETE 不计算
|
||||
* @param newNode 请求体 JSON(DELETE 传 null);缺失或非 JSON 不计算
|
||||
* @return 变更列表;无变更或无法计算返回 null(不落库 changes 字段)
|
||||
*/
|
||||
static List<ChangeEntry> compute(String method, JsonNode oldNode, JsonNode newNode) {
|
||||
var missing = MissingNode.getInstance();
|
||||
return switch (method == null ? "" : method) {
|
||||
case "POST" -> newNode == null ? null : diffTree(missing, newNode, true);
|
||||
case "DELETE" -> oldNode == null ? null : diffTree(oldNode, missing, true);
|
||||
case "PUT" ->
|
||||
(oldNode == null || newNode == null) ? null : diffTree(oldNode, newNode, true);
|
||||
// PATCH 两种形态:JSON Patch(RFC 6902 ops 数组,Halo 扩展路由的标准 PATCH)
|
||||
// 与 JSON Merge Patch(对象 body,仅比较 body 中出现的字段)
|
||||
case "PATCH" -> {
|
||||
if (oldNode == null || newNode == null) {
|
||||
yield null;
|
||||
}
|
||||
yield newNode.isArray()
|
||||
? capChanges(jsonPatchEntries(oldNode, newNode))
|
||||
: diffTree(oldNode, newNode, false);
|
||||
}
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON Patch(RFC 6902)ops 数组 → 变更条目:replace/add 按 JSON Pointer 查旧值判定
|
||||
* 新增或修改,remove 记录被删原值;move/copy/test 等少见操作整条 op 落库兜底。
|
||||
*/
|
||||
private static List<ChangeEntry> jsonPatchEntries(JsonNode oldNode, JsonNode patchOps) {
|
||||
var changes = new ArrayList<ChangeEntry>();
|
||||
for (var op : patchOps) {
|
||||
var pointer = op.path("path").asText("");
|
||||
var field = pointer.isEmpty() ? ROOT_PLACEHOLDER_FIELD
|
||||
: pointerToField(pointer);
|
||||
var opType = op.path("op").asText("");
|
||||
switch (opType) {
|
||||
case "replace", "add" -> {
|
||||
var oldValue = oldNode.at(pointer);
|
||||
var missingOld = oldValue.isMissingNode();
|
||||
addEntry(changes, field, missingOld ? ChangeType.ADDED : ChangeType.UPDATED,
|
||||
missingOld ? null : oldValue, op.get("value"));
|
||||
}
|
||||
case "remove" -> {
|
||||
var oldValue = oldNode.at(pointer);
|
||||
if (oldValue.isMissingNode()) {
|
||||
continue;
|
||||
}
|
||||
addEntry(changes, field, ChangeType.REMOVED, oldValue, null);
|
||||
}
|
||||
default ->
|
||||
// move/copy/test 等少见操作:整条 op 作为兜底记录
|
||||
addEntry(changes, field, ChangeType.UPDATED, null, op);
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
/** JSON Pointer({@code /spec/title},含 ~0/~1 转义)→ 字段路径({@code spec.title})。 */
|
||||
private static String pointerToField(String pointer) {
|
||||
var segments = new ArrayList<String>();
|
||||
for (var segment : pointer.substring(1).split("/", -1)) {
|
||||
segments.add(segment.replace("~1", "/").replace("~0", "~"));
|
||||
}
|
||||
return String.join(".", segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* 变更列表的紧凑中文摘要(导出 CSV"变更"列用):如
|
||||
* {@code 修改 spec.title:旧值 → 新值;新增 spec.cover:x;删除 spec.slug:y}。
|
||||
*/
|
||||
static String formatChanges(List<ChangeEntry> changes) {
|
||||
if (changes == null || changes.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return changes.stream()
|
||||
.map(ChangeDiffEngine::formatChange)
|
||||
.collect(Collectors.joining(";"));
|
||||
}
|
||||
|
||||
private static String formatChange(ChangeEntry change) {
|
||||
var field = change.getField();
|
||||
if (OVERFLOW_FIELD.equals(field)) {
|
||||
// 汇总兜底条:newValue 即说明文本
|
||||
return orDash(change.getNewValue());
|
||||
}
|
||||
return switch (change.getChangeType()) {
|
||||
case ADDED -> "新增 " + field + ":" + orDash(change.getNewValue());
|
||||
case UPDATED -> "修改 " + field + ":" + orDash(change.getOldValue())
|
||||
+ " → " + orDash(change.getNewValue());
|
||||
case REMOVED -> "删除 " + field + ":" + orDash(change.getOldValue());
|
||||
};
|
||||
}
|
||||
|
||||
private static String orDash(String value) {
|
||||
return value == null || value.isEmpty() ? "-" : value;
|
||||
}
|
||||
|
||||
private static List<ChangeEntry> diffTree(JsonNode oldNode, JsonNode newNode,
|
||||
boolean removalsEnabled) {
|
||||
var changes = new ArrayList<ChangeEntry>();
|
||||
collectChanges("", oldNode, newNode, removalsEnabled, 0, changes);
|
||||
if (changes.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return capChanges(changes);
|
||||
}
|
||||
|
||||
/** 条数封顶:超出 {@value #MAX_CHANGES} 条时截断并追加汇总条。 */
|
||||
private static List<ChangeEntry> capChanges(List<ChangeEntry> changes) {
|
||||
if (changes.size() <= MAX_CHANGES) {
|
||||
return changes;
|
||||
}
|
||||
var capped = new ArrayList<ChangeEntry>(changes.subList(0, MAX_CHANGES));
|
||||
var summary = new ChangeEntry();
|
||||
summary.setField(OVERFLOW_FIELD);
|
||||
summary.setChangeType(ChangeType.UPDATED);
|
||||
summary.setNewValue("变更过多,仅记录前 " + MAX_CHANGES + " 处(共 "
|
||||
+ changes.size() + " 处)");
|
||||
capped.add(summary);
|
||||
return capped;
|
||||
}
|
||||
|
||||
private static void collectChanges(String path, JsonNode oldNode, JsonNode newNode,
|
||||
boolean removalsEnabled, int depth, List<ChangeEntry> out) {
|
||||
// 对象(或单侧缺失)逐字段比较;缺失侧交由 collectObjectChanges 展开 ADDED/REMOVED
|
||||
if (depth < MAX_DEPTH && isContainerOrAbsent(oldNode) && isContainerOrAbsent(newNode)) {
|
||||
collectObjectChanges(path, oldNode, newNode, removalsEnabled, depth, out);
|
||||
return;
|
||||
}
|
||||
// 数组 / 标量 / 类型变更 / 超深子树:整体叶子比较
|
||||
if (oldNode.equals(newNode)) {
|
||||
return;
|
||||
}
|
||||
addEntry(out, path, ChangeType.UPDATED, oldNode, newNode);
|
||||
}
|
||||
|
||||
private static boolean isContainerOrAbsent(JsonNode node) {
|
||||
return node.isObject() || node.isMissingNode();
|
||||
}
|
||||
|
||||
private static void collectObjectChanges(String path, JsonNode oldNode, JsonNode newNode,
|
||||
boolean removalsEnabled, int depth, List<ChangeEntry> out) {
|
||||
// 顺序:先 body 侧(新状态)后旧侧独有(被删除)字段,展示顺序贴近最终状态
|
||||
var keys = new LinkedHashSet<String>();
|
||||
newNode.fieldNames().forEachRemaining(keys::add);
|
||||
oldNode.fieldNames().forEachRemaining(keys::add);
|
||||
|
||||
for (var key : keys) {
|
||||
if (path.isEmpty() && ROOT_SKIPPED_KEYS.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
var childPath = path.isEmpty() ? key : path + "." + key;
|
||||
var oldValue = fieldOf(oldNode, key);
|
||||
var newValue = fieldOf(newNode, key);
|
||||
|
||||
if (oldValue.isMissingNode() && newValue.isMissingNode()) {
|
||||
continue;
|
||||
}
|
||||
if (oldValue.isMissingNode()) {
|
||||
// 显式 null 等同未设置:无实际变化
|
||||
if (newValue.isNull()) {
|
||||
continue;
|
||||
}
|
||||
expandAdded(childPath, newValue, depth + 1, out);
|
||||
continue;
|
||||
}
|
||||
if (newValue.isMissingNode()) {
|
||||
// PATCH(merge patch)语义:body 未携带的字段视为未变更;null 旧值等同未设置
|
||||
if (!removalsEnabled || oldValue.isNull()) {
|
||||
continue;
|
||||
}
|
||||
expandRemoved(childPath, oldValue, depth + 1, out);
|
||||
continue;
|
||||
}
|
||||
if (newValue.isNull() || oldValue.isNull()) {
|
||||
collectNullishChange(childPath, oldValue, newValue, removalsEnabled, depth, out);
|
||||
continue;
|
||||
}
|
||||
if (oldValue.isObject() && newValue.isObject()) {
|
||||
// 进入根级 metadata 时过滤服务端管理子键
|
||||
if (path.isEmpty() && "metadata".equals(key)) {
|
||||
oldValue = filterMetadata(oldValue);
|
||||
newValue = filterMetadata(newValue);
|
||||
}
|
||||
collectChanges(childPath, oldValue, newValue, removalsEnabled, depth + 1, out);
|
||||
continue;
|
||||
}
|
||||
// 数组 / 标量 / 类型变更:整体叶子比较
|
||||
if (!oldValue.equals(newValue)) {
|
||||
addEntry(out, childPath, ChangeType.UPDATED, oldValue, newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 两侧存在显式 null 的比较:PUT 视为置空(修改),PATCH 视为删除该字段。 */
|
||||
private static void collectNullishChange(String childPath, JsonNode oldValue,
|
||||
JsonNode newValue, boolean removalsEnabled, int depth, List<ChangeEntry> out) {
|
||||
if (oldValue.isNull() && newValue.isNull()) {
|
||||
return;
|
||||
}
|
||||
if (newValue.isNull()) {
|
||||
var type = removalsEnabled ? ChangeType.UPDATED : ChangeType.REMOVED;
|
||||
addEntry(out, childPath, type, oldValue, removalsEnabled ? newValue : null);
|
||||
return;
|
||||
}
|
||||
expandAdded(childPath, newValue, depth + 1, out);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单侧新增的子树展开:对象逐字段展开为 ADDED(含根级噪音键与 metadata 服务端子键
|
||||
* 过滤),数组/标量为一条叶子条目;显式 null 视为未设置,跳过。
|
||||
*/
|
||||
private static void expandAdded(String path, JsonNode node, int depth,
|
||||
List<ChangeEntry> out) {
|
||||
if (!node.isObject() || depth >= MAX_DEPTH) {
|
||||
addEntry(out, path, ChangeType.ADDED, null, node);
|
||||
return;
|
||||
}
|
||||
var keys = new LinkedHashSet<String>();
|
||||
node.fieldNames().forEachRemaining(keys::add);
|
||||
for (var key : keys) {
|
||||
if (path.isEmpty() && ROOT_SKIPPED_KEYS.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
var childPath = path.isEmpty() ? key : path + "." + key;
|
||||
var value = node.get(key);
|
||||
if (value.isNull()) {
|
||||
continue;
|
||||
}
|
||||
if (path.isEmpty() && "metadata".equals(key)) {
|
||||
value = filterMetadata(value);
|
||||
}
|
||||
expandAdded(childPath, value, depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** 单侧移除的子树展开:与 {@link #expandAdded} 对称,展开为 REMOVED。 */
|
||||
private static void expandRemoved(String path, JsonNode node, int depth,
|
||||
List<ChangeEntry> out) {
|
||||
if (!node.isObject() || depth >= MAX_DEPTH) {
|
||||
addEntry(out, path, ChangeType.REMOVED, node, null);
|
||||
return;
|
||||
}
|
||||
var keys = new LinkedHashSet<String>();
|
||||
node.fieldNames().forEachRemaining(keys::add);
|
||||
for (var key : keys) {
|
||||
if (path.isEmpty() && ROOT_SKIPPED_KEYS.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
var childPath = path.isEmpty() ? key : path + "." + key;
|
||||
var value = node.get(key);
|
||||
if (value.isNull()) {
|
||||
continue;
|
||||
}
|
||||
if (path.isEmpty() && "metadata".equals(key)) {
|
||||
value = filterMetadata(value);
|
||||
}
|
||||
expandRemoved(childPath, value, depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** 过滤 metadata 节点:仅保留用户可写子键;非对象原样返回(交由叶子比较)。 */
|
||||
private static JsonNode filterMetadata(JsonNode metadata) {
|
||||
if (!metadata.isObject()) {
|
||||
return metadata;
|
||||
}
|
||||
var filtered = JsonNodeFactory.instance.objectNode();
|
||||
METADATA_INCLUDED_KEYS.forEach(key -> {
|
||||
var value = metadata.get(key);
|
||||
if (value != null) {
|
||||
filtered.set(key, value);
|
||||
}
|
||||
});
|
||||
return filtered;
|
||||
}
|
||||
|
||||
private static JsonNode fieldOf(JsonNode node, String key) {
|
||||
var value = node.get(key);
|
||||
return value == null ? MissingNode.getInstance() : value;
|
||||
}
|
||||
|
||||
private static void addEntry(List<ChangeEntry> out, String field, ChangeType type,
|
||||
JsonNode oldValue, JsonNode newValue) {
|
||||
var resolvedField = field.isEmpty() ? ROOT_PLACEHOLDER_FIELD : field;
|
||||
var sensitive = isSensitiveField(resolvedField);
|
||||
var entry = new ChangeEntry();
|
||||
entry.setField(resolvedField);
|
||||
entry.setChangeType(type);
|
||||
entry.setOldValue(oldValue == null ? null : formatValue(oldValue, sensitive));
|
||||
entry.setNewValue(newValue == null ? null : formatValue(newValue, sensitive));
|
||||
out.add(entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。
|
||||
* 包内可见:登录尝试用户名提取({@link LoginAttemptCapture})兜底复用同一规则。
|
||||
*/
|
||||
static boolean isSensitiveField(String field) {
|
||||
for (var segment : field.split("\\.")) {
|
||||
if (SENSITIVE_FIELD.matcher(segment).find()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 标量取原文,对象/数组序列化为紧凑 JSON;统一脱敏与截断。 */
|
||||
private static String formatValue(JsonNode value, boolean sensitive) {
|
||||
if (sensitive) {
|
||||
return REDACTED_VALUE;
|
||||
}
|
||||
var text = value.isValueNode() ? value.asText() : value.toString();
|
||||
if (text.length() > MAX_VALUE_LENGTH) {
|
||||
return text.substring(0, MAX_VALUE_LENGTH) + TRUNCATION_SUFFIX;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 字段级变更条目({@code spec.changes} 的元素,产品设计 V2"字段级变更 diff")。
|
||||
*
|
||||
* <p>oldValue/newValue 均为格式化后的字符串(JSON 子树序列化或标量原文),
|
||||
* 传入前已经脱敏与截断;缺失侧为 null(如 ADDED 无 oldValue)。
|
||||
*/
|
||||
@Data
|
||||
public class ChangeEntry {
|
||||
|
||||
/** 字段路径(点号分隔,如 {@code spec.title}、{@code metadata.labels})。 */
|
||||
private String field;
|
||||
|
||||
/** 变更类型。 */
|
||||
private ChangeType changeType;
|
||||
|
||||
/** 变更前的值;字段为新增时为 null。 */
|
||||
private String oldValue;
|
||||
|
||||
/** 变更后的值;字段被移除时为 null。 */
|
||||
private String newValue;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
/**
|
||||
* 字段级变更类型(产品设计 V2"字段级变更 diff")。
|
||||
*/
|
||||
public enum ChangeType {
|
||||
|
||||
/** 新增字段(新建资源或 PUT 补充字段)。 */
|
||||
ADDED,
|
||||
|
||||
/** 字段值修改。 */
|
||||
UPDATED,
|
||||
|
||||
/** 字段被移除(PUT 删除字段、PATCH 显式置 null、资源删除)。 */
|
||||
REMOVED
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
|
||||
/**
|
||||
* 扩展资源路径解析(路径 → GVK + 资源名,经 SchemeManager 将 plural 映射为 GVK)。
|
||||
*
|
||||
* <p>支持两种路由形态(技术方案 D7 已源码级验证):
|
||||
* <ul>
|
||||
* <li>{@code /apis/{group}/{version}/{plural}/{name}}(group 非空的扩展模型)</li>
|
||||
* <li>{@code /api/{version}/{plural}/{name}}(空 group 核心模型,如 ConfigMap/User)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>更深层子资源路径取主资源 name 段(子资源操作写入的也是主资源);集合级路径
|
||||
* (无 name)与模型未注册(plural 无法映射 GVK)返回 null。
|
||||
*/
|
||||
final class ExtensionTargets {
|
||||
|
||||
/** 解析目标:GVK + 资源名。 */
|
||||
record Target(GroupVersionKind gvk, String name) {
|
||||
}
|
||||
|
||||
private ExtensionTargets() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析路径对应的资源目标。
|
||||
*
|
||||
* @param path 不含查询串的请求路径
|
||||
* @return GVK + 资源名;无法解析(路径形态不符、无资源名或模型未注册)时为 null
|
||||
*/
|
||||
static Target resolve(SchemeManager schemeManager, String path) {
|
||||
if (path == null || path.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
var parts = path.split("/");
|
||||
String group = "";
|
||||
String version;
|
||||
String plural;
|
||||
int nameIndex;
|
||||
if (path.startsWith(CaptureRule.APIS_PREFIX) && parts.length >= 6) {
|
||||
// parts: ["", "apis", group, version, plural, name(, 子资源...)]
|
||||
group = parts[2];
|
||||
version = parts[3];
|
||||
plural = parts[4];
|
||||
nameIndex = 5;
|
||||
} else if (path.startsWith("/api/") && parts.length >= 5) {
|
||||
// parts: ["", "api", version, plural, name(, 子资源...)]
|
||||
version = parts[2];
|
||||
plural = parts[3];
|
||||
nameIndex = 4;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (parts[nameIndex].isBlank()) {
|
||||
return null;
|
||||
}
|
||||
var resolvedGroup = group;
|
||||
var gvk = schemeManager.schemes().stream()
|
||||
.filter(scheme -> matches(scheme, resolvedGroup, version, plural))
|
||||
.map(Scheme::groupVersionKind)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
return gvk == null ? null : new Target(gvk, parts[nameIndex]);
|
||||
}
|
||||
|
||||
private static boolean matches(Scheme scheme, String group, String version, String plural) {
|
||||
var gvk = scheme.groupVersionKind();
|
||||
return gvk.group().equals(group) && gvk.version().equals(version)
|
||||
&& scheme.plural().equals(plural);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
|
||||
/**
|
||||
* HTTP 写请求标记注册表(系统内部变更,产品设计 V2)。
|
||||
*
|
||||
* <p>过滤器为所有写方法请求登记两类信息,供 {@link InternalChangeWatcher} 区分
|
||||
* "HTTP 触发的变更"(由该请求归属,勿重复记录)与"真正的系统内部变更":
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>目标标记</b>:路径可解析出的资源(GVK + name)在请求生命周期内的引用计数——
|
||||
* 请求期发起的写入由该请求归属(如 PUT /apis/.../posts/x 触发的 posts/x 更新);</li>
|
||||
* <li><b>活动宽限窗</b>:最近一次写请求活动(开始/完成)后的短窗口——设置类端点
|
||||
* (保存系统设置、插件配置、主题激活等)经路径解析与实际写入的资源不一致
|
||||
* (路径指向端点,实际写 ConfigMap/Secret),无法经目标标记归属,改用宽限窗
|
||||
* 将该窗口内设置类资源的变更视为 HTTP 副产物。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>纯内存操作(写请求开始/完成各一次字符串解析与计数增减),不阻塞请求主流程。
|
||||
*/
|
||||
@Component
|
||||
public class HttpWriteMarker {
|
||||
|
||||
/** 设置类资源宽限窗时长。 */
|
||||
static final Duration GRACE = Duration.ofSeconds(5);
|
||||
|
||||
private final SchemeManager schemeManager;
|
||||
|
||||
/** 活跃写请求的目标资源标记:key = (gvk|name),值为引用计数(并发同资源请求叠加)。 */
|
||||
private final ConcurrentHashMap<String, AtomicInteger> activeTargets =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
/** 最近一次写请求活动的纳秒时间戳(0 = 无活动);包内可见以便测试模拟时间流逝。 */
|
||||
volatile long lastActivityNanos;
|
||||
|
||||
public HttpWriteMarker(SchemeManager schemeManager) {
|
||||
this.schemeManager = schemeManager;
|
||||
}
|
||||
|
||||
/** 写方法请求开始时调用:登记目标资源标记并刷新活动时间。 */
|
||||
public void onRequestStart(ServerHttpRequest request) {
|
||||
touchActivity();
|
||||
shiftTarget(request, 1);
|
||||
}
|
||||
|
||||
/** 写方法请求响应完成时调用:解除目标资源标记并刷新活动时间。 */
|
||||
public void onRequestComplete(ServerHttpRequest request) {
|
||||
touchActivity();
|
||||
shiftTarget(request, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标资源是否正处于某个 HTTP 写请求的生命周期内:是则该变更由该请求触发,
|
||||
* 由 HTTP 过滤器归属,内部变更通道跳过。
|
||||
*/
|
||||
public boolean isMarked(GroupVersionKind gvk, String name) {
|
||||
var counter = activeTargets.get(key(gvk, name));
|
||||
return counter != null && counter.get() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否处于写请求活动宽限窗内(最近一次写请求开始或完成后的 {@value GRACE} 秒内)。
|
||||
* 设置类资源(ConfigMap/Secret)在该窗口内的变更视为 HTTP 请求副产物。
|
||||
*/
|
||||
public boolean inSettingsGraceWindow() {
|
||||
var last = lastActivityNanos;
|
||||
return last != 0 && System.nanoTime() - last < GRACE.toNanos();
|
||||
}
|
||||
|
||||
/** 设置类资源:设置型端点的内部实际写入目标(保存系统设置/插件配置/主题激活等)。 */
|
||||
static boolean isSettingsKind(GroupVersionKind gvk) {
|
||||
return gvk.group().isEmpty()
|
||||
&& ("ConfigMap".equals(gvk.kind()) || "Secret".equals(gvk.kind()));
|
||||
}
|
||||
|
||||
private void touchActivity() {
|
||||
lastActivityNanos = System.nanoTime();
|
||||
}
|
||||
|
||||
private void shiftTarget(ServerHttpRequest request, int delta) {
|
||||
var target = ExtensionTargets.resolve(schemeManager, request.getPath().value());
|
||||
if (target == null) {
|
||||
return;
|
||||
}
|
||||
var key = key(target.gvk(), target.name());
|
||||
if (delta > 0) {
|
||||
activeTargets.computeIfAbsent(key, k -> new AtomicInteger()).incrementAndGet();
|
||||
} else {
|
||||
// 计数归零移除,避免注册表随请求量增长
|
||||
activeTargets.computeIfPresent(key,
|
||||
(k, counter) -> counter.decrementAndGet() <= 0 ? null : counter);
|
||||
}
|
||||
}
|
||||
|
||||
private static String key(GroupVersionKind gvk, String name) {
|
||||
return gvk.group() + "/" + gvk.version() + "/" + gvk.kind() + "|" + name;
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.util.StringUtils;
|
||||
import run.halo.app.extension.Extension;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.Unstructured;
|
||||
import run.halo.app.extension.Watcher;
|
||||
|
||||
/**
|
||||
* 系统内部变更监听(产品设计 V2"系统内部变更"):定时发布等非 HTTP 触发的资源变更,
|
||||
* 执行者记 "system"。
|
||||
*
|
||||
* <p>通道(已按 v2.26.1 源码级验证):经 {@link ReactiveExtensionClient#watch(Watcher)}
|
||||
* 注册到全局 Watcher 组合,Halo 对每次扩展模型 create/update/delete 成功落库后派发事件
|
||||
* (回调在写入链内、boundedElastic 线程执行);仅 status 变化或无变化的更新 Halo 不派发,
|
||||
* GC 的真实移除走存储层亦不产生事件。仅处理 update/delete 两类事件:
|
||||
* 内部新建几乎均由 HTTP 触发(已被过滤器捕获),不记录以避免重复。
|
||||
*
|
||||
* <p>噪音与归属过滤:
|
||||
* <ul>
|
||||
* <li>{@code AuditLog} 自身:插件写入与保留期清理均不记录;</li>
|
||||
* <li>HTTP 写请求生命周期内的目标资源({@link HttpWriteMarker#isMarked}):由该请求
|
||||
* 归属,跳过避免重复记录;</li>
|
||||
* <li>设置类资源(ConfigMap/Secret)在写请求活动宽限窗内:视为设置型端点(保存系统
|
||||
* 设置、插件配置、主题激活)的副产物,跳过避免误归属;</li>
|
||||
* <li>插件自身配置 ConfigMap:保存插件设置走 json-config 端点,实际写的是本 ConfigMap,
|
||||
* 路径无法归属,直接排除;</li>
|
||||
* <li>diff 为空(用户可写面无变化,如 reconciler 增删 finalizer 等簿记):跳过。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>通过过滤的变更以 PUT/DELETE 语义计算字段级 diff(新旧全量状态对比)后落库,
|
||||
* 路径为该资源的规范 API 路径({@code /apis/{group}/{version}/{plural}/{name}} 或
|
||||
* {@code /api/{version}/{plural}/{name}}),结果恒为成功(事件在写入成功后派发)。
|
||||
*
|
||||
* <p>安全边界:回调运行在业务写入链内,全程捕获异常,绝不抛出影响业务写入
|
||||
* (设计原则 4);diff 计算失败降级为跳过该条记录。
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class InternalChangeWatcher implements Watcher {
|
||||
|
||||
/** AuditLog 模型的 kind(与 {@code @GVK} 注解一致,用于排除自身写入)。 */
|
||||
private static final String AUDIT_LOG_KIND = "AuditLog";
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
private final SchemeManager schemeManager;
|
||||
private final HttpWriteMarker writeMarker;
|
||||
private final AuditRecorder recorder;
|
||||
/** 插件自身配置 ConfigMap 名(保存插件设置的实际写入目标,排除避免误归属)。 */
|
||||
private final String ownConfigMapName;
|
||||
|
||||
private final AtomicBoolean disposed = new AtomicBoolean();
|
||||
|
||||
private volatile Runnable disposeHook;
|
||||
|
||||
/** 插件启动时调用:注册到全局 Watcher 组合,开始接收扩展模型变更事件。 */
|
||||
public void start() {
|
||||
client.watch(this);
|
||||
log.info("Internal change watcher started");
|
||||
}
|
||||
|
||||
/** 插件停止时调用:停止处理事件并从 Watcher 组合中移除。 */
|
||||
public void stop() {
|
||||
dispose();
|
||||
log.info("Internal change watcher stopped");
|
||||
}
|
||||
|
||||
/** 更新事件:新旧全量状态对比(PUT 语义)。 */
|
||||
@Override
|
||||
public void onUpdate(Extension oldExtension, Extension newExtension) {
|
||||
handle("PUT", oldExtension, newExtension);
|
||||
}
|
||||
|
||||
/** 删除事件:记录被删内容(DELETE 语义)。 */
|
||||
@Override
|
||||
public void onDelete(Extension extension) {
|
||||
handle("DELETE", extension, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建事件不处理:内部新建(引导初始化、插件安装自建配置等)几乎均由 HTTP 触发
|
||||
* (HTTP 新建已被过滤器捕获),不记录以避免重复;纯内部新建暂不纳入 V2 范围。
|
||||
*/
|
||||
@Override
|
||||
public void onAdd(Extension extension) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
private void handle(String method, Extension oldExtension, Extension newExtension) {
|
||||
try {
|
||||
doHandle(method, oldExtension, newExtension);
|
||||
} catch (Exception e) {
|
||||
// 回调运行在 Halo 写入链内,任何异常都不能向外抛出(否则会导致业务写入失败)
|
||||
log.warn("Failed to record internal extension change", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void doHandle(String method, Extension oldExtension, Extension newExtension) {
|
||||
if (disposed.get()) {
|
||||
return;
|
||||
}
|
||||
var extension = newExtension != null ? newExtension : oldExtension;
|
||||
if (extension == null) {
|
||||
return;
|
||||
}
|
||||
var gvk = extension.groupVersionKind();
|
||||
if (AuditLog.GROUP.equals(gvk.group()) && AUDIT_LOG_KIND.equals(gvk.kind())) {
|
||||
// 自身写入与保留期清理删除均不记录
|
||||
return;
|
||||
}
|
||||
var plural = schemeOf(gvk);
|
||||
if (plural == null) {
|
||||
return;
|
||||
}
|
||||
var metadata = extension.getMetadata();
|
||||
var name = metadata != null ? metadata.getName() : null;
|
||||
if (!StringUtils.hasText(name)) {
|
||||
return;
|
||||
}
|
||||
if (ownConfigMapName != null && HttpWriteMarker.isSettingsKind(gvk)
|
||||
&& ownConfigMapName.equals(name)) {
|
||||
return;
|
||||
}
|
||||
// HTTP 写请求生命周期内的目标资源变更由该请求归属(避免与过滤器重复记录)
|
||||
if (writeMarker.isMarked(gvk, name)) {
|
||||
return;
|
||||
}
|
||||
// 设置类资源在写请求活动宽限窗内的变更视为 HTTP 副产物(设置型端点路径与
|
||||
// 实际写入资源不一致,无法经目标标记归属)
|
||||
if (HttpWriteMarker.isSettingsKind(gvk) && writeMarker.inSettingsGraceWindow()) {
|
||||
return;
|
||||
}
|
||||
var changes = diffOf(method, oldExtension, newExtension);
|
||||
if (changes == null) {
|
||||
// 用户可写面无变化:reconciler 簿记(finalizer 等)噪音,跳过
|
||||
return;
|
||||
}
|
||||
recorder.recordSystemChange(method, plural, name, canonicalPath(gvk, plural, name),
|
||||
changes);
|
||||
}
|
||||
|
||||
/** GVK 对应的 plural(资源类型);模型未注册返回 null。 */
|
||||
private String schemeOf(GroupVersionKind gvk) {
|
||||
return schemeManager.fetch(gvk)
|
||||
.map(Scheme::plural)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段级 diff:更新按 PUT 语义(新旧全量对比,移除生效),删除按 DELETE 语义
|
||||
* (全部记移除)。只比较用户可写面(复用 {@link ChangeDiffEngine} 的降噪规则),
|
||||
* 序列化或 diff 失败降级为跳过。
|
||||
*/
|
||||
private static List<ChangeEntry> diffOf(String method, Extension oldExtension,
|
||||
Extension newExtension) {
|
||||
try {
|
||||
var oldNode = oldExtension != null
|
||||
? Unstructured.OBJECT_MAPPER.valueToTree(oldExtension) : null;
|
||||
var newNode = newExtension != null
|
||||
? Unstructured.OBJECT_MAPPER.valueToTree(newExtension) : null;
|
||||
return ChangeDiffEngine.compute(method, oldNode, newNode);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to compute diff for internal change, skip recording", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 资源的规范 API 路径:空 group 核心模型走 {@code /api/...},其余走 {@code /apis/...}。 */
|
||||
private static String canonicalPath(GroupVersionKind gvk, String plural, String name) {
|
||||
return gvk.group().isEmpty()
|
||||
? "/api/" + gvk.version() + "/" + plural + "/" + name
|
||||
: "/apis/" + gvk.group() + "/" + gvk.version() + "/" + plural + "/" + name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disposable 语义(Watcher 组合约定):dispose 后不再处理事件,并经组合注册的
|
||||
* hook 将自身从组合中移除,插件重复启停不产生残留监听。
|
||||
*/
|
||||
@Override
|
||||
public void dispose() {
|
||||
disposed.set(true);
|
||||
var hook = disposeHook;
|
||||
if (hook != null) {
|
||||
hook.run();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDisposed() {
|
||||
return disposed.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerDisposeHook(Runnable dispose) {
|
||||
disposeHook = dispose;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+177
@@ -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,71 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 登录结果判定(纯函数):Halo 2.26 登录端点的成功/失败在 HTTP 层并非「非 2xx 即失败」——
|
||||
* 表单提交的成功与失败都以 302 重定向收尾(成功 → {@code /uc} 或 2FA 页;失败 →
|
||||
* {@code /login?error=...&method=...}),仅 XHR/JSON 请求才以 200/401 区分成败
|
||||
* (见 Halo {@code LoginSuccessHandler} / {@code LoginFailureHandler})。
|
||||
* 因此登录结果须结合重定向目标判定,不能只看状态码。
|
||||
*/
|
||||
public final class LoginOutcome {
|
||||
|
||||
private LoginOutcome() {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST {@code /login} 的登录结果判定(Halo 2.26 登录端点契约):
|
||||
*
|
||||
* <ul>
|
||||
* <li>2xx → 成功(XHR/JSON 请求返回 200 + 主体 JSON);</li>
|
||||
* <li>3xx → 重定向目标查询串含 {@code error} 参数 → 失败(表单登录失败统一重定向
|
||||
* 到 {@code /login?error=invalid-credential&method=...} 等,含无值的
|
||||
* {@code /login?error&method=...});其余重定向目标(成功 → {@code /uc}、
|
||||
* 两步验证 → {@code /challenges/two-factor/totp})→ 成功;</li>
|
||||
* <li>其余(401 等)→ 失败(XHR 登录失败;状态码缺失/为 0 亦按失败处理)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
public static boolean isFailure(Integer statusCode, URI location) {
|
||||
if (statusCode == null) {
|
||||
return true;
|
||||
}
|
||||
if (statusCode >= 200 && statusCode < 300) {
|
||||
return false;
|
||||
}
|
||||
if (statusCode >= 300 && statusCode < 400) {
|
||||
return location != null && hasErrorParam(location.getRawQuery());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败回显判定:{@code GET /login} 且查询串含 {@code error} 参数。
|
||||
* 登录失败后 Halo 重定向到带 error 参数的登录页,浏览器随后渲染该页(HTTP 200);
|
||||
* 该请求是失败登录的回显而非独立操作,审计记录须标注登录失败而非「登录成功 200」。
|
||||
*/
|
||||
public static boolean isFailureEcho(String fullPath) {
|
||||
if (fullPath == null) {
|
||||
return false;
|
||||
}
|
||||
var queryStart = fullPath.indexOf('?');
|
||||
if (queryStart < 0 || !"/login".equals(fullPath.substring(0, queryStart))) {
|
||||
return false;
|
||||
}
|
||||
return hasErrorParam(fullPath.substring(queryStart + 1));
|
||||
}
|
||||
|
||||
/** 查询串是否含 {@code error} 参数(可为无值形式 {@code error})。 */
|
||||
private static boolean hasErrorParam(String query) {
|
||||
if (query == null || query.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Arrays.stream(query.split("&"))
|
||||
.map(pair -> {
|
||||
var idx = pair.indexOf('=');
|
||||
return idx < 0 ? pair : pair.substring(0, idx);
|
||||
})
|
||||
.anyMatch("error"::equals);
|
||||
}
|
||||
}
|
||||
+41
-23
@@ -3,7 +3,6 @@ package run.halo.operationaudit.audit;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.shouldCapture;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -15,15 +14,25 @@ import reactor.util.context.ContextView;
|
||||
import run.halo.app.security.AfterSecurityWebFilter;
|
||||
|
||||
/**
|
||||
* 审计捕获过滤器(技术方案 D1 / 5.1)。
|
||||
* 审计捕获过滤器(技术方案 D1 / 5.1),仅负责 {@code /apis/**} 写操作。
|
||||
*
|
||||
* <p>以 {@link AfterSecurityWebFilter} 扩展点注册:位于 Security 过滤链最后、认证之后,
|
||||
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。
|
||||
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。认证端点
|
||||
* ({@code /login}、{@code /logout})不在此过滤器捕获——表单登录/登出过滤器命中请求后
|
||||
* 直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到(P0 缺陷实测);
|
||||
* 详见 {@link AuthEndpointAuditWebFilter}。
|
||||
*
|
||||
* <p>注意 WebFlux 无 ThreadLocal:用户名提取经 {@code transformDeferredContextual} 在订阅
|
||||
* 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。
|
||||
* 上下文中的值是 {@code Mono<SecurityContext>}(由 ReactorContextWebFilter 写入),
|
||||
* 可独立订阅,因此记录时再解析操作者。
|
||||
*
|
||||
* <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON
|
||||
* 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。
|
||||
*
|
||||
* <p>系统内部变更(产品设计 V2):未被捕获规则命中的写方法请求({@code /api/**}
|
||||
* 核心模型)同样经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
||||
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -33,33 +42,51 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
private static final String ANONYMOUS_USER = "anonymousUser";
|
||||
|
||||
private final AuditRecorder recorder;
|
||||
private final ChangeCaptureManager captureManager;
|
||||
private final HttpWriteMarker writeMarker;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
var request = exchange.getRequest();
|
||||
var path = request.getPath().value();
|
||||
if (!shouldCapture(path, request.getMethod().name())) {
|
||||
var method = request.getMethod().name();
|
||||
if (!shouldCapture(path, method)) {
|
||||
// 未命中捕获规则的写方法请求(/api/** 核心模型等)不记录,
|
||||
// 但仍登记标记:请求期触发的资源变更由该请求归属
|
||||
if (CaptureRule.WRITE_METHODS.contains(method)) {
|
||||
writeMarker.onRequestStart(request);
|
||||
return chain.filter(exchange)
|
||||
.doFinally(signal -> writeMarker.onRequestComplete(request));
|
||||
}
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
writeMarker.onRequestStart(request);
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
return chain.filter(exchange)
|
||||
var capture = new ChangeCapture();
|
||||
return captureManager.prepare(exchange, snapshot, capture)
|
||||
.flatMap(chain::filter)
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> operatorOf(ctx, path).subscribe(
|
||||
signal -> {
|
||||
writeMarker.onRequestComplete(request);
|
||||
var statusCode = statusOf(exchange);
|
||||
operatorOf(ctx).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
recorder.record(snapshot, statusOf(exchange), username);
|
||||
if (shouldRecord(username)) {
|
||||
recorder.record(snapshot, capture, statusCode, username,
|
||||
null, false);
|
||||
}
|
||||
},
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ })));
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从订阅上下文解析操作者用户名。
|
||||
*
|
||||
* <p>上下文中无 SecurityContext(匿名请求)→ 空用户名;登录端点的匿名请求记“未知用户”。
|
||||
* <p>上下文中无 SecurityContext 或认证无用户名 → 记“未知用户”占位。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Mono<String> operatorOf(ContextView ctx, String path) {
|
||||
private static Mono<String> operatorOf(ContextView ctx) {
|
||||
return ctx.getOrEmpty(SecurityContext.class)
|
||||
.map(value -> ((Mono<SecurityContext>) value)
|
||||
.flatMap(sc -> Mono.justOrEmpty(sc != null ? sc.getAuthentication() : null))
|
||||
@@ -70,13 +97,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录决策(技术方案 D1):匿名判断在记录时做——
|
||||
* {@code /apis/**} 下认证后仍为匿名主体(401/403 场景)的请求跳过不记。
|
||||
* 记录决策(技术方案 D1):匿名判断在记录时做——认证后仍为匿名主体
|
||||
* (401/403 场景)的请求跳过不记。
|
||||
*/
|
||||
private static boolean shouldRecord(String path, String username) {
|
||||
if (CaptureRule.isAuthEndpoint(path)) {
|
||||
return true;
|
||||
}
|
||||
private static boolean shouldRecord(String username) {
|
||||
return StringUtils.hasText(username) && !ANONYMOUS_USER.equals(username)
|
||||
&& !AuditLogSpec.UNKNOWN_USERNAME.equals(username);
|
||||
}
|
||||
@@ -85,10 +109,4 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
var status = exchange.getResponse().getStatusCode();
|
||||
return status != null ? status.value() : 0;
|
||||
}
|
||||
|
||||
/** 仅供测试与未来扩展使用:判断认证主体是否匿名。 */
|
||||
static boolean isAnonymous(Authentication authentication) {
|
||||
return authentication == null || !StringUtils.hasText(authentication.getName())
|
||||
|| ANONYMOUS_USER.equals(authentication.getName());
|
||||
}
|
||||
}
|
||||
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 操作描述(这条操作真正干了什么):由 method / resourceType / path 推导中文短语,
|
||||
* 如 登录、登出、新建用户、修改文章、发布文章、启用插件、修改密码。
|
||||
*
|
||||
* <p>语义动作标注(产品设计 V2):捕获时由 {@link #actionOf} 推导语义动作键落库
|
||||
* ({@code spec.action},如 login/create/publish,可空),注册索引后支持按语义动作筛选;
|
||||
* 展示/导出由 {@link #describe} 推导中文短语,历史记录(无 action 字段)同样按
|
||||
* method/path 现场推导,不受影响。
|
||||
*
|
||||
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code deriveAction} / {@code describeOperation}
|
||||
* 保持一致(同一套 RESOURCE_LABELS / METHOD_ACTIONS / SEGMENT_ACTIONS / ACTION_PHRASES /
|
||||
* ACTION_VERBS 映射与子动作解析规则),两处需同步修改。未识别的子动作回退为
|
||||
* 「method 动词 + 资源名」,未识别的资源类型直接使用原始 resourceType。
|
||||
*/
|
||||
final class OperationDescription {
|
||||
|
||||
/** 资源类型的中文展示名(未知类型回退原始值)。 */
|
||||
private static final Map<String, String> RESOURCE_LABELS = Map.ofEntries(
|
||||
Map.entry("posts", "文章"),
|
||||
Map.entry("singlepages", "页面"),
|
||||
Map.entry("comments", "评论"),
|
||||
Map.entry("replies", "回复"),
|
||||
Map.entry("users", "用户"),
|
||||
Map.entry("roles", "角色"),
|
||||
Map.entry("settings", "设置"),
|
||||
Map.entry("configmaps", "配置"),
|
||||
Map.entry("plugins", "插件"),
|
||||
Map.entry("themes", "主题"),
|
||||
Map.entry("attachments", "附件"),
|
||||
Map.entry("menus", "菜单"),
|
||||
Map.entry("categories", "分类"),
|
||||
Map.entry("tags", "标签"));
|
||||
|
||||
/** 动作方法 → 语义动作键(未知方法无键)。 */
|
||||
private static final Map<String, String> METHOD_ACTIONS = Map.of(
|
||||
"POST", "create",
|
||||
"PUT", "update",
|
||||
"PATCH", "update",
|
||||
"DELETE", "delete",
|
||||
"GET", "view");
|
||||
|
||||
/**
|
||||
* 子资源动作段({@code /apis/.../{plural}/{name}/{action}} 的 action)→ 语义动作键。
|
||||
* activation 与 enable 语义相同(激活/启用),归并为同一动作键便于统一筛选。
|
||||
*/
|
||||
private static final Map<String, String> SEGMENT_ACTIONS = Map.ofEntries(
|
||||
Map.entry("publish", "publish"),
|
||||
Map.entry("unpublish", "unpublish"),
|
||||
Map.entry("recycle", "recycle"),
|
||||
Map.entry("restore", "restore"),
|
||||
Map.entry("enable", "enable"),
|
||||
Map.entry("activation", "enable"),
|
||||
Map.entry("disable", "disable"),
|
||||
Map.entry("upgrade", "upgrade"),
|
||||
Map.entry("uninstall", "uninstall"),
|
||||
Map.entry("reload", "reload"),
|
||||
Map.entry("reply", "reply"),
|
||||
Map.entry("recalculate", "recalculate"),
|
||||
Map.entry("password", "password"),
|
||||
Map.entry("resetpassword", "resetpassword"));
|
||||
|
||||
/**
|
||||
* 登录失败语义动作键:POST {@code /login} 失败(重定向目标含 error 参数或 4xx/5xx)
|
||||
* 与登录失败回显(GET {@code /login?error=...},HTTP 200)落库标注,供列表红色
|
||||
* 标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||
*/
|
||||
static final String LOGIN_FAILURE_ACTION = "login-failure";
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼接资源名)。 */
|
||||
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
|
||||
Map.entry("login", "登录"),
|
||||
Map.entry(LOGIN_FAILURE_ACTION, "登录失败"),
|
||||
Map.entry("logout", "登出"),
|
||||
Map.entry("auth", "认证操作"),
|
||||
Map.entry("password", "修改密码"),
|
||||
Map.entry("resetpassword", "重置密码"));
|
||||
|
||||
/** 语义动作键 → 动词(与资源中文名拼接成短语,如 publish + 文章 = 发布文章)。 */
|
||||
private static final Map<String, String> ACTION_VERBS = Map.ofEntries(
|
||||
Map.entry("create", "新建"),
|
||||
Map.entry("update", "修改"),
|
||||
Map.entry("delete", "删除"),
|
||||
Map.entry("view", "查看"),
|
||||
Map.entry("publish", "发布"),
|
||||
Map.entry("unpublish", "取消发布"),
|
||||
Map.entry("recycle", "移入回收站"),
|
||||
Map.entry("restore", "恢复"),
|
||||
Map.entry("enable", "启用"),
|
||||
Map.entry("disable", "停用"),
|
||||
Map.entry("upgrade", "升级"),
|
||||
Map.entry("uninstall", "卸载"),
|
||||
Map.entry("reload", "重载"),
|
||||
Map.entry("reply", "回复"),
|
||||
Map.entry("recalculate", "重新统计"));
|
||||
|
||||
private OperationDescription() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导语义动作键(捕获时落库标注,供筛选):登录/登出/认证操作由路径判定,
|
||||
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 无法识别(未知方法等)返回 null,记录不标注。
|
||||
*/
|
||||
static String actionOf(String method, String resourceType, String path) {
|
||||
var cleanPath = pathWithoutQuery(path);
|
||||
if ("/login".equals(cleanPath)) {
|
||||
return "login";
|
||||
}
|
||||
if ("/logout".equals(cleanPath)) {
|
||||
return "logout";
|
||||
}
|
||||
if ("auth".equals(resourceType)) {
|
||||
return "auth";
|
||||
}
|
||||
// /apis/{group}/{version}/{plural}/{name}/{action}:
|
||||
// 去掉空段后 segments 为 [apis, group, version, plural, name, action],
|
||||
// 子动作段为 segments[5]
|
||||
var segments = Arrays.stream(cleanPath.split("/"))
|
||||
.filter(segment -> !segment.isEmpty())
|
||||
.toArray(String[]::new);
|
||||
if (segments.length >= 6) {
|
||||
var action = SEGMENT_ACTIONS.get(segments[5].toLowerCase());
|
||||
if (action != null) {
|
||||
return action;
|
||||
}
|
||||
}
|
||||
return METHOD_ACTIONS.get(method);
|
||||
}
|
||||
|
||||
/** 由语义动作键推导中文描述;键为 null 或未识别返回 null(调用方回退 method 推导)。 */
|
||||
static String describeAction(String action, String resourceType) {
|
||||
if (action == null) {
|
||||
return null;
|
||||
}
|
||||
var phrase = ACTION_PHRASES.get(action);
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
var verb = ACTION_VERBS.get(action);
|
||||
return verb == null ? null : verb + resourceLabel(resourceType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导操作中文描述(展示/导出用):优先语义动作键,识别失败回退为
|
||||
* 「method 动词 + 资源名」。
|
||||
*/
|
||||
static String describe(String method, String resourceType, String path) {
|
||||
var phrase = describeAction(actionOf(method, resourceType, path), resourceType);
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
return method + resourceLabel(resourceType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 由落库 spec 推导操作中文描述(导出用):优先落库的语义动作标注(含登录失败
|
||||
* 标注——回显页 HTTP 200 无法由路径重新推导出失败),无标注或未识别时回退为
|
||||
* method/path 现场推导(与前端 {@code describeOperation} 一致)。
|
||||
*/
|
||||
static String describe(AuditLogSpec spec) {
|
||||
var phrase = describeAction(spec.getAction(), spec.getResourceType());
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
return describe(spec.getMethod(), spec.getResourceType(), spec.getPath());
|
||||
}
|
||||
|
||||
private static String resourceLabel(String resourceType) {
|
||||
return RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
|
||||
}
|
||||
|
||||
/** 剥离路径的查询串(spec.path 存的是含查询串的完整路径)。 */
|
||||
private static String pathWithoutQuery(String path) {
|
||||
if (path == null || path.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
var queryStart = path.indexOf('?');
|
||||
return queryStart >= 0 ? path.substring(0, queryStart) : path;
|
||||
}
|
||||
}
|
||||
+18
-2
@@ -5,7 +5,8 @@ package run.halo.operationaudit.housekeeping;
|
||||
*
|
||||
* <p>取值全部经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值。
|
||||
*/
|
||||
public record AuditSettings(Boolean enabled, Integer retentionDays) {
|
||||
public record AuditSettings(Boolean enabled, Integer retentionDays, Boolean recordChanges,
|
||||
Boolean recordSystemChanges) {
|
||||
|
||||
/** ConfigMap 中的配置组名。 */
|
||||
public static final String GROUP = "audit";
|
||||
@@ -19,6 +20,12 @@ public record AuditSettings(Boolean enabled, Integer retentionDays) {
|
||||
/** 审计开关默认值。 */
|
||||
public static final boolean DEFAULT_ENABLED = true;
|
||||
|
||||
/** 字段级变更记录默认值(字段级变更 diff,产品设计 V2)。 */
|
||||
public static final boolean DEFAULT_RECORD_CHANGES = true;
|
||||
|
||||
/** 系统内部变更记录默认值(系统内部变更,产品设计 V2)。 */
|
||||
public static final boolean DEFAULT_RECORD_SYSTEM_CHANGES = true;
|
||||
|
||||
public boolean enabledOrDefault() {
|
||||
return enabled == null ? DEFAULT_ENABLED : enabled;
|
||||
}
|
||||
@@ -30,7 +37,16 @@ public record AuditSettings(Boolean enabled, Integer retentionDays) {
|
||||
return retentionDays;
|
||||
}
|
||||
|
||||
public boolean recordChangesOrDefault() {
|
||||
return recordChanges == null ? DEFAULT_RECORD_CHANGES : recordChanges;
|
||||
}
|
||||
|
||||
public boolean recordSystemChangesOrDefault() {
|
||||
return recordSystemChanges == null ? DEFAULT_RECORD_SYSTEM_CHANGES : recordSystemChanges;
|
||||
}
|
||||
|
||||
public static AuditSettings defaults() {
|
||||
return new AuditSettings(DEFAULT_ENABLED, DEFAULT_RETENTION_DAYS);
|
||||
return new AuditSettings(DEFAULT_ENABLED, DEFAULT_RETENTION_DAYS, DEFAULT_RECORD_CHANGES,
|
||||
DEFAULT_RECORD_SYSTEM_CHANGES);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ rules:
|
||||
# verbs 仅 get/list(技术方案 D4):被授权角色技术上也无法删除/编辑审计记录
|
||||
# auditlogs/query 为自有查询端点 /apis/.../auditlogs/-/query 的 RBAC 资源组合
|
||||
# (资源 auditlogs + 子资源 query,请求动词 get)
|
||||
- apiGroups: ["audit.example.com"]
|
||||
resources: ["auditlogs", "auditlogs/query"]
|
||||
# auditlogs/export 为自有导出端点 /apis/.../auditlogs/-/export 的 RBAC 资源组合
|
||||
# (资源 auditlogs + 子资源 export,请求动词 get;只读导出,无写入语义)
|
||||
- apiGroups: ["audit.guichumo.com"]
|
||||
resources: ["auditlogs", "auditlogs/query", "auditlogs/export"]
|
||||
verbs: ["get", "list"]
|
||||
|
||||
@@ -12,6 +12,16 @@ spec:
|
||||
name: enabled
|
||||
value: true
|
||||
help: 关闭后不再记录新的操作审计日志,已有记录仍可查询
|
||||
- $formkit: checkbox
|
||||
label: 记录字段变更
|
||||
name: recordChanges
|
||||
value: true
|
||||
help: 对成功的新建/修改/删除操作记录字段级新旧值(敏感字段自动脱敏),关闭后仅记录操作元信息
|
||||
- $formkit: checkbox
|
||||
label: 记录系统内部变更
|
||||
name: recordSystemChanges
|
||||
value: true
|
||||
help: 记录定时发布等非页面操作触发的资源变更(执行者记为 system),关闭后仅记录页面/API 操作
|
||||
- $formkit: number
|
||||
label: 保留天数
|
||||
name: retentionDays
|
||||
@@ -19,3 +29,38 @@ spec:
|
||||
step: 1
|
||||
value: 90
|
||||
help: 超过保留期的审计记录将在每日自动清理(最小 7 天)
|
||||
- group: alerts
|
||||
label: 告警通知
|
||||
formSchema:
|
||||
- $formkit: checkbox
|
||||
label: 启用登录失败告警
|
||||
name: enabled
|
||||
value: false
|
||||
help: 统计窗口内登录失败达到触发阈值时向 Webhook 地址推送 JSON 告警(独立于审计开关,默认关闭)
|
||||
- $formkit: secret
|
||||
label: Webhook 地址
|
||||
name: webhookSecretName
|
||||
descriptionPreset: 操作审计告警 Webhook
|
||||
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
|
||||
label: 触发阈值(次)
|
||||
name: thresholdCount
|
||||
min: 1
|
||||
step: 1
|
||||
value: 5
|
||||
help: 统计窗口内累计登录失败达到该次数即触发一次告警
|
||||
- $formkit: number
|
||||
label: 统计窗口(分钟)
|
||||
name: windowMinutes
|
||||
min: 1
|
||||
step: 1
|
||||
value: 5
|
||||
help: 失败次数的累计窗口;告警后窗口重开(下次告警需再次达到阈值),登录成功立即清零
|
||||
|
||||
@@ -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"
|
||||
author:
|
||||
name: Guichumo
|
||||
website: http://101.43.163.221:3000/836061373/halo-ops-audit
|
||||
logo: logo.svg
|
||||
homepage: http://101.43.163.221:3000/836061373/halo-ops-audit
|
||||
repo: http://101.43.163.221:3000/836061373/halo-ops-audit
|
||||
issues: http://101.43.163.221:3000/836061373/halo-ops-audit/issues
|
||||
displayName: "操作审计"
|
||||
description: "记录后台写操作与登录事件,回答谁、在什么时候、对什么资源、做了什么操作、结果如何。"
|
||||
settingName: operation-audit-settings
|
||||
configMapName: operation-audit-configmap
|
||||
license:
|
||||
- name: "GPL-3.0"
|
||||
url: "https://www.gnu.org/licenses/gpl-3.0.html"
|
||||
|
||||
+13
-5
@@ -20,10 +20,12 @@ import run.halo.app.extension.index.IndexSpecs;
|
||||
import run.halo.app.extension.index.ValueIndexSpec;
|
||||
import run.halo.app.plugin.PluginContext;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
import run.halo.operationaudit.audit.InternalChangeWatcher;
|
||||
import run.halo.operationaudit.housekeeping.RetentionCleaner;
|
||||
|
||||
/**
|
||||
* 插件生命周期测试:启动注册 {@link AuditLog} 模型与全部索引,停止注销。
|
||||
* 插件生命周期测试:启动注册 {@link AuditLog} 模型与全部索引、启动清理调度与
|
||||
* 系统内部变更监听,停止时全部反向注销。
|
||||
*/
|
||||
class OperationAuditPluginTest {
|
||||
|
||||
@@ -31,13 +33,14 @@ class OperationAuditPluginTest {
|
||||
void shouldRegisterAuditLogWithExpectedIndexesOnStart() {
|
||||
var schemeManager = mock(SchemeManager.class);
|
||||
var cleaner = mock(RetentionCleaner.class);
|
||||
var watcher = mock(InternalChangeWatcher.class);
|
||||
var registeredSpecs = new AtomicReference<Consumer<IndexSpecs<AuditLog>>>();
|
||||
doAnswer(invocation -> {
|
||||
registeredSpecs.set(invocation.getArgument(1));
|
||||
return null;
|
||||
}).when(schemeManager).register(eq(AuditLog.class), any());
|
||||
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager, cleaner);
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager, cleaner, watcher);
|
||||
plugin.start();
|
||||
|
||||
var recordingSpecs = new RecordingIndexSpecs();
|
||||
@@ -47,23 +50,28 @@ class OperationAuditPluginTest {
|
||||
"spec.username",
|
||||
"spec.resourceType",
|
||||
"spec.method",
|
||||
"spec.action",
|
||||
"spec.statusCode",
|
||||
"spec.resourceName",
|
||||
"spec.path");
|
||||
// 系统内部变更监听随插件启动注册(产品设计 V2"系统内部变更")
|
||||
verify(watcher).start();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldStopCleanerAndUnregisterSchemeOnStop() {
|
||||
void shouldStopCleanerWatcherAndUnregisterSchemeOnStop() {
|
||||
var schemeManager = mock(SchemeManager.class);
|
||||
var cleaner = mock(RetentionCleaner.class);
|
||||
var watcher = mock(InternalChangeWatcher.class);
|
||||
var scheme = mock(Scheme.class);
|
||||
var gvk = new GroupVersionKind("audit.example.com", "v1alpha1", "AuditLog");
|
||||
var gvk = new GroupVersionKind("audit.guichumo.com", "v1alpha1", "AuditLog");
|
||||
org.mockito.Mockito.when(schemeManager.fetch(gvk))
|
||||
.thenReturn(java.util.Optional.of(scheme));
|
||||
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager, cleaner);
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager, cleaner, watcher);
|
||||
plugin.stop();
|
||||
|
||||
verify(watcher).stop();
|
||||
verify(cleaner).stop();
|
||||
verify(schemeManager).unregister(scheme);
|
||||
}
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
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.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.Secret;
|
||||
import run.halo.app.plugin.ReactiveSettingFetcher;
|
||||
|
||||
/**
|
||||
* 告警设置 TTL 缓存测试(与审计设置同款模式):命中缓存、失败/缺省回退默认(告警关闭);
|
||||
* Webhook 地址 Secret 解析:未配置引用 / Secret 不存在 / 缺字段 / 空白值均 fail closed
|
||||
* (错误信号,绝不发送),字段值去除首尾空白。
|
||||
*/
|
||||
class AlertSettingProviderTest {
|
||||
|
||||
private final ReactiveSettingFetcher fetcher = mock(ReactiveSettingFetcher.class);
|
||||
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
|
||||
void shouldCacheWithinTtl() {
|
||||
var fetchCount = new AtomicInteger(0);
|
||||
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
|
||||
.thenAnswer(inv -> {
|
||||
fetchCount.incrementAndGet();
|
||||
return Mono.just(new AlertSettings(true, "webhook-secret", 3, 2));
|
||||
});
|
||||
|
||||
var first = provider.get().block();
|
||||
var second = provider.get().block();
|
||||
|
||||
assertThat(first).extracting(AlertSettings::enabled, AlertSettings::webhookSecretName,
|
||||
AlertSettings::thresholdCount, AlertSettings::windowMinutes)
|
||||
.containsExactly(true, "webhook-secret", 3, 2);
|
||||
assertThat(second).isSameAs(first);
|
||||
assertThat(fetchCount.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToDefaultsWhenFetchFails() {
|
||||
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
|
||||
.thenReturn(Mono.error(new IllegalStateException("configmap missing")));
|
||||
|
||||
var settings = provider.get().block();
|
||||
|
||||
assertThat(settings).isEqualTo(AlertSettings.defaults());
|
||||
assertThat(settings.enabledOrDefault()).isFalse();
|
||||
assertThat(settings.webhookSecretNameOrDefault()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToDefaultsWhenConfigMissing() {
|
||||
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
|
||||
.thenReturn(Mono.empty());
|
||||
|
||||
assertThat(provider.get().block()).isEqualTo(AlertSettings.defaults());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRefetchAfterExpiry() {
|
||||
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
|
||||
.thenReturn(Mono.just(AlertSettings.defaults()));
|
||||
|
||||
provider.get().block();
|
||||
|
||||
// 手动使缓存过期(TTL 为 60s,等待必然不现实,直接构造过期条目)
|
||||
provider.cache = new AlertSettingProvider.CacheEntry(AlertSettings.defaults(), 0);
|
||||
|
||||
provider.get().block();
|
||||
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("缺少");
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 告警设置归一测试:缺省/非法值回退默认;凭据安全要求下本记录只持有 Secret 引用名
|
||||
* (真实 Webhook 地址由 AlertSettingProvider 从 Secret 解析)。
|
||||
*/
|
||||
class AlertSettingsTest {
|
||||
|
||||
@Test
|
||||
void shouldFallbackToDefaultsWhenMissing() {
|
||||
var settings = AlertSettings.defaults();
|
||||
|
||||
assertThat(settings.enabledOrDefault()).isFalse();
|
||||
assertThat(settings.webhookSecretNameOrDefault()).isNull();
|
||||
assertThat(settings.thresholdCountOrDefault()).isEqualTo(5);
|
||||
assertThat(settings.windowMinutesOrDefault()).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNormalizeSecretName() {
|
||||
assertThat(new AlertSettings(true, " operation-audit-webhook ", null, null)
|
||||
.webhookSecretNameOrDefault()).isEqualTo("operation-audit-webhook");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectBlankSecretName() {
|
||||
assertThat(new AlertSettings(true, null, null, null).webhookSecretNameOrDefault())
|
||||
.isNull();
|
||||
assertThat(new AlertSettings(true, "", null, null).webhookSecretNameOrDefault())
|
||||
.isNull();
|
||||
assertThat(new AlertSettings(true, " ", null, null).webhookSecretNameOrDefault())
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNormalizeThresholdCount() {
|
||||
assertThat(new AlertSettings(null, null, null, null).thresholdCountOrDefault())
|
||||
.isEqualTo(5);
|
||||
assertThat(new AlertSettings(null, null, 0, null).thresholdCountOrDefault())
|
||||
.isEqualTo(5);
|
||||
assertThat(new AlertSettings(null, null, -3, null).thresholdCountOrDefault())
|
||||
.isEqualTo(5);
|
||||
assertThat(new AlertSettings(null, null, 1, null).thresholdCountOrDefault()).isEqualTo(1);
|
||||
assertThat(new AlertSettings(null, null, 10, null).thresholdCountOrDefault())
|
||||
.isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNormalizeWindowMinutes() {
|
||||
assertThat(new AlertSettings(null, null, null, null).windowMinutesOrDefault())
|
||||
.isEqualTo(5);
|
||||
assertThat(new AlertSettings(null, null, null, 0).windowMinutesOrDefault()).isEqualTo(5);
|
||||
assertThat(new AlertSettings(null, null, null, 1).windowMinutesOrDefault()).isEqualTo(1);
|
||||
assertThat(new AlertSettings(null, null, null, 30).windowMinutesOrDefault()).isEqualTo(30);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRespectExplicitEnabledFlag() {
|
||||
assertThat(new AlertSettings(null, "webhook-secret", null, null).enabledOrDefault())
|
||||
.isFalse();
|
||||
assertThat(new AlertSettings(false, "webhook-secret", null, null).enabledOrDefault())
|
||||
.isFalse();
|
||||
assertThat(new AlertSettings(true, "webhook-secret", null, null).enabledOrDefault())
|
||||
.isTrue();
|
||||
}
|
||||
}
|
||||
+123
@@ -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);
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/**
|
||||
* Webhook 推送集成测试(JDK 内置 HttpServer 走真实 HTTP):
|
||||
*
|
||||
* <p>HTTP 机制经 {@code sendToTarget} 直接驱动(目标已完成校验、地址钉定)——
|
||||
* JSON POST 负载可达、非 2xx / 连接失败 / 校验失败均归一为结果或静默降级不抛出;
|
||||
* 结果化推送(功能评审 P0-2)返回送达与否 + 原因摘要,同样永不抛出。
|
||||
*
|
||||
* <p>出站安全链路经 {@code sendForResult} 驱动(真实路径):回环/内网等受限地址
|
||||
* 在 SSRF 校验阶段即拒绝(不建连),建连钉定校验地址(DNS rebinding 防护——
|
||||
* 主机名 localhost + 钉定 127.0.0.2 的用例证明建连走钉定地址而非 DNS 结果)。
|
||||
*/
|
||||
class AlertWebhookSenderTest {
|
||||
|
||||
private HttpServer server;
|
||||
|
||||
private final AlertWebhookSender sender = new AlertWebhookSender(new OutboundUrlGuard());
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (server != null) {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在指定回环地址上启动测试 HTTP 服务,返回实际端口。 */
|
||||
private int startServer(InetAddress bind, int status, AtomicReference<byte[]> body,
|
||||
AtomicReference<String> contentType, CountDownLatch received) throws Exception {
|
||||
var httpServer = HttpServer.create(new InetSocketAddress(bind, 0), 0);
|
||||
httpServer.createContext("/hook", exchange -> {
|
||||
body.set(exchange.getRequestBody().readAllBytes());
|
||||
contentType.set(exchange.getRequestHeaders().getFirst("Content-Type"));
|
||||
exchange.sendResponseHeaders(status, -1);
|
||||
exchange.close();
|
||||
received.countDown();
|
||||
});
|
||||
httpServer.start();
|
||||
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
|
||||
void shouldPostJsonPayloadViaPinnedTarget() throws Exception {
|
||||
var body = new AtomicReference<byte[]>();
|
||||
var contentType = new AtomicReference<String>();
|
||||
var received = new CountDownLatch(1);
|
||||
var port = startServer(InetAddress.getLoopbackAddress(), 200, body, contentType,
|
||||
received);
|
||||
var url = "http://127.0.0.1:" + port + "/hook";
|
||||
|
||||
// fire-and-forget 语义:订阅即异步执行,不等待结果
|
||||
sender.sendToTarget(pinnedTarget(url),
|
||||
Map.of("title", "操作审计告警:登录失败", "failures", 3)).subscribe();
|
||||
|
||||
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
assertThat(contentType.get()).contains("application/json");
|
||||
var payload = new ObjectMapper().readTree(body.get());
|
||||
assertThat(payload.get("title").asText()).isEqualTo("操作审计告警:登录失败");
|
||||
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
|
||||
void shouldNotThrowOnNon2xxResponse() throws Exception {
|
||||
var body = new AtomicReference<byte[]>();
|
||||
var contentType = new AtomicReference<String>();
|
||||
var received = new CountDownLatch(1);
|
||||
var port = startServer(InetAddress.getLoopbackAddress(), 500, body, contentType,
|
||||
received);
|
||||
var url = "http://127.0.0.1:" + port + "/hook";
|
||||
|
||||
assertThatCode(() -> sender.sendToTarget(pinnedTarget(url), Map.of()).subscribe())
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
// 500 响应同样送达(接收方先收到请求才返回 500),随后静默降级为日志
|
||||
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
|
||||
void shouldReturnFailureResultWhenTargetUnreachable() throws Exception {
|
||||
// 服务监听后立即停止(端口保留);或直接钉定无监听端口 → 连接失败归一为失败结果
|
||||
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();
|
||||
assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.time.Duration;
|
||||
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.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.operationaudit.audit.RequestSnapshot;
|
||||
|
||||
/**
|
||||
* 登录失败告警阈值窗口测试(产品设计 V2「告警通知」):
|
||||
* 达阈值告警一次、告警后重开窗口、窗口过期重开、登录成功清零、开关与地址降级。
|
||||
* Webhook 地址凭据存于 Halo Secret:handle 先经 AlertSettingProvider 解析地址,
|
||||
* 未配置/解析失败则静默跳过(不计数也不告警)。
|
||||
*/
|
||||
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 AlertSettingProvider settingProvider;
|
||||
private AlertWebhookSender sender;
|
||||
private LoginFailureAlertService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
settingProvider = mock(AlertSettingProvider.class);
|
||||
sender = mock(AlertWebhookSender.class);
|
||||
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) {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(
|
||||
new AlertSettings(true, WEBHOOK_REF, threshold, windowMinutes)));
|
||||
}
|
||||
|
||||
private static RequestSnapshot loginSnapshot() {
|
||||
return RequestSnapshot.of(MockServerHttpRequest.post("http://localhost/login")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.header("User-Agent", "UA-1")
|
||||
.build());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> capturedPayload() {
|
||||
var captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(sender).send(eq(WEBHOOK_URL), captor.capture());
|
||||
return (Map<String, Object>) captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSendAlertWhenFailuresReachThreshold() {
|
||||
enableAlerts(3, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat(payload.get("type")).isEqualTo("login-failure");
|
||||
assertThat(payload.get("title")).isEqualTo("操作审计告警:登录失败");
|
||||
assertThat((String) payload.get("content"))
|
||||
.contains("5 分钟内出现 3 次登录失败")
|
||||
.contains("127.0.0.1")
|
||||
.contains("UA-1");
|
||||
assertThat((String) payload.get("timestamp")).isNotBlank();
|
||||
assertThat((Map<String, Object>) payload.get("data"))
|
||||
.containsEntry("failures", 3)
|
||||
.containsEntry("windowMinutes", 5)
|
||||
.containsEntry("remoteIp", "127.0.0.1")
|
||||
.containsEntry("userAgent", "UA-1")
|
||||
.containsEntry("attemptedUsername", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAlertOncePerWindow() {
|
||||
enableAlerts(3, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
// 达到阈值告警一次后窗口重开:后续失败需重新累计,不会连环告警
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
verify(sender, times(1)).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAlertAgainAfterSecondWindow() {
|
||||
var settings = settings(2, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
// 告警后窗口重开,再次累计到阈值 → 第二次告警
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
service.handle(settings, snapshot, false, null, now);
|
||||
|
||||
verify(sender, times(2)).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRestartWindowWhenExpired() {
|
||||
enableAlerts(3, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
// 第一次失败开启窗口,10 分钟后窗口已过期 → 计数从新窗口重新开始
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
|
||||
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((Map<String, Object>) payload.get("data")).containsEntry("failures", 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResetCounterOnLoginSuccess() {
|
||||
enableAlerts(3, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
var now = Instant.now();
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
// 登录成功立即清零:其后失败需重新累计
|
||||
service.handle(settings(3, 5), snapshot, true, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
|
||||
service.handle(settings(3, 5), snapshot, false, null, now);
|
||||
verify(sender, times(1)).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCountFailureFromCallbackFlag() {
|
||||
// 状态码→成败的解释已上移到 LoginOutcome(表单登录成败均为 302 重定向),
|
||||
// 服务只按回调布尔计数:false 计失败
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResetCounterOnSuccessCallback() {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, true, null);
|
||||
service.onLoginResult(snapshot, true, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAlertOnFirstFailureWhenThresholdOne() {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldIncludeAttemptedUsernameInPayload() {
|
||||
// 登录尝试用户名(功能评审 P0-1):进入负载 content 与 data,接收方可区分定向撞库
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 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
|
||||
void shouldSkipWhenAlertDisabled() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(
|
||||
new AlertSettings(false, WEBHOOK_REF, 1, 5)));
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
assertThat(service.failureCount).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipWhenWebhookUrlUnavailable() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(
|
||||
new AlertSettings(true, " ", 1, 5)));
|
||||
when(settingProvider.webhookUrl(any(AlertSettings.class)))
|
||||
.thenReturn(Mono.error(new IllegalStateException("Webhook 地址未配置")));
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
// 地址解析失败(未配置 Secret / Secret 缺字段):静默跳过,不计数也不告警
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
assertThat(service.failureCount).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipWhenSettingsUnavailable() {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
assertThatCode(() -> service.onLoginResult(snapshot, false, null))
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenSenderFails() {
|
||||
enableAlerts(1, 5);
|
||||
doThrow(new IllegalStateException("webhook broken"))
|
||||
.when(sender).send(any(), any());
|
||||
|
||||
assertThatCode(() -> service.onLoginResult(loginSnapshot(), false, null))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldOmitUserAgentSegmentWhenAbsent() {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest.post("http://localhost/login")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((String) payload.get("content")).doesNotContain("()");
|
||||
assertThat((Map<String, Object>) payload.get("data")).containsEntry("userAgent", null);
|
||||
}
|
||||
|
||||
/** 直接驱动 handle 用的告警设置(handle 只读开关/阈值,地址走 provider 解析)。 */
|
||||
private AlertSettings settings(int thresholdCount, int windowMinutes) {
|
||||
return new AlertSettings(true, WEBHOOK_REF, thresholdCount, windowMinutes);
|
||||
}
|
||||
}
|
||||
+236
@@ -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>");
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.ListResult;
|
||||
import run.halo.app.extension.Metadata;
|
||||
import run.halo.app.extension.PageRequest;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
|
||||
/**
|
||||
* 导出端点与 CSV 生成测试:响应头/BOM/表头/数据行、转义与注入防护、
|
||||
* 全量分批取数(升序、每批 200、循环至不足一批)、非法筛选参数 400。
|
||||
*/
|
||||
class AuditExportEndpointTest {
|
||||
|
||||
private static final String EXPORT_URI =
|
||||
"/apis/" + AuditLog.GROUP + "/v1alpha1/auditlogs/-/export";
|
||||
|
||||
private static final String CSV_HEADER =
|
||||
"操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
|
||||
private ReactiveExtensionClient client;
|
||||
private WebTestClient webClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
client = mock(ReactiveExtensionClient.class);
|
||||
// 导出路由挂在 AuditQueryEndpoint 上(同一 builder),真实 exporter + mock client
|
||||
var endpoint = new AuditQueryEndpoint(client, new AuditLogCsvExporter(client));
|
||||
var mounted = org.springframework.web.reactive.function.server.RouterFunctions.nest(
|
||||
org.springframework.web.reactive.function.server.RequestPredicates.path(
|
||||
"/apis/" + AuditLog.GROUP + "/v1alpha1"),
|
||||
endpoint.endpoint());
|
||||
webClient = WebTestClient.bindToRouterFunction(mounted).build();
|
||||
}
|
||||
|
||||
private static AuditLog auditLog(String name, Instant creationTimestamp, String username,
|
||||
String attemptedUsername, String method, String resourceType, String resourceName,
|
||||
String path, Integer statusCode, String remoteIp, String userAgent) {
|
||||
var metadata = new Metadata();
|
||||
metadata.setName(name);
|
||||
metadata.setCreationTimestamp(creationTimestamp);
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setUsername(username);
|
||||
spec.setAttemptedUsername(attemptedUsername);
|
||||
spec.setMethod(method);
|
||||
spec.setResourceType(resourceType);
|
||||
spec.setResourceName(resourceName);
|
||||
spec.setPath(path);
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(remoteIp);
|
||||
spec.setUserAgent(userAgent);
|
||||
var log = new AuditLog();
|
||||
log.setMetadata(metadata);
|
||||
log.setSpec(spec);
|
||||
return log;
|
||||
}
|
||||
|
||||
/** 与实现一致的期望操作时间列(服务器时区)。 */
|
||||
private static String expectedTimeColumn(Instant instant) {
|
||||
return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.withZone(ZoneId.systemDefault())
|
||||
.format(instant);
|
||||
}
|
||||
|
||||
private void stubSinglePage(List<AuditLog> items) {
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
|
||||
items.size(), items)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportCsvWithBomHeaderAndRows() {
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
stubSinglePage(List.of(
|
||||
auditLog("auditlog-1", time, "admin", null, "POST", "users", "zhangsan",
|
||||
"/apis/api.console.halo.run/v1alpha1/users", 201, "127.0.0.1",
|
||||
"Mozilla/5.0"),
|
||||
// 登录失败记录(功能评审 P0-1):尝试用户列为登录时尝试的用户名
|
||||
auditLog("auditlog-2", time.plusSeconds(60), "unknown", "admin", "POST", "auth",
|
||||
null, "/login", 401, "10.0.0.8", "Mozilla/5.0")));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
assertThat(body).startsWith("\uFEFF" + CSV_HEADER + "\r\n");
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(3); // 表头 + 2 行数据(末尾 \r\n 切出的空串不进 split 前段)
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",admin,,POST,users,zhangsan,/apis/api.console.halo.run/v1alpha1/users"
|
||||
+ ",新建用户,,成功,201,127.0.0.1,Mozilla/5.0");
|
||||
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||
+ ",unknown,admin,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportLoginFailureRowsAsFailureDespiteHttp2xx3xx() {
|
||||
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)与失败回显页
|
||||
// (GET /login?error=...,200)状态码落在 2xx/3xx,结果列仍应为「失败」;
|
||||
// 描述列优先落库语义动作(登录失败),而非按路径重新推导出的「登录」
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
var failedFormLogin = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth",
|
||||
null, "/login", 302, "119.53.161.18", "Mozilla/5.0");
|
||||
failedFormLogin.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
var failureEcho = auditLog("auditlog-2", time.plusSeconds(60), "unknown", null, "GET",
|
||||
"auth", null, "/login?error=invalid-credential&method=local", 200, "119.53.161.18",
|
||||
"Mozilla/5.0");
|
||||
failureEcho.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
stubSinglePage(List.of(failedFormLogin, failureEcho));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(3);
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",unknown,admin,POST,auth,,/login,登录失败,,失败,302,119.53.161.18,Mozilla/5.0");
|
||||
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||
+ ",unknown,,GET,auth,,/login?error=invalid-credential&method=local"
|
||||
+ ",登录失败,,失败,200,119.53.161.18,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportChangesColumnWhenRecordHasChanges() {
|
||||
var time = Instant.parse("2026-11-04T00:00:00Z");
|
||||
var log = auditLog("auditlog-1", time, "admin", null, "PUT", "posts", "abc",
|
||||
"/apis/content.halo.run/v1alpha1/posts/abc", 200, "127.0.0.1", "UA");
|
||||
log.getSpec().setChanges(List.of(
|
||||
change(ChangeType.UPDATED, "spec.title", "旧标题", "新标题"),
|
||||
change(ChangeType.ADDED, "spec.cover", null, "c.png")));
|
||||
stubSinglePage(List.of(log));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",admin,,PUT,posts,abc,/apis/content.halo.run/v1alpha1/posts/abc"
|
||||
+ ",修改文章,修改 spec.title:旧标题 → 新标题;新增 spec.cover:c.png"
|
||||
+ ",成功,200,127.0.0.1,UA");
|
||||
}
|
||||
|
||||
private static ChangeEntry change(ChangeType type, String field, String oldValue,
|
||||
String newValue) {
|
||||
var entry = new ChangeEntry();
|
||||
entry.setField(field);
|
||||
entry.setChangeType(type);
|
||||
entry.setOldValue(oldValue);
|
||||
entry.setNewValue(newValue);
|
||||
return entry;
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportOnlyHeaderWhenNoRecords() {
|
||||
stubSinglePage(List.of());
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
assertThat(body).isEqualTo("\uFEFF" + CSV_HEADER + "\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldEscapeSpecialCharactersAndFormulaInjection() {
|
||||
stubSinglePage(List.of(
|
||||
// 逗号与引号需加引号且内部引号翻倍;= 开头需加单引号前缀
|
||||
auditLog("auditlog-1", Instant.parse("2026-11-02T00:00:00Z"), "a\"b", null, "PUT",
|
||||
"posts", "=sum(A1)", "/apis/content.halo.run/v1alpha1/posts/x,y", 200,
|
||||
"127.0.0.1", "@evil")));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(2);
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-02T00:00:00Z"))
|
||||
+ ",\"a\"\"b\",,PUT,posts,'=sum(A1),\"/apis/content.halo.run/v1alpha1/posts/x,y\""
|
||||
+ ",修改文章,,成功,200,127.0.0.1,'@evil");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatNullStatusCodeAsFailureAndEmptyFields() {
|
||||
stubSinglePage(List.of(
|
||||
auditLog("auditlog-1", Instant.parse("2026-11-03T00:00:00Z"), "admin", null,
|
||||
"PATCH", "themes", null, null, null, null, null)));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-03T00:00:00Z"))
|
||||
+ ",admin,,PATCH,themes,,,修改主题,,失败,,,");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldApplyFilterParamsSameAsQuery() {
|
||||
stubSinglePage(List.of());
|
||||
exportAndGetBody(EXPORT_URI
|
||||
+ "?fieldSelector=spec.username=admin&result=failure&keyword=hello"
|
||||
+ "&startTime=2026-11-01T00:00:00Z&endTime=2026-11-21T00:00:00Z");
|
||||
|
||||
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.username")
|
||||
.contains("admin")
|
||||
.contains("spec.statusCode")
|
||||
.contains("400")
|
||||
.contains("spec.resourceName")
|
||||
.contains("spec.path")
|
||||
.contains("hello")
|
||||
.contains("metadata.creationTimestamp")
|
||||
.contains("2026-11-01T00:00:00Z")
|
||||
.contains("2026-11-21T00:00:00Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectNonWhitelistedFieldSelector() {
|
||||
webClient.get()
|
||||
.uri(EXPORT_URI + "?fieldSelector=spec.userAgent=evil")
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectInvalidResultFilter() {
|
||||
webClient.get()
|
||||
.uri(EXPORT_URI + "?result=unknown")
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectInvalidTimeFormat() {
|
||||
webClient.get()
|
||||
.uri(EXPORT_URI + "?startTime=not-a-time")
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFetchAllInBatchesUntilShortPage() {
|
||||
// 第一页满批 200 条、第二页满批、第三页不足一批:共 401 条,验证分批递归终止
|
||||
var page1 = fullBatch(1);
|
||||
var page2 = fullBatch(2);
|
||||
var page3 = List.of(
|
||||
auditLog("auditlog-401", Instant.parse("2026-11-01T00:00:00Z"), "admin", null,
|
||||
"POST", "users", "zhangsan", "/apis/v1alpha1/users", 200, "127.0.0.1", "UA"));
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
|
||||
401, page1)),
|
||||
Mono.just(new ListResult<>(2, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
|
||||
401, page2)),
|
||||
Mono.just(new ListResult<>(3, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
|
||||
401, page3)));
|
||||
|
||||
var exporter = new AuditLogCsvExporter(client);
|
||||
StepVerifier.create(exporter.fetchAll(new ListOptions()
|
||||
.setFieldSelector(run.halo.app.extension.router.selector.FieldSelector.all())))
|
||||
.expectNextCount(401)
|
||||
.verifyComplete();
|
||||
|
||||
// 三次分批查询:页码 1/2/3、批大小 200、时间升序(导出期间并发写入不打乱分页边界)
|
||||
var captor = ArgumentCaptor.forClass(PageRequest.class);
|
||||
verify(client, times(3)).listBy(eq(AuditLog.class), any(ListOptions.class),
|
||||
captor.capture());
|
||||
var pages = captor.getAllValues();
|
||||
assertThat(pages).hasSize(3);
|
||||
for (int i = 0; i < pages.size(); i++) {
|
||||
assertThat(pages.get(i).getPageNumber()).isEqualTo(i + 1);
|
||||
assertThat(pages.get(i).getPageSize())
|
||||
.isEqualTo(AuditLogCsvExporter.EXPORT_BATCH_SIZE);
|
||||
assertThat(pages.get(i).getSort().getOrderFor("metadata.creationTimestamp"))
|
||||
.extracting(Sort.Order::getDirection)
|
||||
.isEqualTo(Sort.Direction.ASC);
|
||||
}
|
||||
}
|
||||
|
||||
private List<AuditLog> fullBatch(long firstTimestampEpochSecond) {
|
||||
var items = new ArrayList<AuditLog>();
|
||||
for (int i = 0; i < AuditLogCsvExporter.EXPORT_BATCH_SIZE; i++) {
|
||||
items.add(auditLog("auditlog-" + i,
|
||||
Instant.ofEpochSecond(firstTimestampEpochSecond * 1000 + i),
|
||||
"admin", null, "POST", "users", "user-" + i, "/apis/v1alpha1/users", 200,
|
||||
"127.0.0.1", "UA"));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private String exportAndGetBody(String uri) {
|
||||
var bytes = webClient.get()
|
||||
.uri(uri)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectHeader().contentType(MediaType.parseMediaType("text/csv;charset=UTF-8"))
|
||||
.expectHeader().value(HttpHeaders.CONTENT_DISPOSITION,
|
||||
disposition -> assertThat(disposition)
|
||||
.startsWith("attachment; filename=audit-logs-")
|
||||
.endsWith(".csv"))
|
||||
.expectBody(byte[].class)
|
||||
.returnResult()
|
||||
.getResponseBody();
|
||||
return new String(bytes, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
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.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 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 shouldRecordLoginPageVisitExactlyOnceThroughRealChain() {
|
||||
// GET /login 会流经全链(无终止过滤器命中):必须仅由链首过滤器记录一次,
|
||||
// 链尾过滤器不得重复记录(两个过滤器按 CaptureRule 分治、互不重叠)
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.build());
|
||||
|
||||
proxy.filter(exchange, OUTER_CHAIN).block();
|
||||
|
||||
verify(recorder, timeout(CALLBACK_TIMEOUT_MS).times(1))
|
||||
.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());
|
||||
}
|
||||
}
|
||||
+50
-14
@@ -30,7 +30,7 @@ class AuditQueryEndpointTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
client = mock(ReactiveExtensionClient.class);
|
||||
var endpoint = new AuditQueryEndpoint(client);
|
||||
var endpoint = new AuditQueryEndpoint(client, mock(AuditLogCsvExporter.class));
|
||||
// 复现生产环境挂载方式(CustomEndpointsBuilder 在 /apis/{groupVersion} 下 nest)
|
||||
var mounted = org.springframework.web.reactive.function.server.RouterFunctions.nest(
|
||||
org.springframework.web.reactive.function.server.RequestPredicates.path(
|
||||
@@ -44,7 +44,7 @@ class AuditQueryEndpointTest {
|
||||
@Test
|
||||
void shouldQueryWithDefaults() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query")
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
@@ -61,7 +61,7 @@ class AuditQueryEndpointTest {
|
||||
@Test
|
||||
void shouldApplyEqualityFieldSelectors() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query"
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?fieldSelector=spec.username=admin"
|
||||
+ "&fieldSelector=spec.method=POST"
|
||||
+ "&fieldSelector=spec.statusCode=500")
|
||||
@@ -81,25 +81,61 @@ class AuditQueryEndpointTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldApplyResultFilter() {
|
||||
void shouldApplySemanticActionFieldSelector() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query?result=failure")
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?fieldSelector=spec.action=publish")
|
||||
.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();
|
||||
// failure = statusCode >= 400(无上界)
|
||||
assertThat(condition)
|
||||
.contains("spec.action")
|
||||
.contains("publish");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldApplyResultFilter() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?result=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();
|
||||
// failure = statusCode >= 400(无上界)或语义动作标注 login-failure
|
||||
// (登录失败的 HTTP 状态码可能为 200/302)
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("400");
|
||||
.contains("400")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldApplySuccessResultFilterExcludingLoginFailure() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?result=success")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
// success = 2xx/3xx 且排除登录失败标注(其状态码可能落在 2xx/3xx 区间)
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectInvalidResultFilter() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query?result=unknown")
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?result=unknown")
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest();
|
||||
}
|
||||
@@ -109,7 +145,7 @@ class AuditQueryEndpointTest {
|
||||
var start = Instant.parse("2026-11-01T00:00:00Z");
|
||||
var end = Instant.parse("2026-11-21T00:00:00Z");
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query"
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?keyword=hello&startTime=" + start + "&endTime=" + end)
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
@@ -130,7 +166,7 @@ class AuditQueryEndpointTest {
|
||||
@Test
|
||||
void shouldRejectNonWhitelistedFieldSelector() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query"
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?fieldSelector=spec.userAgent=evil")
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest();
|
||||
@@ -139,7 +175,7 @@ class AuditQueryEndpointTest {
|
||||
@Test
|
||||
void shouldRejectInvalidTimeFormat() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query?startTime=not-a-time")
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?startTime=not-a-time")
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest();
|
||||
}
|
||||
@@ -147,7 +183,7 @@ class AuditQueryEndpointTest {
|
||||
@Test
|
||||
void shouldRejectInvalidFieldSelectorTerm() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query?fieldSelector=noequals")
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?fieldSelector=noequals")
|
||||
.exchange()
|
||||
.expectStatus().isBadRequest();
|
||||
}
|
||||
@@ -155,7 +191,7 @@ class AuditQueryEndpointTest {
|
||||
@Test
|
||||
void shouldClampPageSizeAndForceTimeSort() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query"
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?page=3&size=500&sort=spec.username,asc")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
@@ -173,7 +209,7 @@ class AuditQueryEndpointTest {
|
||||
@Test
|
||||
void shouldSupportAscendingTimeSort() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.example.com/v1alpha1/auditlogs/-/query"
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query"
|
||||
+ "?sort=metadata.creationTimestamp,asc")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
+242
-7
@@ -8,8 +8,10 @@ import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -21,6 +23,7 @@ import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
|
||||
/**
|
||||
* 直写降级测试(技术方案 D2):成功直写、失败降级为 warn 且不抛出、开关关闭跳过(D6)。
|
||||
* 字段级变更(产品设计 V2):成功操作且已捕获上下文时落库 diff,失败/未捕获不落库。
|
||||
*/
|
||||
class AuditRecorderTest {
|
||||
|
||||
@@ -52,7 +55,7 @@ class AuditRecorderTest {
|
||||
.header("User-Agent", "UA-1")
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, 204, "admin");
|
||||
recorder.record(snapshot, new ChangeCapture(), 204, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -60,6 +63,8 @@ class AuditRecorderTest {
|
||||
|
||||
assertThat(auditLog.getSpec().getUsername()).isEqualTo("admin");
|
||||
assertThat(auditLog.getSpec().getMethod()).isEqualTo("DELETE");
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库
|
||||
assertThat(auditLog.getSpec().getAction()).isEqualTo("delete");
|
||||
assertThat(auditLog.getSpec().getResourceType()).isEqualTo("posts");
|
||||
assertThat(auditLog.getSpec().getResourceName()).isEqualTo("xyz");
|
||||
assertThat(auditLog.getSpec().getPath()).isEqualTo(
|
||||
@@ -73,21 +78,97 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
||||
recorder.record(snapshotOf("/login"), 401, null);
|
||||
// XHR/JSON 登录失败(401):过滤器判定 loginFailed=true,动作标注登录失败
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null, true);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
assertThat(captor.getValue().getSpec().getUsername())
|
||||
.isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
||||
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth");
|
||||
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login-failure");
|
||||
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipRecordingWhenAuditDisabled() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(false, 30)));
|
||||
void shouldRecordAttemptedUsernameForLoginAttempt() {
|
||||
// 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan", true);
|
||||
|
||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), 200, "admin");
|
||||
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
|
||||
void shouldAnnotateSubActionSemanticAction() {
|
||||
recorder.record(RequestSnapshot.of(MockServerHttpRequest
|
||||
.put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish")
|
||||
.build()), new ChangeCapture(), 200, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("publish");
|
||||
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("posts");
|
||||
}
|
||||
|
||||
// ===== 登录失败标注(LoginOutcome + 语义动作 login-failure) =====
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailedLoginAttempt() {
|
||||
// 表单登录失败(302 重定向目标含 error 参数):过滤器传入 loginFailed=true,
|
||||
// 语义动作标注 login-failure;状态码仍如实记录 302
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(302);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailureEcho() {
|
||||
// 登录失败回显(GET /login?error=... 页面渲染 HTTP 200):同样标注登录失败
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.get("http://localhost/login?error=invalid-credential&method=local")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, new ChangeCapture(), 200,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(200);
|
||||
assertThat(spec.getPath()).isEqualTo("/login?error=invalid-credential&method=local");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepLoginActionOnSuccessfulLogin() {
|
||||
// 表单登录成功(302 → /uc):语义动作仍为 login,不标注登录失败
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipRecordingWhenAuditDisabled() {
|
||||
when(settingProvider.get())
|
||||
.thenReturn(Mono.just(new AuditSettings(false, 30, null, null)));
|
||||
|
||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
|
||||
200, "admin", null, false);
|
||||
|
||||
verify(client, never()).create(any(AuditLog.class));
|
||||
}
|
||||
@@ -97,7 +178,7 @@ class AuditRecorderTest {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
200, "admin")).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 200, "admin", null, false)).doesNotThrowAnyException();
|
||||
|
||||
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
||||
verify(client).create(any(AuditLog.class));
|
||||
@@ -109,6 +190,160 @@ class AuditRecorderTest {
|
||||
new IllegalStateException("storage unavailable")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
500, "admin")).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 500, "admin", null, false)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordChangesOnSuccessWhenCaptured() {
|
||||
var capture = new ChangeCapture();
|
||||
var mapper = new ObjectMapper();
|
||||
var oldNode = mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "旧标题")));
|
||||
var bodyNode = mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "新标题")));
|
||||
capture.setOldNode(oldNode);
|
||||
capture.setBodyNode(bodyNode);
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.put("http://localhost/apis/content.halo.run/v1alpha1/posts/abc")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 200, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var changes = captor.getValue().getSpec().getChanges();
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(changes.get(0).getField()).isEqualTo("spec.title");
|
||||
assertThat(changes.get(0).getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(changes.get(0).getOldValue()).isEqualTo("旧标题");
|
||||
assertThat(changes.get(0).getNewValue()).isEqualTo("新标题");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotRecordChangesOnFailedRequest() {
|
||||
var capture = new ChangeCapture();
|
||||
var mapper = new ObjectMapper();
|
||||
capture.setOldNode(mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "旧"))));
|
||||
capture.setBodyNode(mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "新"))));
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.put("http://localhost/apis/content.halo.run/v1alpha1/posts/abc")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 403, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
// 失败请求资源未实际变更:不落库字段变更
|
||||
assertThat(captor.getValue().getSpec().getChanges()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotRecordChangesWhenContextMissing() {
|
||||
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
|
||||
new ChangeCapture(), 200, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
// 未捕获请求体/旧状态(非 JSON、超限或获取失败):不落库字段变更
|
||||
assertThat(captor.getValue().getSpec().getChanges()).isNull();
|
||||
}
|
||||
|
||||
// ===== 系统内部变更(产品设计 V2"系统内部变更") =====
|
||||
|
||||
@Test
|
||||
void shouldRecordSystemChangeAsSystemOperator() {
|
||||
var changes = List.of(newChange("spec.releaseSnapshot", ChangeType.UPDATED, "snapshot-a",
|
||||
"snapshot-b"));
|
||||
|
||||
recorder.recordSystemChange("PUT", "posts", "abc",
|
||||
"/apis/api.content.halo.run/v1alpha1/posts/abc", changes);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
// 执行者记 system(定时发布等非 HTTP 触发的变更)
|
||||
assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.SYSTEM_USERNAME);
|
||||
assertThat(spec.getMethod()).isEqualTo("PUT");
|
||||
assertThat(spec.getAction()).isEqualTo("update");
|
||||
assertThat(spec.getResourceType()).isEqualTo("posts");
|
||||
assertThat(spec.getResourceName()).isEqualTo("abc");
|
||||
assertThat(spec.getPath()).isEqualTo("/apis/api.content.halo.run/v1alpha1/posts/abc");
|
||||
// 内部变更无响应码语义,事件在写入成功后派发,恒记 200
|
||||
assertThat(spec.getStatusCode()).isEqualTo(200);
|
||||
assertThat(spec.getRemoteIp()).isNull();
|
||||
assertThat(spec.getUserAgent()).isNull();
|
||||
assertThat(spec.getChanges()).isSameAs(changes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordSystemDeleteWithDeleteAction() {
|
||||
recorder.recordSystemChange("DELETE", "comments", "c1",
|
||||
"/apis/api.content.halo.run/v1alpha1/comments/c1",
|
||||
List.of(newChange("spec.raw", ChangeType.REMOVED, "内容", null)));
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.SYSTEM_USERNAME);
|
||||
assertThat(spec.getMethod()).isEqualTo("DELETE");
|
||||
assertThat(spec.getAction()).isEqualTo("delete");
|
||||
assertThat(spec.getResourceType()).isEqualTo("comments");
|
||||
assertThat(spec.getChanges()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipSystemChangeWhenDisabled() {
|
||||
when(settingProvider.get())
|
||||
.thenReturn(Mono.just(new AuditSettings(true, 90, null, false)));
|
||||
|
||||
recorder.recordSystemChange("PUT", "posts", "abc", "/apis/x/v1alpha1/posts/abc",
|
||||
List.of(newChange("spec.title", ChangeType.UPDATED, "a", "b")));
|
||||
|
||||
verify(client, never()).create(any(AuditLog.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipSystemChangeWhenAuditDisabled() {
|
||||
when(settingProvider.get())
|
||||
.thenReturn(Mono.just(new AuditSettings(false, 90, null, null)));
|
||||
|
||||
recorder.recordSystemChange("PUT", "posts", "abc", "/apis/x/v1alpha1/posts/abc",
|
||||
List.of());
|
||||
|
||||
verify(client, never()).create(any(AuditLog.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordSystemChangeWhenSettingsUnavailable() {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
|
||||
assertThatCode(() -> recorder.recordSystemChange("PUT", "posts", "abc",
|
||||
"/apis/x/v1alpha1/posts/abc", List.of())).doesNotThrowAnyException();
|
||||
|
||||
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
||||
verify(client).create(any(AuditLog.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenSystemChangeCreateFails() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.error(
|
||||
new IllegalStateException("storage unavailable")));
|
||||
|
||||
assertThatCode(() -> recorder.recordSystemChange("PUT", "posts", "abc",
|
||||
"/apis/x/v1alpha1/posts/abc", List.of())).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
private static ChangeEntry newChange(String field, ChangeType type, String oldValue,
|
||||
String newValue) {
|
||||
var entry = new ChangeEntry();
|
||||
entry.setField(field);
|
||||
entry.setChangeType(type);
|
||||
entry.setOldValue(oldValue);
|
||||
entry.setNewValue(newValue);
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
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 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 链之前承接)。操作者统一为未知用户,登录尝试账号由请求体白名单提取;
|
||||
* 登录失败告警回调仅发生在 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 shouldRecordLoginPageVisitWithoutFailureMark() {
|
||||
// 首次打开登录页(无 error 参数):记录登录页访问,不标注登录失败
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(false));
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginPageErrorEchoAsLoginFailure() {
|
||||
// 登录失败回显:GET /login?error=... 页面渲染 HTTP 200,标注登录失败,
|
||||
// 但不是登录尝试、不触发告警
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login?error=invalid-credential&method=local")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), isNull(), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull(), eq(true));
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@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());
|
||||
}
|
||||
}
|
||||
+18
-4
@@ -28,10 +28,12 @@ class CaptureRuleTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureAuthEndpointsRegardlessOfMethod() {
|
||||
assertThat(shouldCapture("/login", "POST")).isTrue();
|
||||
assertThat(shouldCapture("/login", "GET")).isTrue();
|
||||
assertThat(shouldCapture("/logout", "POST")).isTrue();
|
||||
void shouldNotCaptureAuthEndpointsInApisRule() {
|
||||
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 独立捕获(isAuthEndpoint),
|
||||
// 通用规则不再包含,两个过滤器按规则分治、互不重叠
|
||||
assertThat(shouldCapture("/login", "POST")).isFalse();
|
||||
assertThat(shouldCapture("/login", "GET")).isFalse();
|
||||
assertThat(shouldCapture("/logout", "POST")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -57,4 +59,16 @@ class CaptureRuleTest {
|
||||
assertThat(CaptureRule.isAuthEndpoint("/console/login")).isFalse();
|
||||
assertThat(CaptureRule.isAuthEndpoint(null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDetectLoginAttemptOnlyForPostLogin() {
|
||||
// 登录失败告警触发点(产品设计 V2「告警通知」):仅 POST /login
|
||||
assertThat(CaptureRule.isLoginAttempt("/login", "POST")).isTrue();
|
||||
assertThat(CaptureRule.isLoginAttempt("/login", "GET")).isFalse();
|
||||
assertThat(CaptureRule.isLoginAttempt("/logout", "POST")).isFalse();
|
||||
assertThat(CaptureRule.isLoginAttempt("/loginx", "POST")).isFalse();
|
||||
assertThat(CaptureRule.isLoginAttempt("/console/login", "POST")).isFalse();
|
||||
assertThat(CaptureRule.isLoginAttempt(null, "POST")).isFalse();
|
||||
assertThat(CaptureRule.isLoginAttempt("/login", null)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.Unstructured;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettingProvider;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
|
||||
/**
|
||||
* 字段级变更捕获测试(产品设计 V2):请求体缓存与装饰(下游可重复读)、
|
||||
* 旧状态抓取(改/删且模型已注册)、设置开关降级与适用性判定。
|
||||
*/
|
||||
class ChangeCaptureManagerTest {
|
||||
|
||||
private AuditSettingProvider settingProvider;
|
||||
private SchemeManager schemeManager;
|
||||
private ReactiveExtensionClient client;
|
||||
private ChangeCaptureManager manager;
|
||||
|
||||
/**
|
||||
* 以 {@link AuditLog}(group 非空,group/version/plural 均由 Scheme 推导)
|
||||
* 作为测试目标模型。注意空 group 的核心模型走 /api/** 路径,本就不在捕获范围。
|
||||
*/
|
||||
private Scheme targetScheme;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
settingProvider = mock(AuditSettingProvider.class);
|
||||
schemeManager = mock(SchemeManager.class);
|
||||
client = mock(ReactiveExtensionClient.class);
|
||||
manager = new ChangeCaptureManager(settingProvider, schemeManager, client);
|
||||
targetScheme = Scheme.buildFromType(AuditLog.class);
|
||||
when(schemeManager.schemes()).thenReturn(java.util.List.of(targetScheme));
|
||||
when(settingProvider.get()).thenReturn(Mono.just(AuditSettings.defaults()));
|
||||
}
|
||||
|
||||
private String targetPath() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
return "/apis/" + gvk.group() + "/" + gvk.version() + "/" + targetScheme.plural();
|
||||
}
|
||||
|
||||
/** 经自定义反序列化器构造 Unstructured(与 Halo 存储读取路径一致)。 */
|
||||
private static Unstructured unstructured(String json) {
|
||||
try {
|
||||
return Unstructured.OBJECT_MAPPER.readValue(json, Unstructured.class);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 适用性判定 =====
|
||||
|
||||
@Test
|
||||
void shouldCaptureWritesOnApisPaths() {
|
||||
var jsonRequest = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(2)
|
||||
.body("{}");
|
||||
var mergePatchRequest = MockServerHttpRequest
|
||||
.patch("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.parseMediaType("application/merge-patch+json"))
|
||||
.contentLength(2)
|
||||
.body("{}");
|
||||
|
||||
// merge-patch+json 同样适用(PATCH 语义按 merge patch 处理)
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(jsonRequest))).isTrue();
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(mergePatchRequest))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureAuthEndpointsOrNonApisPaths() {
|
||||
var loginRequest = MockServerHttpRequest.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_JSON).contentLength(2).body("{}");
|
||||
var webRequest = MockServerHttpRequest.put("http://localhost/web/other")
|
||||
.contentType(MediaType.APPLICATION_JSON).contentLength(2).body("{}");
|
||||
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(loginRequest))).isFalse();
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(webRequest))).isFalse();
|
||||
}
|
||||
|
||||
// ===== 设置开关降级 =====
|
||||
|
||||
@Test
|
||||
void shouldSkipCaptureWhenRecordChangesDisabled() {
|
||||
when(settingProvider.get())
|
||||
.thenReturn(Mono.just(new AuditSettings(true, 90, false, null)));
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(20)
|
||||
.body("{\"data\": {\"key\": \"v\"}}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
StepVerifier.create(manager.prepare(exchange, RequestSnapshot.of(request), capture))
|
||||
.expectNextMatches(prepared -> prepared == exchange)
|
||||
.verifyComplete();
|
||||
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToPassthroughWhenPrepareFails() {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(20)
|
||||
.body("{\"data\": {\"key\": \"v\"}}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
// 捕获失败降级为原 exchange:不抛错、不影响业务请求
|
||||
StepVerifier.create(manager.prepare(exchange, RequestSnapshot.of(request), capture))
|
||||
.expectNextMatches(prepared -> prepared == exchange)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
// ===== 请求体缓存与装饰 =====
|
||||
|
||||
@Test
|
||||
void shouldCacheJsonBodyAndKeepItReadableDownstream() {
|
||||
var body = "{\"data\": {\"key\": \"配置值\"}}";
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body);
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
when(client.fetch(any(GroupVersionKind.class), any())).thenReturn(Mono.just(
|
||||
unstructured("{\"metadata\": {\"name\": \"my-cm\"}}")));
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
assertThat(capture.getBodyNode()).isNotNull();
|
||||
assertThat(capture.getBodyNode().at("/data/key").asText()).isEqualTo("配置值");
|
||||
|
||||
// 装饰后的请求可重复读(每次订阅独立 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 shouldSkipBodyAndOldStateForNonJsonPut() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.TEXT_PLAIN)
|
||||
.contentLength(10)
|
||||
.body("plain-text");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 非 JSON 请求体:PUT 的 body 与旧状态均无 diff 意义,全部跳过
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCacheBodyWithoutContentLength() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(Flux.just(DefaultDataBufferFactory.sharedInstance
|
||||
.wrap("{\"data\": {\"key\": \"v\"}}".getBytes(StandardCharsets.UTF_8))));
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 分块传输(无 Content-Length):不缓存,避免中断流式请求
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCacheOversizedBody() {
|
||||
var oversized = "a".repeat(ChangeCaptureManager.MAX_BODY_BYTES + 1);
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(oversized.length())
|
||||
.body(oversized);
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
}
|
||||
|
||||
// ===== 旧状态抓取 =====
|
||||
|
||||
@Test
|
||||
void shouldFetchOldStateForPutOnRegisteredScheme() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
var body = "{\"data\": {\"key\": \"新\"}}";
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body);
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
when(client.fetch(eq(gvk), eq("my-cm"))).thenReturn(Mono.just(
|
||||
unstructured("{\"metadata\": {\"name\": \"my-cm\"}, \"data\": {\"key\": \"旧\"}}")));
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
assertThat(capture.getOldNode()).isNotNull();
|
||||
assertThat(capture.getOldNode().at("/data/key").asText()).isEqualTo("旧");
|
||||
assertThat(capture.getBodyNode().at("/data/key").asText()).isEqualTo("新");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFetchOldStateForDeleteButNotPost() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
when(client.fetch(eq(gvk), eq("my-cm"))).thenReturn(Mono.just(
|
||||
unstructured("{\"metadata\": {\"name\": \"my-cm\"}, \"data\": {\"key\": \"旧\"}}")));
|
||||
|
||||
// DELETE:需要旧状态(记录被删内容)
|
||||
var deleteRequest = MockServerHttpRequest
|
||||
.delete("http://localhost" + targetPath() + "/my-cm").build();
|
||||
var deleteCapture = new ChangeCapture();
|
||||
manager.prepare(MockServerWebExchange.from(deleteRequest),
|
||||
RequestSnapshot.of(deleteRequest), deleteCapture).block();
|
||||
assertThat(deleteCapture.getOldNode()).isNotNull();
|
||||
assertThat(deleteCapture.getOldNode().at("/data/key").asText()).isEqualTo("旧");
|
||||
|
||||
// POST(新建集合资源):无旧状态
|
||||
var postRequest = MockServerHttpRequest
|
||||
.post("http://localhost" + targetPath())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\": {\"k\": \"v\"}}");
|
||||
var postCapture = new ChangeCapture();
|
||||
manager.prepare(MockServerWebExchange.from(postRequest),
|
||||
RequestSnapshot.of(postRequest), postCapture).block();
|
||||
assertThat(postCapture.getOldNode()).isNull();
|
||||
|
||||
// 仅 DELETE 抓了一次旧状态
|
||||
verify(client, times(1)).fetch(any(GroupVersionKind.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipOldStateWhenSchemeNotRegistered() {
|
||||
// 未注册模型 → 无法定位 GVK,不抓旧状态
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost/apis/unknown.group/v1alpha1/unknowns/xyz")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
verify(client, never()).fetch(any(GroupVersionKind.class), any());
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipOldStateWhenFetchFails() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
when(client.fetch(eq(gvk), eq("gone")))
|
||||
.thenReturn(Mono.error(new IllegalStateException("store down")));
|
||||
var request = MockServerHttpRequest
|
||||
.delete("http://localhost" + targetPath() + "/gone").build();
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 旧状态获取失败:静默跳过 diff,请求继续(返回原 exchange)
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipOldStateForCollectionPathWithoutResourceName() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
verify(client, never()).fetch(any(GroupVersionKind.class), any());
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
// ===== 外围保障 =====
|
||||
|
||||
@Test
|
||||
void shouldNotTouchResponse() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(2)
|
||||
.body("{}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 捕获过程只读请求侧,不写响应(状态码仍为未设置的 null)
|
||||
assertThat(exchange.getResponse().getStatusCode()).isNull();
|
||||
}
|
||||
}
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 字段级变更 diff 引擎测试(产品设计 V2):
|
||||
* 方法语义(PUT 全量 / PATCH merge / POST 新增 / DELETE 移除)、范围降噪
|
||||
* (根级 apiVersion/kind/status、metadata 服务端子键)、脱敏、截断、封顶与空结果。
|
||||
*/
|
||||
class ChangeDiffEngineTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static JsonNode json(String content) {
|
||||
try {
|
||||
return MAPPER.readTree(content);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ChangeEntry entry(List<ChangeEntry> changes, String field) {
|
||||
return changes.stream()
|
||||
.filter(change -> change.getField().equals(field))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
// ===== 方法语义 =====
|
||||
|
||||
@Test
|
||||
void shouldDiffPutWithUpdateAddAndRemove() {
|
||||
var old = json("""
|
||||
{"metadata": {"name": "p"}, "spec": {"title": "旧", "slug": "a", "cover": "c.png"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"metadata": {"name": "p"}, "spec": {"title": "新", "slug": "a"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
assertThat(changes).hasSize(2);
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isEqualTo("旧");
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("新");
|
||||
assertThat(entry(changes, "spec.cover").getChangeType()).isEqualTo(ChangeType.REMOVED);
|
||||
assertThat(entry(changes, "spec.cover").getOldValue()).isEqualTo("c.png");
|
||||
assertThat(entry(changes, "spec.cover").getNewValue()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatPatchAsMergeSemantics() {
|
||||
var old = json("""
|
||||
{"spec": {"title": "旧", "slug": "a"}}
|
||||
""");
|
||||
// merge patch 只带变更字段;slug 未携带 → 不应记为删除
|
||||
var body = json("""
|
||||
{"spec": {"title": "新"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExpandJsonPatchOpsArray() {
|
||||
// Halo 扩展路由的 PATCH 为 JSON Patch(RFC 6902 ops 数组)
|
||||
var old = json("""
|
||||
{"spec": {"title": "旧", "cover": "c.png", "slug": "a"}}
|
||||
""");
|
||||
var body = json("""
|
||||
[{"op": "replace", "path": "/spec/title", "value": "新"},
|
||||
{"op": "add", "path": "/spec/excerpt", "value": "摘要"},
|
||||
{"op": "remove", "path": "/spec/cover"}]
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isEqualTo("旧");
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("新");
|
||||
assertThat(entry(changes, "spec.excerpt").getChangeType()).isEqualTo(ChangeType.ADDED);
|
||||
assertThat(entry(changes, "spec.excerpt").getNewValue()).isEqualTo("摘要");
|
||||
assertThat(entry(changes, "spec.cover").getChangeType()).isEqualTo(ChangeType.REMOVED);
|
||||
assertThat(entry(changes, "spec.cover").getOldValue()).isEqualTo("c.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldMapJsonPatchPointerEscapes() {
|
||||
var old = json("""
|
||||
{"metadata": {"annotations": {"a/b": "旧", "x~y": "1"}}}
|
||||
""");
|
||||
var body = json("""
|
||||
[{"op": "replace", "path": "/metadata/annotations/a~1b", "value": "新"},
|
||||
{"op": "replace", "path": "/metadata/annotations/x~0y", "value": "2"}]
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(entry(changes, "metadata.annotations.a/b").getNewValue()).isEqualTo("新");
|
||||
assertThat(entry(changes, "metadata.annotations.x~y").getNewValue()).isEqualTo("2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRedactSensitiveJsonPatchTarget() {
|
||||
var old = json("""
|
||||
{"spec": {"password": "old-pw"}}
|
||||
""");
|
||||
var body = json("""
|
||||
[{"op": "replace", "path": "/spec/password", "value": "new-pw"}]
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(entry(changes, "spec.password").getOldValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
assertThat(entry(changes, "spec.password").getNewValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExpandPostBodyAsAddedFields() {
|
||||
var body = json("""
|
||||
{"metadata": {"name": "p", "labels": {"k": "v"}},
|
||||
"spec": {"title": "新文章", "content": "正文"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("POST", null, body);
|
||||
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.ADDED);
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("新文章");
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isNull();
|
||||
assertThat(entry(changes, "metadata.name").getChangeType()).isEqualTo(ChangeType.ADDED);
|
||||
assertThat(entry(changes, "metadata.name").getNewValue()).isEqualTo("p");
|
||||
assertThat(entry(changes, "metadata.labels.k").getNewValue()).isEqualTo("v");
|
||||
assertThat(changes.stream().map(ChangeEntry::getField))
|
||||
.doesNotContain("apiVersion", "kind", "status");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExpandDeleteOldStateAsRemovedFields() {
|
||||
var old = json("""
|
||||
{"metadata": {"name": "p"}, "spec": {"title": "被删文章", "slug": "gone"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("DELETE", old, null);
|
||||
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.REMOVED);
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isEqualTo("被删文章");
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isNull();
|
||||
assertThat(entry(changes, "spec.slug").getOldValue()).isEqualTo("gone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullWhenContextMissingForPutPatchDelete() {
|
||||
var old = json("{\"spec\": {\"title\": \"x\"}}");
|
||||
var body = json("{\"spec\": {\"title\": \"y\"}}");
|
||||
|
||||
assertThat(ChangeDiffEngine.compute("PUT", null, body)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("PATCH", old, null)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("DELETE", null, null)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForGetMethodAndMissingBody() {
|
||||
var old = json("{\"spec\": {\"title\": \"x\"}}");
|
||||
|
||||
assertThat(ChangeDiffEngine.compute("GET", old, old)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("PUT", old, null)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("POST", null, null)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("PATCH", old, null)).isNull();
|
||||
}
|
||||
|
||||
// ===== 范围与降噪 =====
|
||||
|
||||
@Test
|
||||
void shouldSkipRootNoiseAndServerManagedMetadata() {
|
||||
var old = json("""
|
||||
{"apiVersion": "content.halo.run/v1alpha1", "kind": "Post", "status": {"phase": "A"},
|
||||
"metadata": {"name": "p", "version": 3, "managedFields": [{"a": 1}],
|
||||
"creationTimestamp": "2026-01-01T00:00:00Z", "labels": {"k": "1"}},
|
||||
"spec": {"title": "旧"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"apiVersion": "content.halo.run/v1alpha1", "kind": "Post", "status": {"phase": "B"},
|
||||
"metadata": {"name": "p", "labels": {"k": "2"}},
|
||||
"spec": {"title": "新"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// 仅 metadata.labels.k 与 spec.title 两处;version/managedFields/时间戳/status 不参与
|
||||
assertThat(changes).hasSize(2);
|
||||
assertThat(entry(changes, "metadata.labels.k").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepConfigMapDataField() {
|
||||
var old = json("""
|
||||
{"metadata": {"name": "cm"}, "data": {"key": "旧配置"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"metadata": {"name": "cm"}, "data": {"key": "新配置"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// ConfigMap 的顶层 data(插件设置存储形态)必须参与 diff
|
||||
assertThat(entry(changes, "data.key").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "data.key").getOldValue()).isEqualTo("旧配置");
|
||||
assertThat(entry(changes, "data.key").getNewValue()).isEqualTo("新配置");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCompareArraysAsWholeLeaf() {
|
||||
var old = json("""
|
||||
{"spec": {"members": ["a", "b"], "tags": ["x"]}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"spec": {"members": ["a", "b"], "tags": ["x", "y"]}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// 相同数组跳过,不同数组整体一条(不做按下标配对)
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(entry(changes, "spec.tags").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.tags").getOldValue()).isEqualTo("[\"x\"]");
|
||||
assertThat(entry(changes, "spec.tags").getNewValue()).isEqualTo("[\"x\",\"y\"]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordTypeChangeAsUpdatedLeaf() {
|
||||
var old = json("""
|
||||
{"spec": {"value": {"nested": 1}}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"spec": {"value": "scalar-now"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(entry(changes, "spec.value").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.value").getNewValue()).isEqualTo("scalar-now");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullWhenNoRealChange() {
|
||||
var old = json("""
|
||||
{"apiVersion": "v1", "kind": "Post", "status": {"a": 1},
|
||||
"metadata": {"name": "p", "version": 9}, "spec": {"title": "同"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"apiVersion": "v1", "kind": "Post", "status": {"a": 2},
|
||||
"metadata": {"name": "p"}, "spec": {"title": "同"}}
|
||||
""");
|
||||
|
||||
// 仅噪音字段(status/version)不同 → 无实际变更
|
||||
assertThat(ChangeDiffEngine.compute("PUT", old, body)).isNull();
|
||||
}
|
||||
|
||||
// ===== 脱敏、截断与封顶 =====
|
||||
|
||||
@Test
|
||||
void shouldRedactSensitiveFieldsByPathSegment() {
|
||||
var body = json("""
|
||||
{"spec": {"password": "p@ss", "accessToken": "tk-1", "title": "ok"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("POST", null, body);
|
||||
|
||||
assertThat(entry(changes, "spec.password").getNewValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
assertThat(entry(changes, "spec.accessToken").getNewValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("ok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTruncateLongValues() {
|
||||
var longValue = "字".repeat(ChangeDiffEngine.MAX_VALUE_LENGTH + 50);
|
||||
var body = json("{\"spec\": {\"content\": \"" + longValue + "\"}}");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("POST", null, body);
|
||||
|
||||
assertThat(entry(changes, "spec.content").getNewValue())
|
||||
.isEqualTo("字".repeat(ChangeDiffEngine.MAX_VALUE_LENGTH)
|
||||
+ ChangeDiffEngine.TRUNCATION_SUFFIX);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCapChangesWithSummaryEntry() {
|
||||
var fields = new StringBuilder();
|
||||
for (int i = 0; i < ChangeDiffEngine.MAX_CHANGES + 10; i++) {
|
||||
if (i > 0) {
|
||||
fields.append(',');
|
||||
}
|
||||
fields.append("\"f").append(i).append("\": \"v").append(i).append('"');
|
||||
}
|
||||
var old = json("{\"spec\": {}}");
|
||||
var body = json("{\"spec\": {" + fields + "}}");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// 30 条实际变更 + 1 条汇总兜底
|
||||
assertThat(changes).hasSize(ChangeDiffEngine.MAX_CHANGES + 1);
|
||||
var summary = changes.get(ChangeDiffEngine.MAX_CHANGES);
|
||||
assertThat(summary.getField()).isEqualTo(ChangeDiffEngine.OVERFLOW_FIELD);
|
||||
assertThat(summary.getNewValue()).contains("共 " + (ChangeDiffEngine.MAX_CHANGES + 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFormatChangesForCsvColumn() {
|
||||
var changes = List.of(
|
||||
change(ChangeType.UPDATED, "spec.title", "旧", "新"),
|
||||
change(ChangeType.ADDED, "spec.cover", null, "c.png"),
|
||||
change(ChangeType.REMOVED, "spec.slug", "a", null));
|
||||
|
||||
assertThat(ChangeDiffEngine.formatChanges(changes))
|
||||
.isEqualTo("修改 spec.title:旧 → 新;新增 spec.cover:c.png;删除 spec.slug:a");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnEmptySummaryWhenNoChanges() {
|
||||
assertThat(ChangeDiffEngine.formatChanges(null)).isEmpty();
|
||||
assertThat(ChangeDiffEngine.formatChanges(List.of())).isEmpty();
|
||||
}
|
||||
|
||||
private static ChangeEntry change(ChangeType type, String field, String oldValue,
|
||||
String newValue) {
|
||||
var entry = new ChangeEntry();
|
||||
entry.setField(field);
|
||||
entry.setChangeType(type);
|
||||
entry.setOldValue(oldValue);
|
||||
entry.setNewValue(newValue);
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import run.halo.app.extension.ConfigMap;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
|
||||
/**
|
||||
* 扩展资源路径解析测试:/apis 与 /api 两种路由形态、子资源、集合级路径、
|
||||
* 未注册模型的降级。
|
||||
*/
|
||||
class ExtensionTargetsTest {
|
||||
|
||||
private SchemeManager schemeManager;
|
||||
private Scheme auditScheme;
|
||||
private Scheme configMapScheme;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
schemeManager = mock(SchemeManager.class);
|
||||
auditScheme = Scheme.buildFromType(AuditLog.class);
|
||||
configMapScheme = Scheme.buildFromType(ConfigMap.class);
|
||||
when(schemeManager.schemes()).thenReturn(List.of(auditScheme, configMapScheme));
|
||||
}
|
||||
|
||||
private static GroupVersionKind gvkOf(Scheme scheme) {
|
||||
return scheme.groupVersionKind();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveApisNamedResource() {
|
||||
var gvk = gvkOf(auditScheme);
|
||||
var target = ExtensionTargets.resolve(schemeManager,
|
||||
"/apis/" + gvk.group() + "/" + gvk.version() + "/" + auditScheme.plural() + "/abc");
|
||||
|
||||
assertThat(target).isNotNull();
|
||||
assertThat(target.gvk()).isEqualTo(gvk);
|
||||
assertThat(target.name()).isEqualTo("abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveSubResourceToMainResource() {
|
||||
// 子资源路径取主资源 name 段(子资源操作写入的也是主资源)
|
||||
var gvk = gvkOf(auditScheme);
|
||||
var target = ExtensionTargets.resolve(schemeManager,
|
||||
"/apis/" + gvk.group() + "/" + gvk.version() + "/" + auditScheme.plural()
|
||||
+ "/abc/publish");
|
||||
|
||||
assertThat(target).isNotNull();
|
||||
assertThat(target.name()).isEqualTo("abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForCollectionPath() {
|
||||
var gvk = gvkOf(auditScheme);
|
||||
assertThat(ExtensionTargets.resolve(schemeManager,
|
||||
"/apis/" + gvk.group() + "/" + gvk.version() + "/" + auditScheme.plural())).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForUnregisteredPlural() {
|
||||
assertThat(ExtensionTargets.resolve(schemeManager,
|
||||
"/apis/unknown.group/v1alpha1/things/abc")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveApiCoreModel() {
|
||||
// 空 group 核心模型(ConfigMap)走 /api/{version}/{plural}/{name}
|
||||
var target = ExtensionTargets.resolve(schemeManager, "/api/v1alpha1/configmaps/system");
|
||||
|
||||
assertThat(target).isNotNull();
|
||||
assertThat(target.gvk()).isEqualTo(gvkOf(configMapScheme));
|
||||
assertThat(target.gvk().group()).isEmpty();
|
||||
assertThat(target.name()).isEqualTo("system");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForApiCollectionPath() {
|
||||
assertThat(ExtensionTargets.resolve(schemeManager, "/api/v1alpha1/configmaps")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForUnrecognizedPath() {
|
||||
assertThat(ExtensionTargets.resolve(schemeManager, "/login")).isNull();
|
||||
assertThat(ExtensionTargets.resolve(schemeManager, "/web/other")).isNull();
|
||||
assertThat(ExtensionTargets.resolve(schemeManager, null)).isNull();
|
||||
assertThat(ExtensionTargets.resolve(schemeManager, " ")).isNull();
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import run.halo.app.extension.ConfigMap;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
|
||||
/**
|
||||
* HTTP 写请求标记测试(系统内部变更,产品设计 V2):目标标记的登记/解除与引用计数、
|
||||
* 活动宽限窗、设置类资源判定。
|
||||
*/
|
||||
class HttpWriteMarkerTest {
|
||||
|
||||
private SchemeManager schemeManager;
|
||||
private Scheme configMapScheme;
|
||||
private HttpWriteMarker marker;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
schemeManager = mock(SchemeManager.class);
|
||||
configMapScheme = Scheme.buildFromType(ConfigMap.class);
|
||||
when(schemeManager.schemes()).thenReturn(List.of(configMapScheme));
|
||||
marker = new HttpWriteMarker(schemeManager);
|
||||
}
|
||||
|
||||
private GroupVersionKind configMapGvk() {
|
||||
return configMapScheme.groupVersionKind();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldMarkTargetDuringRequestLifecycle() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost/api/v1alpha1/configmaps/system").build();
|
||||
|
||||
assertThat(marker.isMarked(configMapGvk(), "system")).isFalse();
|
||||
|
||||
marker.onRequestStart(request);
|
||||
assertThat(marker.isMarked(configMapGvk(), "system")).isTrue();
|
||||
|
||||
marker.onRequestComplete(request);
|
||||
assertThat(marker.isMarked(configMapGvk(), "system")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepMarkWhileOtherRequestStillActive() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost/api/v1alpha1/configmaps/system").build();
|
||||
|
||||
marker.onRequestStart(request);
|
||||
marker.onRequestStart(request);
|
||||
marker.onRequestComplete(request);
|
||||
// 并发同资源请求:引用计数清零前标记保持
|
||||
assertThat(marker.isMarked(configMapGvk(), "system")).isTrue();
|
||||
|
||||
marker.onRequestComplete(request);
|
||||
assertThat(marker.isMarked(configMapGvk(), "system")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldIgnoreUnregisteredTarget() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost/apis/unknown.group/v1alpha1/things/abc").build();
|
||||
|
||||
marker.onRequestStart(request);
|
||||
assertThat(marker.isMarked(new GroupVersionKind("unknown.group", "v1alpha1", "Thing"),
|
||||
"abc")).isFalse();
|
||||
// 解析失败不应残留活动计数条目
|
||||
marker.onRequestComplete(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportRecentWriteActivityWithinGraceWindow() {
|
||||
assertThat(marker.inSettingsGraceWindow()).isFalse();
|
||||
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost/api/v1alpha1/configmaps/system").build();
|
||||
marker.onRequestStart(request);
|
||||
assertThat(marker.inSettingsGraceWindow()).isTrue();
|
||||
|
||||
marker.onRequestComplete(request);
|
||||
assertThat(marker.inSettingsGraceWindow()).isTrue();
|
||||
|
||||
// 宽限窗后恢复(直接改写内部时间戳模拟时间流逝,避免真实等待)
|
||||
marker.lastActivityNanos = System.nanoTime() - HttpWriteMarker.GRACE.toNanos() - 1;
|
||||
assertThat(marker.inSettingsGraceWindow()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecognizeSettingsKinds() {
|
||||
assertThat(HttpWriteMarker.isSettingsKind(configMapGvk())).isTrue();
|
||||
assertThat(HttpWriteMarker.isSettingsKind(new GroupVersionKind("", "v1alpha1", "Secret")))
|
||||
.isTrue();
|
||||
var auditGvk = Scheme.buildFromType(AuditLog.class).groupVersionKind();
|
||||
assertThat(HttpWriteMarker.isSettingsKind(auditGvk)).isFalse();
|
||||
assertThat(HttpWriteMarker.isSettingsKind(
|
||||
new GroupVersionKind("content.halo.run", "v1alpha1", "Post"))).isFalse();
|
||||
}
|
||||
}
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import run.halo.app.extension.ConfigMap;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.Metadata;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.AbstractExtension;
|
||||
import run.halo.app.extension.GVK;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* 系统内部变更监听测试(产品设计 V2"系统内部变更"):update/delete 事件落库、
|
||||
* AuditLog 自身排除、HTTP 标记与设置类宽限窗跳过、簿记噪音跳过、异常不外抛。
|
||||
*/
|
||||
class InternalChangeWatcherTest {
|
||||
|
||||
/** 测试用扩展模型(group 非空,等价于真实内容模型如 Post)。 */
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@GVK(group = "test.guichumo.com", version = "v1alpha1", kind = "Widget",
|
||||
plural = "widgets", singular = "widget")
|
||||
static class Widget extends AbstractExtension {
|
||||
private WidgetSpec spec = new WidgetSpec();
|
||||
}
|
||||
|
||||
@Data
|
||||
static class WidgetSpec {
|
||||
private String title;
|
||||
private List<String> tags;
|
||||
}
|
||||
|
||||
private static final String API_VERSION = "test.guichumo.com/v1alpha1";
|
||||
|
||||
private ReactiveExtensionClient client;
|
||||
private SchemeManager schemeManager;
|
||||
private HttpWriteMarker writeMarker;
|
||||
private AuditRecorder recorder;
|
||||
private InternalChangeWatcher watcher;
|
||||
private Scheme widgetScheme;
|
||||
private Scheme configMapScheme;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
client = mock(ReactiveExtensionClient.class);
|
||||
schemeManager = mock(SchemeManager.class);
|
||||
writeMarker = mock(HttpWriteMarker.class);
|
||||
recorder = mock(AuditRecorder.class);
|
||||
widgetScheme = Scheme.buildFromType(Widget.class);
|
||||
configMapScheme = Scheme.buildFromType(ConfigMap.class);
|
||||
watcher = new InternalChangeWatcher(client, schemeManager, writeMarker, recorder,
|
||||
"operation-audit-configmap");
|
||||
}
|
||||
|
||||
private static Widget widget(String name, String title, java.util.Set<String> finalizers) {
|
||||
var widget = new Widget();
|
||||
widget.groupVersionKind(new GroupVersionKind("test.guichumo.com", "v1alpha1", "Widget"));
|
||||
var metadata = new Metadata();
|
||||
metadata.setName(name);
|
||||
metadata.setFinalizers(finalizers);
|
||||
metadata.setVersion(1L);
|
||||
widget.setMetadata(metadata);
|
||||
widget.getSpec().setTitle(title);
|
||||
return widget;
|
||||
}
|
||||
|
||||
private void stubSchemes() {
|
||||
when(schemeManager.fetch(any(GroupVersionKind.class))).thenReturn(Optional.empty());
|
||||
when(schemeManager.fetch(widgetScheme.groupVersionKind()))
|
||||
.thenReturn(Optional.of(widgetScheme));
|
||||
when(schemeManager.fetch(configMapScheme.groupVersionKind()))
|
||||
.thenReturn(Optional.of(configMapScheme));
|
||||
}
|
||||
|
||||
private static AuditLog auditLog(String name) {
|
||||
var auditLog = new AuditLog();
|
||||
auditLog.setApiVersion(AuditLog.GROUP + "/v1alpha1");
|
||||
auditLog.setKind("AuditLog");
|
||||
var metadata = new Metadata();
|
||||
metadata.setName(name);
|
||||
auditLog.setMetadata(metadata);
|
||||
return auditLog;
|
||||
}
|
||||
|
||||
private static ConfigMap configMap(String name, Map<String, String> data) {
|
||||
var configMap = new ConfigMap();
|
||||
configMap.groupVersionKind(new GroupVersionKind("", "v1alpha1", "ConfigMap"));
|
||||
var metadata = new Metadata();
|
||||
metadata.setName(name);
|
||||
configMap.setMetadata(metadata);
|
||||
configMap.setData(data);
|
||||
return configMap;
|
||||
}
|
||||
|
||||
// ===== 正常落库 =====
|
||||
|
||||
@Test
|
||||
void shouldRecordInternalUpdateWithDiff() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(any(), anyString())).thenReturn(false);
|
||||
when(writeMarker.inSettingsGraceWindow()).thenReturn(false);
|
||||
|
||||
watcher.onUpdate(widget("w1", "旧标题", Set.of()), widget("w1", "新标题", Set.of()));
|
||||
|
||||
var captor = ArgumentCaptor.forClass(String.class);
|
||||
verify(recorder).recordSystemChange(eq("PUT"), captor.capture(), eq("w1"),
|
||||
eq("/apis/test.guichumo.com/v1alpha1/widgets/w1"), any());
|
||||
assertThat(captor.getValue()).isEqualTo("widgets");
|
||||
|
||||
var changesCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(recorder).recordSystemChange(eq("PUT"), anyString(), eq("w1"),
|
||||
anyString(), changesCaptor.capture());
|
||||
var changes = (List<ChangeEntry>) (List<?>) changesCaptor.getValue();
|
||||
assertThat(changes).isNotNull().hasSize(1);
|
||||
assertThat(changes.get(0).getField()).isEqualTo("spec.title");
|
||||
assertThat(changes.get(0).getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(changes.get(0).getOldValue()).isEqualTo("旧标题");
|
||||
assertThat(changes.get(0).getNewValue()).isEqualTo("新标题");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordInternalDeleteWithRemovedEntries() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(any(), anyString())).thenReturn(false);
|
||||
when(writeMarker.inSettingsGraceWindow()).thenReturn(false);
|
||||
|
||||
watcher.onDelete(widget("w2", "旧标题", Set.of()));
|
||||
|
||||
var changesCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(recorder).recordSystemChange(eq("DELETE"), eq("widgets"), eq("w2"),
|
||||
eq("/apis/test.guichumo.com/v1alpha1/widgets/w2"), changesCaptor.capture());
|
||||
var changes = (List<ChangeEntry>) (List<?>) changesCaptor.getValue();
|
||||
assertThat(changes).isNotNull().allMatch(change -> change.getChangeType()
|
||||
== ChangeType.REMOVED);
|
||||
assertThat(changes).extracting(ChangeEntry::getField)
|
||||
.contains("spec.title", "metadata.name");
|
||||
}
|
||||
|
||||
// ===== 排除与跳过 =====
|
||||
|
||||
@Test
|
||||
void shouldSkipAuditLogChanges() {
|
||||
// 自身写入与保留期清理删除均不记录(也避免递归)
|
||||
watcher.onUpdate(auditLog("auditlog-1"), auditLog("auditlog-1"));
|
||||
|
||||
verifyNoInteractions(recorder);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipBookkeepingOnlyChanges() {
|
||||
stubSchemes();
|
||||
// 仅 finalizer/metadata 服务端管理子键变化:diff 为空,跳过
|
||||
var old = widget("w3", "标题", Set.of());
|
||||
old.getMetadata().setVersion(1L);
|
||||
var updated = widget("w3", "标题", Set.of("halo.run/cleanup"));
|
||||
updated.getMetadata().setVersion(2L);
|
||||
|
||||
watcher.onUpdate(old, updated);
|
||||
|
||||
verify(recorder, never()).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipUnregisteredModel() {
|
||||
// 未注册模型(Halo 也不会为其派发真实事件,此处防御性验证)
|
||||
stubSchemes();
|
||||
var thing = new AbstractExtension() {
|
||||
};
|
||||
thing.setApiVersion("unknown.group/v1alpha1");
|
||||
thing.setKind("Thing");
|
||||
var metadata = new Metadata();
|
||||
metadata.setName("t1");
|
||||
thing.setMetadata(metadata);
|
||||
|
||||
assertThatCode(() -> watcher.onUpdate(thing, thing)).doesNotThrowAnyException();
|
||||
verify(recorder, never()).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipTargetMarkedByActiveHttpRequest() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(widgetScheme.groupVersionKind(), "w1")).thenReturn(true);
|
||||
|
||||
watcher.onUpdate(widget("w1", "旧", Set.of()), widget("w1", "新", Set.of()));
|
||||
|
||||
verify(recorder, never()).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipSettingsKindsInGraceWindow() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(any(), anyString())).thenReturn(false);
|
||||
when(writeMarker.inSettingsGraceWindow()).thenReturn(true);
|
||||
|
||||
watcher.onUpdate(configMap("system", Map.of("basic", "{}")),
|
||||
configMap("system", Map.of("basic", "{\"title\":\"新\"}")));
|
||||
|
||||
verify(recorder, never()).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipOwnPluginConfigMap() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(any(), anyString())).thenReturn(false);
|
||||
when(writeMarker.inSettingsGraceWindow()).thenReturn(false);
|
||||
|
||||
// 插件配置保存走 json-config 端点,实际写的是本 ConfigMap,直接排除
|
||||
watcher.onUpdate(configMap("operation-audit-configmap", Map.of("audit", "{}")),
|
||||
configMap("operation-audit-configmap", Map.of("audit", "{\"enabled\":false}")));
|
||||
|
||||
verify(recorder, never()).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordConfigMapOutsideGraceWindow() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(any(), anyString())).thenReturn(false);
|
||||
when(writeMarker.inSettingsGraceWindow()).thenReturn(false);
|
||||
|
||||
watcher.onUpdate(configMap("theme", Map.of("theme", "default")),
|
||||
configMap("theme", Map.of("theme", "anatole")));
|
||||
|
||||
var pathCaptor = ArgumentCaptor.forClass(String.class);
|
||||
verify(recorder).recordSystemChange(eq("PUT"), eq("configmaps"), eq("theme"),
|
||||
pathCaptor.capture(), any());
|
||||
// 空 group 核心模型合成 /api/... 规范路径
|
||||
assertThat(pathCaptor.getValue()).isEqualTo("/api/v1alpha1/configmaps/theme");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldIgnoreCreateEvents() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(any(), anyString())).thenReturn(false);
|
||||
when(writeMarker.inSettingsGraceWindow()).thenReturn(false);
|
||||
|
||||
watcher.onAdd(widget("w4", "标题", Set.of()));
|
||||
|
||||
verify(recorder, never()).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipWhenDisposed() {
|
||||
stubSchemes();
|
||||
watcher.stop();
|
||||
|
||||
watcher.onUpdate(widget("w1", "旧", Set.of()), widget("w1", "新", Set.of()));
|
||||
|
||||
verify(recorder, never()).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
}
|
||||
|
||||
// ===== 生命周期与安全边界 =====
|
||||
|
||||
@Test
|
||||
void shouldRegisterOnStartAndRunDisposeHookOnStop() {
|
||||
stubSchemes();
|
||||
// client.watch 为 void 方法:mock 默认无操作,注册行为经 verify 验证
|
||||
var hook = mock(Runnable.class);
|
||||
watcher.registerDisposeHook(hook);
|
||||
|
||||
watcher.start();
|
||||
verify(client).watch(watcher);
|
||||
|
||||
watcher.stop();
|
||||
verify(hook).run();
|
||||
assertThat(watcher.isDisposed()).isTrue();
|
||||
|
||||
// disposed 后再次注册会被组合拒绝(addWatcher 检查 isDisposed)——防御性验证
|
||||
watcher.start();
|
||||
verify(client, times(2)).watch(watcher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSwallowCallbackExceptions() {
|
||||
stubSchemes();
|
||||
when(writeMarker.isMarked(any(), anyString())).thenReturn(false);
|
||||
when(writeMarker.inSettingsGraceWindow()).thenReturn(false);
|
||||
// recorder 抛出异常:回调运行在 Halo 写入链内,绝不能外抛影响业务写入
|
||||
org.mockito.Mockito.doThrow(new IllegalStateException("boom"))
|
||||
.when(recorder).recordSystemChange(anyString(), anyString(), anyString(),
|
||||
anyString(), any());
|
||||
|
||||
assertThatCode(() -> watcher.onUpdate(widget("w1", "旧", Set.of()),
|
||||
widget("w1", "新", Set.of()))).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSwallowSchemeLookupFailures() {
|
||||
when(schemeManager.fetch(any(GroupVersionKind.class)))
|
||||
.thenThrow(new IllegalStateException("boom"));
|
||||
|
||||
assertThatCode(() -> watcher.onUpdate(widget("w1", "旧", Set.of()),
|
||||
widget("w1", "新", Set.of()))).doesNotThrowAnyException();
|
||||
verifyNoInteractions(recorder);
|
||||
}
|
||||
|
||||
// ===== 设置门控(recordSystemChanges 默认开启,随 defaults 校验) =====
|
||||
@Test
|
||||
void shouldExposeSystemChangesSettingDefault() {
|
||||
assertThat(AuditSettings.defaults().recordSystemChangesOrDefault()).isTrue();
|
||||
assertThat(new AuditSettings(true, 90, null, false).recordSystemChangesOrDefault())
|
||||
.isFalse();
|
||||
}
|
||||
}
|
||||
+268
@@ -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();
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.net.URI;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 登录结果判定测试(LoginOutcome):Halo 2.26 登录端点表单提交的成功与失败均为
|
||||
* 302 重定向(成功 → /uc、2FA 页;失败 → /login?error=...&method=...),仅 XHR/JSON
|
||||
* 请求以 200/401 区分成败,成败判定必须结合重定向目标。
|
||||
*/
|
||||
class LoginOutcomeTest {
|
||||
|
||||
// ===== POST /login:状态码 + 重定向目标 =====
|
||||
|
||||
@Test
|
||||
void xhrSuccessIsNotFailure() {
|
||||
// XHR/JSON 登录成功:200 + 主体 JSON
|
||||
assertThat(LoginOutcome.isFailure(200, null)).isFalse();
|
||||
assertThat(LoginOutcome.isFailure(204, null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void xhrFailureIsFailure() {
|
||||
// XHR/JSON 登录失败:401 + JSON 错误体
|
||||
assertThat(LoginOutcome.isFailure(401, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void formSuccessRedirectIsNotFailure() {
|
||||
// 表单登录成功:302 → /uc(无 error 参数)
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/uc"))).isFalse();
|
||||
// 两步验证:302 → /challenges/two-factor/totp
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/challenges/two-factor/totp"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void formFailureRedirectWithErrorParamIsFailure() {
|
||||
// 表单登录失败:302 → /login?error=invalid-credential&method=local
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=invalid-credential&method=local"))).isTrue();
|
||||
// 账号禁用/限流等其他失败码同样含 error 参数
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=account-disabled&method=local"))).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(302,
|
||||
URI.create("/login?error=rate-limit-exceeded&method=local"))).isTrue();
|
||||
// 兜底失败分支:error 参数无值(/login?error&method=...)
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?error&method=local"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectWithoutLocationIsNotFailure() {
|
||||
// 3xx 但缺失 Location(无法确认失败):按成功处理,不凭空判失败
|
||||
assertThat(LoginOutcome.isFailure(302, null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingOrZeroStatusIsFailure() {
|
||||
// 状态码缺失(响应未写出)按失败处理,宁可多告警不漏报
|
||||
assertThat(LoginOutcome.isFailure(null, null)).isTrue();
|
||||
assertThat(LoginOutcome.isFailure(0, null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorParamNameMustMatchExactly() {
|
||||
// 含 error 字样的其他参数(如 errors=1)不算失败标记
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/uc?errors=1"))).isFalse();
|
||||
assertThat(LoginOutcome.isFailure(302, URI.create("/login?errors=1"))).isFalse();
|
||||
}
|
||||
|
||||
// ===== GET /login?error=...:失败回显 =====
|
||||
|
||||
@Test
|
||||
void loginPageWithErrorParamIsFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?error=invalid-credential&method=local"))
|
||||
.isTrue();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?error&method=local")).isTrue();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?method=local&error=invalid-credential"))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainLoginPageIsNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/login")).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/login?method=local")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherEndpointsAreNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho("/logout?error=x")).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/apis/core.halo.run/v1alpha1/login?error=x"))
|
||||
.isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/uc?error=x")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOrQuerylessPathIsNotFailureEcho() {
|
||||
assertThat(LoginOutcome.isFailureEcho(null)).isFalse();
|
||||
assertThat(LoginOutcome.isFailureEcho("/apis/content.halo.run/v1alpha1/posts")).isFalse();
|
||||
}
|
||||
}
|
||||
+107
-24
@@ -2,27 +2,43 @@ 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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/**
|
||||
* 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
* {@code /apis/**} 捕获过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
|
||||
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
|
||||
*
|
||||
* <p>认证端点({@code /login}、{@code /logout})不在本过滤器职责内(P0 修复:它们由
|
||||
* {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,此处透传不记录),
|
||||
* 其行为见 {@link AuthEndpointAuditWebFilterTest} 与过滤链集成测试。
|
||||
*/
|
||||
class OperationAuditWebFilterTest {
|
||||
|
||||
private final AuditRecorder recorder = mock(AuditRecorder.class);
|
||||
private final OperationAuditWebFilter filter = new OperationAuditWebFilter(recorder);
|
||||
private AuditRecorder recorder;
|
||||
private ChangeCaptureManager captureManager;
|
||||
private HttpWriteMarker writeMarker;
|
||||
private OperationAuditWebFilter filter;
|
||||
|
||||
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
||||
private static final WebFilterChainStub CHAIN = new WebFilterChainStub();
|
||||
@@ -36,6 +52,17 @@ class OperationAuditWebFilterTest {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
recorder = mock(AuditRecorder.class);
|
||||
captureManager = mock(ChangeCaptureManager.class);
|
||||
writeMarker = mock(HttpWriteMarker.class);
|
||||
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
||||
any(ChangeCapture.class)))
|
||||
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
|
||||
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureWriteWithAuthenticatedOperator() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
@@ -43,14 +70,15 @@ class OperationAuditWebFilterTest {
|
||||
.build());
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
java.util.List.of(() -> "ROLE_ADMIN"));
|
||||
List.of(() -> "ROLE_ADMIN"));
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(200), eq("admin"));
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq("admin"), isNull(), eq(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -61,20 +89,27 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginFailureAsUnknownUser() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
void shouldPassThroughAuthEndpointsWithoutRecording() {
|
||||
// P0 修复后认证端点由 AuthEndpointAuditWebFilter 在 Security 链之前捕获,
|
||||
// 本过滤器不再记录;写方法请求(POST /login、POST /logout)仍按统一语义
|
||||
// 登记内部变更归属标记(真实链上 POST 请求到不了链尾,GET 由透传处理)
|
||||
var login = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.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).record(any(RequestSnapshot.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME));
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(writeMarker, times(2)).onRequestStart(any());
|
||||
verify(writeMarker, times(2)).onRequestComplete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,7 +121,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,34 +131,82 @@ class OperationAuditWebFilterTest {
|
||||
.delete("/apis/core.halo.run/v1alpha1/users/xyz")
|
||||
.build());
|
||||
var anonymous = UsernamePasswordAuthenticationToken.authenticated(
|
||||
"anonymousUser", null, java.util.List.of());
|
||||
"anonymousUser", null, List.of());
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureLogoutAsAuth() {
|
||||
void shouldPassCaptureContextToRecorder() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/logout")
|
||||
.build());
|
||||
.put("/apis/content.halo.run/v1alpha1/posts/abc")
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Content-Length", "2")
|
||||
.body("{}"));
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
java.util.List.of());
|
||||
List.of(() -> "ROLE_ADMIN"));
|
||||
|
||||
// 捕获管理器返回装饰后的 exchange,并记录请求期传入的 capture 实例
|
||||
var captured = new ChangeCapture[1];
|
||||
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
||||
any(ChangeCapture.class)))
|
||||
.thenAnswer(inv -> {
|
||||
captured[0] = inv.getArgument(2);
|
||||
return Mono.just((ServerWebExchange) inv.getArgument(0));
|
||||
});
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(200), eq("admin"));
|
||||
var captor = org.mockito.ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||
verify(recorder).record(captor.capture(), eq(200), eq("admin"));
|
||||
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
|
||||
.isEqualTo("auth");
|
||||
// 请求期创建的同一个 capture 实例被透传给记录阶段
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
|
||||
eq("admin"), isNull(), eq(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldMarkCapturedWriteRequestLifecycle() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.put("/apis/content.halo.run/v1alpha1/posts/abc")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(writeMarker).onRequestStart(any());
|
||||
verify(writeMarker).onRequestComplete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldMarkNonCapturedWriteRequestLifecycle() {
|
||||
// /api/**(空 group 核心模型)不在捕获规则内,但写方法请求仍需登记标记:
|
||||
// 请求期触发的资源变更由该请求归属,避免内部变更通道重复/误记录
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.put("/api/v1alpha1/configmaps/system")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(writeMarker).onRequestStart(any());
|
||||
verify(writeMarker).onRequestComplete(any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotMarkReadRequests() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/apis/api.content.halo.run/v1alpha1/posts")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(writeMarker, never()).onRequestStart(any());
|
||||
verify(writeMarker, never()).onRequestComplete(any());
|
||||
}
|
||||
}
|
||||
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 操作描述推导测试:与前端 {@code ui/src/utils/audit.spec.ts} 的 describeOperation
|
||||
* 用例一一对应(Java 移植版需与前端推导结果完全一致,两处需同步修改)。
|
||||
*/
|
||||
class OperationDescriptionTest {
|
||||
|
||||
@Test
|
||||
void shouldDescribeLoginEndpointIncludingQuery() {
|
||||
assertThat(OperationDescription.describe("POST", "auth", "/login")).isEqualTo("登录");
|
||||
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
|
||||
assertThat(OperationDescription.describe("GET", "auth",
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("登录");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDescribeLogoutEndpoint() {
|
||||
assertThat(OperationDescription.describe("POST", "auth", "/logout")).isEqualTo("登出");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToAuthOperationForNonLoginLogoutAuthPath() {
|
||||
assertThat(OperationDescription.describe("POST", "auth", "/auth/other"))
|
||||
.isEqualTo("认证操作");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldComposeVerbAndResourceLabel() {
|
||||
assertThat(OperationDescription.describe("POST", "users",
|
||||
"/apis/api.console.halo.run/v1alpha1/users")).isEqualTo("新建用户");
|
||||
assertThat(OperationDescription.describe("PUT", "posts",
|
||||
"/apis/content.halo.run/v1alpha1/posts/post-abc")).isEqualTo("修改文章");
|
||||
assertThat(OperationDescription.describe("PATCH", "themes",
|
||||
"/apis/api.console.halo.run/v1alpha1/themes/theme-abc")).isEqualTo("修改主题");
|
||||
assertThat(OperationDescription.describe("DELETE", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc")).isEqualTo("删除插件");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldComposeSubActionVerbAndResourceLabel() {
|
||||
assertThat(OperationDescription.describe("POST", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish")).isEqualTo("发布文章");
|
||||
assertThat(OperationDescription.describe("POST", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/enable"))
|
||||
.isEqualTo("启用插件");
|
||||
assertThat(OperationDescription.describe("POST", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/disable"))
|
||||
.isEqualTo("停用插件");
|
||||
assertThat(OperationDescription.describe("POST", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/recycle"))
|
||||
.isEqualTo("移入回收站文章");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUseFullPhraseWithoutResourceName() {
|
||||
assertThat(OperationDescription.describe("PUT", "users",
|
||||
"/apis/api.console.halo.run/v1alpha1/users/admin/password")).isEqualTo("修改密码");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToBaseVerbForUnknownSubAction() {
|
||||
assertThat(OperationDescription.describe("PUT", "posts",
|
||||
"/apis/content.halo.run/v1alpha1/posts/post-abc/content")).isEqualTo("修改文章");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldStripQueryBeforeParsingSubAction() {
|
||||
assertThat(OperationDescription.describe("POST", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish?async=true"))
|
||||
.isEqualTo("发布文章");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToRawResourceTypeForUnknownType() {
|
||||
assertThat(OperationDescription.describe("POST", "workflows",
|
||||
"/apis/audit.guichumo.com/v1alpha1/workflows")).isEqualTo("新建workflows");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToRawMethodForUnknownMethod() {
|
||||
assertThat(OperationDescription.describe("TRACE", "posts",
|
||||
"/apis/content.halo.run/v1alpha1/posts/post-abc")).isEqualTo("TRACE文章");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToVerbPlusRawPathForUnparseablePath() {
|
||||
assertThat(OperationDescription.describe("DELETE", "other", "/somewhere/odd"))
|
||||
.isEqualTo("删除other");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleNullPath() {
|
||||
// 防御性:path 缺失时不应抛异常;资源标签来自 resourceType 映射,与 path 无关
|
||||
assertThat(OperationDescription.describe("POST", "users", null)).isEqualTo("新建用户");
|
||||
assertThat(OperationDescription.describe("POST", "workflows", null))
|
||||
.isEqualTo("新建workflows");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeriveLoginLogoutAuthActions() {
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/login")).isEqualTo("login");
|
||||
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
|
||||
assertThat(OperationDescription.actionOf("GET", "auth",
|
||||
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("login");
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/logout")).isEqualTo("logout");
|
||||
assertThat(OperationDescription.actionOf("POST", "auth", "/auth/other"))
|
||||
.isEqualTo("auth");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeriveMethodActions() {
|
||||
assertThat(OperationDescription.actionOf("POST", "users",
|
||||
"/apis/api.console.halo.run/v1alpha1/users")).isEqualTo("create");
|
||||
assertThat(OperationDescription.actionOf("PUT", "posts",
|
||||
"/apis/content.halo.run/v1alpha1/posts/post-abc")).isEqualTo("update");
|
||||
assertThat(OperationDescription.actionOf("PATCH", "themes",
|
||||
"/apis/api.console.halo.run/v1alpha1/themes/theme-abc")).isEqualTo("update");
|
||||
assertThat(OperationDescription.actionOf("DELETE", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc")).isEqualTo("delete");
|
||||
assertThat(OperationDescription.actionOf("GET", "posts",
|
||||
"/apis/content.halo.run/v1alpha1/posts/post-abc")).isEqualTo("view");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeriveSubActionFromPathSegment() {
|
||||
assertThat(OperationDescription.actionOf("POST", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish")).isEqualTo("publish");
|
||||
assertThat(OperationDescription.actionOf("PUT", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/unpublish"))
|
||||
.isEqualTo("unpublish");
|
||||
assertThat(OperationDescription.actionOf("PUT", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/recycle"))
|
||||
.isEqualTo("recycle");
|
||||
assertThat(OperationDescription.actionOf("PUT", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/restore")).isEqualTo("restore");
|
||||
assertThat(OperationDescription.actionOf("PUT", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/enable"))
|
||||
.isEqualTo("enable");
|
||||
assertThat(OperationDescription.actionOf("PUT", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/disable"))
|
||||
.isEqualTo("disable");
|
||||
assertThat(OperationDescription.actionOf("PUT", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/upgrade"))
|
||||
.isEqualTo("upgrade");
|
||||
assertThat(OperationDescription.actionOf("PUT", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/uninstall"))
|
||||
.isEqualTo("uninstall");
|
||||
assertThat(OperationDescription.actionOf("PUT", "plugins",
|
||||
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/reload"))
|
||||
.isEqualTo("reload");
|
||||
assertThat(OperationDescription.actionOf("POST", "comments",
|
||||
"/apis/api.comment.halo.run/v1alpha1/comments/comment-abc/reply"))
|
||||
.isEqualTo("reply");
|
||||
assertThat(OperationDescription.actionOf("PUT", "posts",
|
||||
"/apis/api.content.halo.run/v1alpha1/posts/post-abc/recalculate"))
|
||||
.isEqualTo("recalculate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNormalizeActivationToEnable() {
|
||||
// 激活与启用语义相同(主题/插件 activation 与 enable),归并为同一动作键便于统一筛选
|
||||
assertThat(OperationDescription.actionOf("PUT", "themes",
|
||||
"/apis/api.console.halo.run/v1alpha1/themes/theme-abc/activation"))
|
||||
.isEqualTo("enable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDerivePasswordSubActions() {
|
||||
assertThat(OperationDescription.actionOf("PUT", "users",
|
||||
"/apis/api.console.halo.run/v1alpha1/users/admin/password")).isEqualTo("password");
|
||||
assertThat(OperationDescription.actionOf("PUT", "users",
|
||||
"/apis/api.console.halo.run/v1alpha1/users/admin/resetpassword"))
|
||||
.isEqualTo("resetpassword");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldStripQueryBeforeDerivingAction() {
|
||||
assertThat(OperationDescription.actionOf("PUT", "posts",
|
||||
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish?async=true"))
|
||||
.isEqualTo("publish");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToNullActionForUnknownMethod() {
|
||||
assertThat(OperationDescription.actionOf("TRACE", "posts",
|
||||
"/apis/content.halo.run/v1alpha1/posts/post-abc")).isNull();
|
||||
// 未识别的子动作回退到方法推导
|
||||
assertThat(OperationDescription.actionOf("PUT", "posts",
|
||||
"/apis/content.halo.run/v1alpha1/posts/post-abc/content")).isEqualTo("update");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDescribeFromActionKey() {
|
||||
assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录");
|
||||
// 登录失败语义动作(POST /login 失败或 GET /login?error=... 失败回显)
|
||||
assertThat(OperationDescription.describeAction("login-failure", "auth"))
|
||||
.isEqualTo("登录失败");
|
||||
assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出");
|
||||
assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作");
|
||||
assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户");
|
||||
assertThat(OperationDescription.describeAction("update", "posts")).isEqualTo("修改文章");
|
||||
assertThat(OperationDescription.describeAction("delete", "plugins"))
|
||||
.isEqualTo("删除插件");
|
||||
assertThat(OperationDescription.describeAction("publish", "posts"))
|
||||
.isEqualTo("发布文章");
|
||||
assertThat(OperationDescription.describeAction("restore", "posts"))
|
||||
.isEqualTo("恢复文章");
|
||||
assertThat(OperationDescription.describeAction("enable", "themes"))
|
||||
.isEqualTo("启用主题");
|
||||
assertThat(OperationDescription.describeAction("password", "users"))
|
||||
.isEqualTo("修改密码");
|
||||
// 未识别的键回退 null(调用方回退 method 推导)
|
||||
assertThat(OperationDescription.describeAction(null, "posts")).isNull();
|
||||
assertThat(OperationDescription.describeAction("bogus", "posts")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDescribeSpecPreferingStoredAction() {
|
||||
// 落库语义动作优先:登录失败标注(回显页 HTTP 200 无法由路径重新推导出失败)
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setMethod("GET");
|
||||
spec.setResourceType("auth");
|
||||
spec.setPath("/login?error=invalid-credential&method=local");
|
||||
spec.setAction("login-failure");
|
||||
assertThat(OperationDescription.describe(spec)).isEqualTo("登录失败");
|
||||
|
||||
// 无标注(历史记录)回退 method/path 现场推导
|
||||
var legacy = new AuditLogSpec();
|
||||
legacy.setMethod("POST");
|
||||
legacy.setResourceType("auth");
|
||||
legacy.setPath("/login");
|
||||
assertThat(OperationDescription.describe(legacy)).isEqualTo("登录");
|
||||
|
||||
// 落库标注未识别时同样回退现场推导
|
||||
var bogus = new AuditLogSpec();
|
||||
bogus.setMethod("PUT");
|
||||
bogus.setResourceType("posts");
|
||||
bogus.setPath("/apis/content.halo.run/v1alpha1/posts/abc");
|
||||
bogus.setAction("bogus");
|
||||
assertThat(OperationDescription.describe(bogus)).isEqualTo("修改文章");
|
||||
}
|
||||
}
|
||||
+18
-4
@@ -27,14 +27,15 @@ class AuditSettingProviderTest {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenAnswer(inv -> {
|
||||
fetchCount.incrementAndGet();
|
||||
return Mono.just(new AuditSettings(false, 30));
|
||||
return Mono.just(new AuditSettings(false, 30, null, null));
|
||||
});
|
||||
|
||||
var first = provider.get().block();
|
||||
var second = provider.get().block();
|
||||
|
||||
assertThat(first).extracting(AuditSettings::enabled, AuditSettings::retentionDays)
|
||||
.containsExactly(false, 30);
|
||||
assertThat(first).extracting(AuditSettings::enabled, AuditSettings::retentionDays,
|
||||
AuditSettings::recordChanges)
|
||||
.containsExactly(false, 30, null);
|
||||
assertThat(second).isSameAs(first);
|
||||
assertThat(fetchCount.get()).isEqualTo(1);
|
||||
}
|
||||
@@ -62,12 +63,25 @@ class AuditSettingProviderTest {
|
||||
@Test
|
||||
void shouldNormalizeIllegalValues() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.just(new AuditSettings(null, 1)));
|
||||
.thenReturn(Mono.just(new AuditSettings(null, 1, null, null)));
|
||||
|
||||
var settings = provider.get().block();
|
||||
|
||||
assertThat(settings.enabledOrDefault()).isTrue();
|
||||
assertThat(settings.retentionDaysOrDefault()).isEqualTo(90);
|
||||
assertThat(settings.recordChangesOrDefault()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDisableRecordChangesWhenExplicitlyOff() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.just(new AuditSettings(true, 90, false, null)));
|
||||
|
||||
var settings = provider.get().block();
|
||||
|
||||
// 字段级变更开关显式关闭:捕获阶段跳过请求体缓存与旧状态抓取
|
||||
assertThat(settings.enabledOrDefault()).isTrue();
|
||||
assertThat(settings.recordChangesOrDefault()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-2
@@ -40,7 +40,7 @@ class RetentionCleanerTest {
|
||||
new RetentionCleaner(client, settingProvider, fixedClock);
|
||||
|
||||
private void stubSettings() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 90)));
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 90, null, null)));
|
||||
}
|
||||
|
||||
private static AuditLog logAt(Instant creation) {
|
||||
@@ -96,7 +96,7 @@ class RetentionCleanerTest {
|
||||
|
||||
@Test
|
||||
void shouldUseRetentionDaysFromSettings() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 7)));
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 7, null, null)));
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, 200, 0L, List.of())));
|
||||
|
||||
|
||||
@@ -26,8 +26,22 @@ tasks.register('buildFrontend', NpmTask) {
|
||||
dependsOn tasks.named('npmInstall')
|
||||
}
|
||||
|
||||
// 前端单元测试(vitest:路由注册形态等回归断言)
|
||||
tasks.register('testFrontend', NpmTask) {
|
||||
group = 'verification'
|
||||
description = 'Runs the Console UI unit tests (vitest).'
|
||||
args = ['run', 'test']
|
||||
inputs.files(
|
||||
fileTree('src'),
|
||||
file('package.json'),
|
||||
file('vitest.config.ts'),
|
||||
)
|
||||
dependsOn tasks.named('npmInstall')
|
||||
}
|
||||
|
||||
tasks.named('check') {
|
||||
dependsOn tasks.named('buildFrontend')
|
||||
dependsOn tasks.named('testFrontend')
|
||||
}
|
||||
|
||||
tasks.named('assemble') {
|
||||
|
||||
+582
@@ -6,6 +6,7 @@
|
||||
"": {
|
||||
"name": "plugin-operation-audit-ui",
|
||||
"dependencies": {
|
||||
"@formkit/vue": "^1.7.2",
|
||||
"@halo-dev/api-client": "2.26.0",
|
||||
"@halo-dev/components": "2.26.0",
|
||||
"@halo-dev/console-shared": "^2.21.0",
|
||||
@@ -16,8 +17,10 @@
|
||||
"@types/node": "^20.19.1",
|
||||
"@vitejs/plugin-vue": "^5.2.4",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
"axios": "^1.21.1",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^6.0.0",
|
||||
"vitest": "^5.1.1",
|
||||
"vue-tsc": "^2.2.10"
|
||||
}
|
||||
},
|
||||
@@ -534,6 +537,113 @@
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@formkit/core": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/core/-/core-1.7.2.tgz",
|
||||
"integrity": "sha512-XDRVqkDtOziU3z44hdvgWEqGpiv6nTNeCmP8cnESKkr24a4keQuEwmfDVvibYV0ywyTMg6ylp2lyklCYeRHykQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/dev": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/dev/-/dev-1.7.2.tgz",
|
||||
"integrity": "sha512-W38xbbFS4h4LTV22kUC6ZbPHBmlM2lVbAz5PSYU3SPaNc4FeXp4GTe4GzLEmcS82B+5L1zbSOgGB43kWZts7wA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/i18n": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/i18n/-/i18n-1.7.2.tgz",
|
||||
"integrity": "sha512-Zs6f+rtP2j2Nnt1HkNrL85WU6rtS1l1Q0BAQjCMGQPsbrppiL7/TZ5bNIrVm0DTntLgG3firDS7bNWAxPSwerQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2",
|
||||
"@formkit/validation": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/inputs": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/inputs/-/inputs-1.7.2.tgz",
|
||||
"integrity": "sha512-4xs7RJN8EFGctTCNRXBTvor2O8RvuEEK3q2Hl/RMU5lhhn5tmck90fkkeAr9o+rWRoSNiV8XgbLQArQ/B1IYPw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/observer": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/observer/-/observer-1.7.2.tgz",
|
||||
"integrity": "sha512-KUr5mcu2SAeHOOK1FaMyFigtA8hkHLsUkaPFWpTC81j79o1AUjJppmfPaX6PbtlHLeMs2Zq8Qhp6VAhi7D2WJg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/rules": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/rules/-/rules-1.7.2.tgz",
|
||||
"integrity": "sha512-2e5qKlXzmL9LAetncFp7xkHEX/UAJsU3bo1iL3idloH3HALf5fIdg3lgOKwCNDMdLjbfiKJ6lVwFaeFfFpcDKw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2",
|
||||
"@formkit/validation": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/themes": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/themes/-/themes-1.7.2.tgz",
|
||||
"integrity": "sha512-AaZHy7l9D44Ya3cQRqZ8RIpaTTsCjTB1gX13NlpqYSs6yG0yBTmJ7L7kW60bOGdhs/vmIwSel578EBwz98nybQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/utils": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/utils/-/utils-1.7.2.tgz",
|
||||
"integrity": "sha512-bBF6alUBOqFfJHjVB95Vck0hp36vlw4QfFJxGfTO6BX68AEaFzzzabtpwfy0DbcHtwHh4Yn7l/rOWGxXEve+QQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@formkit/validation": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/validation/-/validation-1.7.2.tgz",
|
||||
"integrity": "sha512-JJsLP7AI/++VujdwtBeUcPhCqY3FXSKZ7hajT7Ow5Feab7JLqVPjxVMFbXDgEOLjq0ex1NX/I+EQHfm5sqMRsA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/observer": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/vue": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/vue/-/vue-1.7.2.tgz",
|
||||
"integrity": "sha512-jrvXl2ZhS6X5klTbP4N5zc0Dg37AjbAf8SCVoz7mfligVkmwrrF4SN3waMBcH+n9gqT+vrkOYb6bQXdvjUdnCQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@formkit/core": "^1.7.2",
|
||||
"@formkit/dev": "^1.7.2",
|
||||
"@formkit/i18n": "^1.7.2",
|
||||
"@formkit/inputs": "^1.7.2",
|
||||
"@formkit/observer": "^1.7.2",
|
||||
"@formkit/rules": "^1.7.2",
|
||||
"@formkit/themes": "^1.7.2",
|
||||
"@formkit/utils": "^1.7.2",
|
||||
"@formkit/validation": "^1.7.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@halo-dev/api-client": {
|
||||
"version": "2.26.0",
|
||||
"resolved": "https://registry.npmjs.org/@halo-dev/api-client/-/api-client-2.26.0.tgz",
|
||||
@@ -608,12 +718,33 @@
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/resolve-uri": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
|
||||
"integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/sourcemap-codec": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
|
||||
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@jridgewell/trace-mapping": {
|
||||
"version": "0.3.31",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
|
||||
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/resolve-uri": "^3.1.0",
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@rollup/rollup-android-arm-eabi": {
|
||||
"version": "4.68.8",
|
||||
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.8.tgz",
|
||||
@@ -1017,6 +1148,24 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@types/chai": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
|
||||
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/deep-eql": "*",
|
||||
"assertion-error": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/estree": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
|
||||
@@ -1048,6 +1197,64 @@
|
||||
"vue": "^3.2.25"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.1.tgz",
|
||||
"integrity": "sha512-b2OgTB4+3ImWIVafXKazJXwLKwQxUNnix6b3xUvUTMh7RyXlrtzoxfZr8aEz9zkHOMAS4K5lu3TvFWoiVeVTQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/trace-mapping": "0.3.31",
|
||||
"@vitest/spy": "5.1.1",
|
||||
"estree-walker": "^3.0.3",
|
||||
"magic-string": "^1.4.5"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"msw": "^2.4.9 || ^3.0.0",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"msw": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker/node_modules/estree-walker": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
|
||||
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/estree": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker/node_modules/magic-string": {
|
||||
"version": "1.4.5",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
|
||||
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/spy": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.1.tgz",
|
||||
"integrity": "sha512-6K8C6alQG1/Yc8/ZI22iJS7JEsxPdVzqtqDq+/xM4Z0mGVykemMVjLhqMy/q6/IHYG3kKD8hKSwRen/ZdyI9vQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@volar/language-core": {
|
||||
"version": "2.4.15",
|
||||
"resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.15.tgz",
|
||||
@@ -1230,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": {
|
||||
"version": "1.0.13",
|
||||
"resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-1.0.13.tgz",
|
||||
@@ -1244,6 +1464,36 @@
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/assertion-error": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"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": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
@@ -1290,6 +1540,29 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/chai": {
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
|
||||
"integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"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": {
|
||||
"version": "0.3.2",
|
||||
"resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz",
|
||||
@@ -1310,6 +1583,34 @@
|
||||
"dev": true,
|
||||
"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": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
@@ -1373,6 +1674,22 @@
|
||||
"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": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
|
||||
@@ -1421,6 +1738,16 @@
|
||||
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/expect-type": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
||||
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/exsolve": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz",
|
||||
@@ -1464,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": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -1549,6 +1914,22 @@
|
||||
"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": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
|
||||
@@ -1571,6 +1952,20 @@
|
||||
"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": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
|
||||
@@ -1612,6 +2007,29 @@
|
||||
"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": {
|
||||
"version": "9.0.9",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
|
||||
@@ -1628,6 +2046,13 @@
|
||||
"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": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz",
|
||||
@@ -1665,6 +2090,20 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/obug": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz",
|
||||
"integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
"https://github.com/sponsors/sxzz",
|
||||
"https://opencollective.com/debug"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/path-browserify": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
|
||||
@@ -1738,6 +2177,16 @@
|
||||
"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": {
|
||||
"version": "6.17.1",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz",
|
||||
@@ -1894,6 +2343,33 @@
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/std-env": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
|
||||
"integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "6.2.4",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.4.tgz",
|
||||
"integrity": "sha512-SQ52jEncXxbMCzJuY2A/jGIbbAu6NYsBWW7grz2pNE+EnzQdoGaoBfpk4qC/opE7qiUcGmGgaGIz5EoHdS1O9w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyexec": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
|
||||
"integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.17",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||
@@ -2007,6 +2483,99 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vitest": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.1.tgz",
|
||||
"integrity": "sha512-trVmzUFOSraCZcI3uZIMD5FqBh4atFkC/XuJP/IU7qtyQay0FCs3Ia+0QiQ2JJwGyWG/xrcBoJNel2+O7kEZ0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/chai": "^5.2.2",
|
||||
"@vitest/mocker": "5.1.1",
|
||||
"chai": "^6.3.0",
|
||||
"es-module-lexer": "^2.3.2",
|
||||
"expect-type": "^1.4.0",
|
||||
"magic-string": "^1.4.5",
|
||||
"obug": "^3.0.0",
|
||||
"picomatch": "^4.0.7",
|
||||
"std-env": "^4.3.0",
|
||||
"tinybench": "^6.2.3",
|
||||
"tinyexec": "^1.3.1",
|
||||
"tinyglobby": "^0.2.17",
|
||||
"why-is-node-running": "3.2.1"
|
||||
},
|
||||
"bin": {
|
||||
"vitest": "vitest.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@edge-runtime/vm": "*",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@types/node": "^22.0.0 || >=24.0.0",
|
||||
"@vitest/browser-playwright": "5.1.1",
|
||||
"@vitest/browser-preview": "5.1.1",
|
||||
"@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
|
||||
"@vitest/coverage-istanbul": "5.1.1",
|
||||
"@vitest/coverage-v8": "5.1.1",
|
||||
"@vitest/ui": "5.1.1",
|
||||
"happy-dom": "*",
|
||||
"jsdom": "*",
|
||||
"vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@edge-runtime/vm": {
|
||||
"optional": true
|
||||
},
|
||||
"@opentelemetry/api": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-playwright": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-preview": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-webdriverio": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/coverage-istanbul": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/coverage-v8": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/ui": {
|
||||
"optional": true
|
||||
},
|
||||
"happy-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"jsdom": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vitest/node_modules/magic-string": {
|
||||
"version": "1.4.5",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
|
||||
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-uri": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.2.0.tgz",
|
||||
@@ -2051,6 +2620,19 @@
|
||||
"peerDependencies": {
|
||||
"typescript": ">=5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/why-is-node-running": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
|
||||
"integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"why-is-node-running": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,11 @@
|
||||
"build": "npm run type-check && npm run build-only",
|
||||
"build-only": "vite build",
|
||||
"dev": "vite build --watch --mode=development",
|
||||
"type-check": "vue-tsc --noEmit"
|
||||
"type-check": "vue-tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@formkit/vue": "^1.7.2",
|
||||
"@halo-dev/api-client": "2.26.0",
|
||||
"@halo-dev/components": "2.26.0",
|
||||
"@halo-dev/console-shared": "^2.21.0",
|
||||
@@ -19,8 +21,10 @@
|
||||
"@types/node": "^20.19.1",
|
||||
"@vitejs/plugin-vue": "^5.2.4",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
"axios": "^1.21.1",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^6.0.0",
|
||||
"vitest": "^5.1.1",
|
||||
"vue-tsc": "^2.2.10"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/* 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 interface ConfigurationParameters {
|
||||
apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
|
||||
username?: string;
|
||||
password?: string;
|
||||
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise<string>);
|
||||
basePath?: string;
|
||||
serverIndex?: number;
|
||||
baseOptions?: any;
|
||||
formDataCtor?: new () => any;
|
||||
}
|
||||
|
||||
export class Configuration {
|
||||
/**
|
||||
* parameter for apiKey security
|
||||
* @param name security name
|
||||
* @memberof Configuration
|
||||
*/
|
||||
apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
|
||||
/**
|
||||
* parameter for basic security
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof Configuration
|
||||
*/
|
||||
username?: string;
|
||||
/**
|
||||
* parameter for basic security
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof Configuration
|
||||
*/
|
||||
password?: string;
|
||||
/**
|
||||
* parameter for oauth2 security
|
||||
* @param name security name
|
||||
* @param scopes oauth2 scope
|
||||
* @memberof Configuration
|
||||
*/
|
||||
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise<string>);
|
||||
/**
|
||||
* override base path
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof Configuration
|
||||
*/
|
||||
basePath?: string;
|
||||
/**
|
||||
* override server index
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof Configuration
|
||||
*/
|
||||
serverIndex?: number;
|
||||
/**
|
||||
* base options for axios calls
|
||||
*
|
||||
* @type {any}
|
||||
* @memberof Configuration
|
||||
*/
|
||||
baseOptions?: any;
|
||||
/**
|
||||
* The FormData constructor that will be used to create multipart form data
|
||||
* requests. You can inject this here so that execution environments that
|
||||
* do not support the FormData class can still run the generated client.
|
||||
*
|
||||
* @type {new () => FormData}
|
||||
*/
|
||||
formDataCtor?: new () => any;
|
||||
|
||||
constructor(param: ConfigurationParameters = {}) {
|
||||
this.apiKey = param.apiKey;
|
||||
this.username = param.username;
|
||||
this.password = param.password;
|
||||
this.accessToken = param.accessToken;
|
||||
this.basePath = param.basePath;
|
||||
this.serverIndex = param.serverIndex;
|
||||
this.baseOptions = param.baseOptions;
|
||||
this.formDataCtor = param.formDataCtor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
public isJsonMime(mime: string): boolean {
|
||||
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
|
||||
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
|
||||
#
|
||||
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
|
||||
|
||||
git_user_id=$1
|
||||
git_repo_id=$2
|
||||
release_note=$3
|
||||
git_host=$4
|
||||
|
||||
if [ "$git_host" = "" ]; then
|
||||
git_host="github.com"
|
||||
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
|
||||
fi
|
||||
|
||||
if [ "$git_user_id" = "" ]; then
|
||||
git_user_id="GIT_USER_ID"
|
||||
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
|
||||
fi
|
||||
|
||||
if [ "$git_repo_id" = "" ]; then
|
||||
git_repo_id="GIT_REPO_ID"
|
||||
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
|
||||
fi
|
||||
|
||||
if [ "$release_note" = "" ]; then
|
||||
release_note="Minor update"
|
||||
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
|
||||
fi
|
||||
|
||||
# Initialize the local directory as a Git repository
|
||||
git init
|
||||
|
||||
# Adds the files in the local repository and stages them for commit.
|
||||
git add .
|
||||
|
||||
# Commits the tracked changes and prepares them to be pushed to a remote repository.
|
||||
git commit -m "$release_note"
|
||||
|
||||
# Sets the new remote
|
||||
git_remote=$(git remote)
|
||||
if [ "$git_remote" = "" ]; then # git remote not defined
|
||||
|
||||
if [ "$GIT_TOKEN" = "" ]; then
|
||||
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
|
||||
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
|
||||
else
|
||||
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
git pull origin master
|
||||
|
||||
# Pushes (Forces) the changes in the local repository up to the remote repository
|
||||
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
|
||||
git push origin master 2>&1 | grep -v 'To https'
|
||||
@@ -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";
|
||||
export * from "./configuration";
|
||||
export * from "./models";
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user