Compare commits
19
Commits
cb3ff6ef17
...
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 |
@@ -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
|
||||
@@ -11,7 +11,8 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
|
||||
|---|---|
|
||||
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
||||
| 系统内部变更 | 定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,执行者记 "system"(界面展示"系统"),与页面/API 操作区分归属、不重复记录 |
|
||||
| 语义动作标注 | 捕获时标注语义动作键(登录/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
|
||||
| 语义动作标注 | 捕获时标注语义动作键(登录/登录失败/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
|
||||
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成败均为 302 重定向,以重定向目标 `error` 参数区分):失败尝试与失败回显页(`GET /login?error=...`)在列表/详情/CSV 中显示红色「失败」,而非被页面渲染的绿色 HTTP 200 掩盖 |
|
||||
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 |
|
||||
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) |
|
||||
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) |
|
||||
|
||||
@@ -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)完成自动化检查、构建及安装/启停验证后再用于生产环境。
|
||||
@@ -31,7 +31,7 @@ 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 副产物不重复记录;插件自身配置写入排除。
|
||||
- 每条记录字段:
|
||||
|
||||
@@ -79,22 +79,23 @@ Console 左侧菜单新增"操作审计"页:
|
||||
|
||||
| 功能 | 说明 | 阶段 |
|
||||
|---|---|---|
|
||||
| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 |
|
||||
| 语义动作标注 | 区分"发布/编辑/恢复/登录失败"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 |
|
||||
| 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 |
|
||||
| 系统内部变更 | 定时发布等非 HTTP 触发的变更:经扩展模型 Watcher 通道观测全部资源写入,用户可写面有实际变化的更新/删除落库,执行者记 "system"(Console 展示"系统");与 HTTP 记录按目标标记区分归属、不重复记录 | V2 已实现 |
|
||||
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
|
||||
| 告警通知 | 登录失败告警:统计窗口内失败达到阈值时向 Webhook 地址异步推送一次通用 JSON 告警(告警后窗口重开防轰炸,登录成功立即清零;独立于审计开关,默认关闭) | V2 已实现 |
|
||||
| 登录失败标注 | 登录成败按 Halo 登录端点契约判定(表单登录成功与失败均为 302 重定向,以重定向目标是否含 `error` 参数区分,见 `LoginOutcome`):失败的登录尝试与失败回显页(`GET /login?error=...`,HTTP 200)标注语义动作 `login-failure`,列表/详情/CSV 显示红色「失败」而非裸状态码,避免绿色 200/302 误读为登录成功;HTTP 状态码仍如实记录 | V2+ 已实现 |
|
||||
| 操作回滚 | 不在产品范围内 | 不做 |
|
||||
|
||||
## 7. 已知局限
|
||||
|
||||
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2)
|
||||
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)不记录(几乎均伴随页面/API 操作,已被 HTTP 通道捕获);操作描述由事件类型推导(更新/删除),具体语义以字段级 diff 为准
|
||||
- 系统内部变更的归属降噪为通用规则:设置类资源(ConfigMap/Secret)在写请求活动宽限窗内的变更视为 HTTP 副产物跳过;极少数"路径与实际写入资源不一致"的非设置类端点,其副产物可能记为 system(已知取舍,完整性优先)
|
||||
- reconciler 在页面/API 操作后的簿记写入(如增删 finalizer)不产生记录(用户可写面无实际变化即跳过);若簿记同时携带真实字段变更,会额外产生一条 system 记录(罕见)
|
||||
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中
|
||||
- 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更
|
||||
- 登录失败告警仅覆盖 POST /login 的失败结果(非 2xx),不含尝试的用户名(与登录记录同一局限);告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
|
||||
- 登录成败判定依赖 Halo 登录端点契约(表单登录成败均为 302 重定向,失败目标含 `error` 参数):Halo 若调整失败重定向格式或引入新的登录方式,需同步调整 `LoginOutcome`;告警仅覆盖 POST /login,登录页 GET 与登出不算尝试;告警为通用 JSON POST,不内置钉钉、企业微信、飞书等平台的消息格式适配;Webhook 推送失败不重试,仅记运行日志
|
||||
- 升级前落库的历史记录无法补标注登录失败:表单登录失败(POST /login,302)在列表中仍显示数字状态码,仅失败回显页(GET,路径含 `error` 参数)可现场推导;升级后新记录由捕获时标注(`spec.action = login-failure`),不再有此局限
|
||||
- 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******`
|
||||
- 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中
|
||||
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口)
|
||||
@@ -103,7 +104,7 @@ Console 左侧菜单新增"操作审计"页:
|
||||
## 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)
|
||||
@@ -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,7 +21,7 @@
|
||||
| 服务端 | 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 自动渲染,零前端代码 |
|
||||
@@ -51,12 +51,14 @@ plugin-operation-audit/
|
||||
│ │ │ ├── InternalChangeWatcher.java # 系统内部变更监听(D8)
|
||||
│ │ │ ├── AuditWatchConfiguration.java # Watcher 装配(注入自身 configMapName)
|
||||
│ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试)
|
||||
│ │ │ ├── LoginOutcome.java # 登录成败判定:状态码 + 重定向目标 error 参数(纯函数)
|
||||
│ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数)
|
||||
│ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照
|
||||
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
|
||||
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
|
||||
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
|
||||
│ │ │ ├── OperationAuditWebFilter.java
|
||||
│ │ │ ├── AuthEndpointAuditWebFilter.java # 认证端点捕获(BeforeSecurityWebFilter,链首)
|
||||
│ │ │ ├── OperationAuditWebFilter.java # /apis/** 捕获(AfterSecurityWebFilter,链尾)
|
||||
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
|
||||
│ │ └── housekeeping/
|
||||
│ │ └── RetentionCleaner.java # 定时清理
|
||||
@@ -77,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 审计写入:响应式直写
|
||||
|
||||
@@ -211,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 资源解析规则(通用,不追求语义完美)
|
||||
|
||||
@@ -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 |
@@ -28,6 +28,9 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
|
||||
- **登录失败告警**:统计窗口内登录失败达到阈值时向 Webhook 地址异步推送 JSON 告警
|
||||
(默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零;内容含尝试的用户名,
|
||||
可区分定向撞库与无差别扫描);独立于审计开关,在插件设置「告警通知」中配置(默认关闭)。
|
||||
Webhook 地址凭据存于 Halo `Secret`(设置仅保存 Secret 引用,支持含 `access_token` 等
|
||||
凭据的地址);发送前对地址做 SSRF 防护校验(http(s) 白名单、拒绝内网/环回/链路本地/
|
||||
云元数据等受限地址段,并钉定校验通过的地址建连以防范 DNS rebinding)。
|
||||
该区提供「发送测试告警」入口:以 `type: "test"` 测试消息向已保存的 Webhook 地址推送并
|
||||
同步反馈发送结果,无需等待真实告警即可验证配置是否可用。
|
||||
- **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录,
|
||||
@@ -57,7 +60,7 @@ Console「插件 → 操作审计 → 设置」:
|
||||
| 记录系统内部变更 | 开 | 记录定时发布等非页面操作触发的资源变更(执行者记为 system) |
|
||||
| 保留天数 | 90 | 最小 7 天;过期记录每日自动清理 |
|
||||
| 启用登录失败告警 | 关 | 统计窗口内失败达到阈值时推送 Webhook 告警(独立于审计开关) |
|
||||
| Webhook 地址 | 空 | 接收告警的 http(s) 地址,JSON POST 异步推送 |
|
||||
| Webhook 地址(Secret) | 空 | 选择或创建存放 Webhook 地址的 Secret(键 `webhookUrl`);地址仅存于 Secret,可含 access_token 等凭据,JSON POST 异步推送 |
|
||||
| 发送测试告警(按钮) | - | 向已保存的 Webhook 地址推送 `type: "test"` 测试消息并直接反馈发送结果(不保存配置值,仅超级管理员可用) |
|
||||
| 触发阈值(次) | 5 | 统计窗口内累计登录失败达到该次数即触发一次告警 |
|
||||
| 统计窗口(分钟) | 5 | 失败次数的累计窗口;告警后窗口重开,登录成功立即清零 |
|
||||
@@ -65,7 +68,9 @@ Console「插件 → 操作审计 → 设置」:
|
||||
设置经 60 秒 TTL 缓存读取,变更最多延迟 1 分钟生效。
|
||||
|
||||
**告警负载**:通用 JSON 结构(`type` / `title` / `content` / `timestamp` / `data`),
|
||||
以 JSON POST 异步推送,超时 10 秒、失败不重试仅记日志:
|
||||
以 JSON POST 异步推送,超时 10 秒、失败不重试仅记日志;发送前经 SSRF 防护校验,
|
||||
受限地址(内网/环回/元数据等)在建立连接前即拒绝,校验失败与推送失败同样只记日志
|
||||
(日志只记主机名,不记可能含凭据的完整地址):
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -88,16 +93,17 @@ Console「插件 → 操作审计 → 设置」:
|
||||
|
||||
「发送测试告警」以相同结构推送 `type: "test"` 的测试消息(接收方可识别为测试消息),
|
||||
推送结果同步返回并提示到设置页(成功/失败 + 原因摘要),同时反馈到运行日志;
|
||||
Webhook 未配置或非法时提示先保存设置。
|
||||
Webhook Secret 未配置、Secret 缺少 `webhookUrl` 键时提示先完成配置。
|
||||
|
||||
不内置钉钉、企业微信、飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
|
||||
不内置钉钉、企业微信、飞书等平台的专属消息格式适配,需要时可在中转服务侧转换
|
||||
(地址凭据已可安全存于 Secret,直连含 token 的地址在传输层可行,消息格式仍需接收方兼容通用 JSON)。
|
||||
|
||||
## 模型 group 与权限标识
|
||||
|
||||
- **group**:已按"自有域名反写(`audit.<你的域名>`)"约定定为 `audit.guichumo.com`。
|
||||
唯一事实来源是 `AuditLog.GROUP` 常量(查询端点、测试挂载路径均引用它);
|
||||
`role-template.yaml` 的 `apiGroups` 与 `ui/src/views/AuditLogList.vue` 的
|
||||
`QUERY_ENDPOINT` 需与其保持一致。⚠️ group 是已落库数据的身份标识,一旦插件启用并
|
||||
`role-template.yaml` 的 `apiGroups` 与 build.gradle `openApi.groupingRules.pathsToMatch`
|
||||
需与其保持一致。⚠️ group 是已落库数据的身份标识,一旦插件启用并
|
||||
产生审计记录,再改 group 会导致旧记录不可见,届时请勿随意变更。
|
||||
- **UI 权限标识**:`plugin:operation-audit:view`(role-template.yaml 与 `ui/src/index.ts`
|
||||
保持一致即可,如需改名请两处同步)。
|
||||
@@ -120,11 +126,18 @@ Webhook 未配置或非法时提示先保存设置。
|
||||
- 审计写入失败静默降级为运行日志,不阻塞业务操作。
|
||||
- 来源 IP 取自 Halo HTTP 服务器解析后的地址(含 forwarding 配置):
|
||||
反向代理未配置 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 + 索引查询,全程响应式非阻塞。
|
||||
- 目标平台 Halo 2.26.1(JDK 21)。捕获经双过滤器扩展点分治:`/apis/**` 写操作走
|
||||
`AfterSecurityWebFilter`(认证之后,`doFinally` 读最终状态码);认证端点 `/login`、
|
||||
`/logout` 走 `BeforeSecurityWebFilter`(Security 链最前)——表单登录/登出过滤器命中
|
||||
请求后直接完成 302 响应、不再向下游传递,链尾过滤器永远看不到认证端点请求,认证端点
|
||||
必须在链首承接(操作者记"未知用户",登录尝试账号由请求体白名单提取)。存储为自定义
|
||||
Extension + 索引查询,全程响应式非阻塞。
|
||||
- 系统内部变更经 `ReactiveExtensionClient.watch(Watcher)` 全局 Watcher 通道观测所有
|
||||
扩展模型写入(回调在写入链内执行,全程捕获异常不影响业务):Halo 对仅 status 变化
|
||||
或无实际变化的更新不派发事件,回收站清理走存储层不产生事件,天然降噪;HTTP 写请求
|
||||
@@ -137,31 +150,52 @@ Webhook 未配置或非法时提示先保存设置。
|
||||
遍历全量,流式输出 CSV——升序保证导出期间并发写入不打乱分页边界。
|
||||
- 定时清理采用 Reactor 调度方案(技术方案风险项 #3 预案),不依赖 `@Scheduled`
|
||||
在插件上下文的可用性。
|
||||
- **API 客户端生成**(官方检查清单第 2 条):Console UI 的 TS 类型与请求方法全部由
|
||||
devtools `generateApiClient` 生成(`ui/src/api/generated`),UI 经 `ui/src/api/index.ts`
|
||||
封装层注入宿主 `axiosInstance` 调用,不手写类型/端点路径,不裸 `fetch`。管线配置在
|
||||
build.gradle `haloPlugin.openApi`(groupingRules 限定自有子资源端点,`AuditLog`
|
||||
模型类型经响应 schema 引用生成);规范 JSON 落盘 `build/openapi/`(不入库)。
|
||||
当前入库的规范文件为 **bootstrap 契约**(`build/openapi/extensionApis.json` 的一次性
|
||||
手工对齐产物,与 Springdoc 声明一一对应)——生成任务需从运行中的 Halo 抓取
|
||||
OpenAPI 文档(需 Docker 或 `useExistingServer`),待环境可用时运行
|
||||
`./gradlew generateOpenApiDocs generateApiClient` 即以运行时契约覆盖重生成;
|
||||
此后修改 API 契约一律改后端 Springdoc 声明再重跑生成任务。
|
||||
- 登录失败告警(产品设计 V2「告警通知」):触发点在捕获过滤器(POST `/login` 结束,
|
||||
经 `CaptureRule.isLoginAttempt` 判定),`LoginFailureAlertService` 维护阈值窗口状态
|
||||
(告警后重开窗口防轰炸,登录成功清零;状态为单例计数,无内存队列),设置经
|
||||
`AlertSettingProvider`(60s TTL 缓存)读取、独立于审计开关;`AlertWebhookSender`
|
||||
以 JSON POST 异步推送(fire-and-forget,超时 10 秒、失败不重试不抛出)。
|
||||
`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/
|
||||
URL 非法一律归一为失败结果,永不抛出,真实告警路径语义不变);`AlertTestEndpoint`
|
||||
地址校验拒绝一律归一为失败结果,永不抛出,真实告警路径语义不变);`AlertTestEndpoint`
|
||||
以 `POST /apis/audit.guichumo.com/v1alpha1/alerts/-/test` 同步等待结果返回,RBAC
|
||||
资源组合 `alerts + alerts/test`(create 动词)不在只读角色模板授权内,仅管理角色可用;
|
||||
设置页经自定义 FormKit 输入(Halo 2.25+ `formkit.inputs`,`@formkit/vue` 已被
|
||||
bundler kit 外部化为宿主共享模块)注册「发送测试告警」按钮,`ignore: true` 不落任何配置值。
|
||||
- 关于测试:`./gradlew test`(当前 219 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
|
||||
- 关于测试:`./gradlew test`(当前 244 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
|
||||
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、登录尝试用户名提取
|
||||
(表单/JSON/白名单/脱敏兜底/降级)、查询端点参数校验、导出 CSV
|
||||
(BOM/表头/转义/注入防护/分批取数)、操作描述与语义动作标注推导(与前端
|
||||
describeOperation / deriveAction 用例一一对应)、设置缓存与保留期清理、登录失败告警
|
||||
(阈值窗口推进/告警防轰炸/成功清零/设置归一/真实 HTTP 推送与静默降级/Webhook 结果化
|
||||
推送与测试端点反馈/测试负载结构);Console UI 以
|
||||
vitest 断言
|
||||
路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)+ 类型检查 + 构建通过为准
|
||||
(阈值窗口推进/告警防轰炸/成功清零/设置归一/Secret 地址解析 fail closed/真实 HTTP
|
||||
推送与静默降级/建连钉定证明/Webhook 结果化推送与测试端点反馈/测试负载结构)、
|
||||
出站地址守卫(结构校验/危险地址段枚举/IPv4 映射内嵌/日志主机名卫生);
|
||||
Console UI 以 vitest 断言路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)、
|
||||
生成客户端链路形态(不手写端点/不裸 fetch)、导出下载链路 + 类型检查 + 构建通过为准
|
||||
(技术方案 §7,MVP 不引入组件测试)。
|
||||
|
||||
## 开发
|
||||
@@ -173,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'
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -16,6 +16,11 @@ public record AlertSendResult(boolean success, String message) {
|
||||
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()
|
||||
|
||||
+43
-3
@@ -4,14 +4,21 @@ 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)。
|
||||
* 告警设置的短 TTL 缓存读取(与审计设置 {@code AuditSettingProvider} 同款模式,技术方案 D6),
|
||||
* 以及 Webhook 地址的 Secret 解析。
|
||||
*
|
||||
* <p>开关变更最多延迟 1 分钟生效——告警为旁路功能,可接受。读取失败或未配置时
|
||||
* 静默回退默认值(关闭告警),绝不影响登录与审计主流程。
|
||||
* <p>凭据安全(官方《敏感数据与出站请求》指南):Setting 只存 Secret 引用名,
|
||||
* 真实 Webhook 地址(可能内嵌 access_token)存于 Halo {@code Secret},经
|
||||
* {@link ReactiveExtensionClient} 按需读取;解析失败以错误信号报出(调用方决定
|
||||
* 降级方式:真实告警路径静默跳过,测试告警端点转为 400 提示),消息只含引用名
|
||||
* 与键名,绝不携带 Secret 内容。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -21,7 +28,11 @@ 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) {
|
||||
@@ -50,4 +61,33 @@ public class AlertSettingProvider {
|
||||
.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")));
|
||||
}
|
||||
}
|
||||
|
||||
+11
-15
@@ -3,10 +3,14 @@ package run.halo.operationaudit.alert;
|
||||
/**
|
||||
* 告警通知设置(存储于插件 ConfigMap 的 {@code alerts} 组,独立于审计设置组)。
|
||||
*
|
||||
* <p>取值经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值;
|
||||
* Webhook 地址非 http(s) 或为空时归一为 null(调用方静默跳过发送)。
|
||||
* <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 webhookUrl, Integer thresholdCount,
|
||||
public record AlertSettings(Boolean enabled, String webhookSecretName, Integer thresholdCount,
|
||||
Integer windowMinutes) {
|
||||
|
||||
/** ConfigMap 中的配置组名(settings.yaml 的告警通知表单组)。 */
|
||||
@@ -25,20 +29,12 @@ public record AlertSettings(Boolean enabled, String webhookUrl, Integer threshol
|
||||
return enabled != null && enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一 Webhook 地址:空白或非 http(s) 开头返回 null(不可用,调用方静默跳过),
|
||||
* 其余去除首尾空白后返回。
|
||||
*/
|
||||
public String webhookUrlOrDefault() {
|
||||
if (webhookUrl == null) {
|
||||
/** 归一 Secret 引用名:空白返回 null(未配置,调用方静默跳过发送)。 */
|
||||
public String webhookSecretNameOrDefault() {
|
||||
if (webhookSecretName == null || webhookSecretName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
var trimmed = webhookUrl.trim();
|
||||
var lower = trimmed.toLowerCase();
|
||||
if (trimmed.isEmpty() || !(lower.startsWith("http://") || lower.startsWith("https://"))) {
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
return webhookSecretName.trim();
|
||||
}
|
||||
|
||||
/** 触发阈值:小于 1 视为非法回退默认。 */
|
||||
|
||||
+27
-17
@@ -1,5 +1,7 @@
|
||||
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;
|
||||
@@ -13,6 +15,7 @@ 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 配置是否可用——以当前配置地址推送一条
|
||||
@@ -24,9 +27,12 @@ import run.halo.operationaudit.audit.AuditLog;
|
||||
* (auditlogs get/list)未授权该资源,仅超级管理员等管理角色可调用——与
|
||||
* "验证告警配置"的管理动作语义一致。
|
||||
*
|
||||
* <p>Webhook 地址未配置或非法(非 http(s))返回 400;推送失败不抛出——以 200 +
|
||||
* {@code success=false} 返回原因摘要(fire-and-forget 语义不变:真实告警路径仍异步
|
||||
* 不等待)。推送结果同时反馈到运行日志,任何异常不影响主流程。
|
||||
* <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
|
||||
@@ -46,33 +52,37 @@ public class AlertTestEndpoint implements CustomEndpoint {
|
||||
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.get()
|
||||
.flatMap(settings -> {
|
||||
var url = settings.webhookUrlOrDefault();
|
||||
if (url == null) {
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("message",
|
||||
"Webhook 地址未配置或非法(需以 http(s) 开头),请先保存设置"));
|
||||
}
|
||||
return sender.sendForResult(url, buildTestPayload(Instant.now()))
|
||||
return settingProvider.webhookUrl()
|
||||
.flatMap(url -> sender.sendForResult(url, buildTestPayload(Instant.now()))
|
||||
.doOnNext(result -> {
|
||||
if (result.success()) {
|
||||
log.info("Test alert sent to {}: {}", url, result.message());
|
||||
log.info("Test alert sent to {}: {}",
|
||||
OutboundUrlGuard.urlHost(url), result.message());
|
||||
} else {
|
||||
log.warn("Failed to send test alert to {}: {}", url,
|
||||
result.message());
|
||||
log.warn("Failed to send test alert to {}: {}",
|
||||
OutboundUrlGuard.urlHost(url), result.message());
|
||||
}
|
||||
})
|
||||
.flatMap(result -> ServerResponse.ok().bodyValue(Map.of(
|
||||
"success", result.success(),
|
||||
"message", 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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+40
-12
@@ -2,57 +2,85 @@ 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 响应、
|
||||
* URL 非法)仅记 warn 日志,不重试、不抛出,绝不影响登录与审计主流程。
|
||||
* 地址非法)仅记 warn 日志,不重试、不抛出,绝不影响登录与审计主流程。
|
||||
*
|
||||
* <p>负载为通用 JSON 结构(type/title/content/timestamp/data),不内置钉钉、企业微信、
|
||||
* 飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
|
||||
*
|
||||
* <p>功能评审 P0-2:新增 {@link #sendForResult(String, Map)}——返回推送结果
|
||||
* <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 WebClient webClient;
|
||||
private final OutboundUrlGuard guard;
|
||||
|
||||
public AlertWebhookSender() {
|
||||
this.webClient = WebClient.builder().build();
|
||||
}
|
||||
|
||||
/** 异步推送 JSON 负载;任何失败仅记 warn 日志,不影响调用方。 */
|
||||
/** 异步推送 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 {}: {}", url, result.message());
|
||||
log.warn("Failed to send alert webhook to {}: {}",
|
||||
OutboundUrlGuard.urlHost(url), result.message());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送 JSON 负载并返回结果(功能评审 P0-2):成功为接收方 2xx;超时、网络错误、
|
||||
* 非 2xx、URL 非法等任何失败均归一为失败结果,绝不抛出、绝不重试。
|
||||
* 非 2xx、地址校验失败等任何失败均归一为失败结果,绝不抛出、绝不重试。
|
||||
*
|
||||
* <p>返回的 Mono 永不为空、永不报错,超时上限与 fire-and-forget 路径一致
|
||||
* (10 秒)——测试告警端点同步等待该结果反馈到设置页。
|
||||
*/
|
||||
public Mono<AlertSendResult> sendForResult(String url, Map<String, Object> payload) {
|
||||
return Mono.defer(() -> webClient.post()
|
||||
.uri(url)
|
||||
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()
|
||||
|
||||
+40
-12
@@ -7,6 +7,7 @@ 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;
|
||||
|
||||
/**
|
||||
@@ -14,14 +15,17 @@ import run.halo.operationaudit.audit.RequestSnapshot;
|
||||
* 推送一次 JSON 告警。
|
||||
*
|
||||
* <p>触发点在捕获过滤器(POST {@code /login} 请求结束,见 {@code CaptureRule#isLoginAttempt}):
|
||||
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击
|
||||
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。
|
||||
* 登录成功立即清零计数,失败累计。成败由过滤器经 {@code LoginOutcome} 判定后传入——
|
||||
* 表单登录的成功与失败均为 302 重定向,以重定向目标是否含 {@code error} 参数区分,
|
||||
* 不能只看状态码。告警后重开窗口(同一攻击波次不会连环轰炸,下次告警需再次达到阈值);
|
||||
* 窗口过期同样重开,无失败时不累计。
|
||||
*
|
||||
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
|
||||
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
|
||||
*
|
||||
* <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关
|
||||
* 相互独立。任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
|
||||
* 相互独立;Webhook 地址凭据存于 Halo Secret(Setting 只存引用),解析失败静默跳过。
|
||||
* 任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -38,15 +42,17 @@ public class LoginFailureAlertService {
|
||||
int failureCount;
|
||||
|
||||
/**
|
||||
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。
|
||||
* 任何失败静默降级,不影响调用方。
|
||||
* 登录结果回调:仅处理 POST /login 请求(成功清零计数,失败累计告警)。
|
||||
* 成败由调用方(捕获过滤器)经 {@code LoginOutcome} 判定后传入,本服务不做
|
||||
* 状态码推断。任何失败静默降级,不影响调用方。
|
||||
*
|
||||
* @param success 登录是否成功(表单登录 302 重定向目标含 error 参数或
|
||||
* 响应 4xx/5xx 为失败;2xx 与成功重定向为成功)
|
||||
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
|
||||
* 提取失败为 null)
|
||||
*/
|
||||
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode,
|
||||
public void onLoginResult(RequestSnapshot snapshot, boolean success,
|
||||
String attemptedUsername) {
|
||||
var success = statusCode != null && statusCode >= 200 && statusCode < 300;
|
||||
settingProvider.get().subscribe(
|
||||
settings -> handle(settings, snapshot, success, attemptedUsername, Instant.now()),
|
||||
e -> log.warn("Failed to load alert settings, skip login alert for {}",
|
||||
@@ -54,8 +60,12 @@ public class LoginFailureAlertService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 阈值窗口判定与告警决策。now 由调用方传入(测试可控);发送在锁外执行。
|
||||
* handle 包内可见以便测试直接驱动窗口推进。
|
||||
* 告警入口:开关开启时先解析 Webhook 地址(凭据存于 Halo Secret,见
|
||||
* {@link AlertSettingProvider#webhookUrl(AlertSettings)}),未配置/读取失败则
|
||||
* 静默跳过(既不计数也不告警,与旧版"无地址不计数"语义一致);地址可用后进入
|
||||
* 阈值窗口判定。now 由调用方传入(测试可控)。
|
||||
*
|
||||
* <p>handle 包内可见以便测试直接驱动。
|
||||
*/
|
||||
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success,
|
||||
String attemptedUsername, Instant now) {
|
||||
@@ -63,10 +73,28 @@ public class LoginFailureAlertService {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
return;
|
||||
}
|
||||
var url = settings.webhookUrlOrDefault();
|
||||
if (url == null) {
|
||||
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) {
|
||||
|
||||
+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());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -103,8 +103,11 @@ public class AuditLogCsvExporter {
|
||||
private String toCsvLine(AuditLog log) {
|
||||
var spec = log.getSpec();
|
||||
var statusCode = spec.getStatusCode();
|
||||
// 结果语义与前端 isSuccessful 一致:2xx/3xx 成功,其余(含空)失败
|
||||
var success = statusCode != null && statusCode >= 200 && statusCode < 400;
|
||||
// 结果语义与前端一致:登录失败标注(HTTP 状态码可能为 200/302——失败回显页
|
||||
// 渲染/失败重定向)一律失败,其余 2xx/3xx 成功
|
||||
var failedLogin = OperationDescription.LOGIN_FAILURE_ACTION.equals(spec.getAction());
|
||||
var success = !failedLogin && statusCode != null && statusCode >= 200
|
||||
&& statusCode < 400;
|
||||
return String.join(",",
|
||||
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||
escape(spec.getUsername()),
|
||||
@@ -113,8 +116,8 @@ public class AuditLogCsvExporter {
|
||||
escape(spec.getResourceType()),
|
||||
escape(spec.getResourceName()),
|
||||
escape(spec.getPath()),
|
||||
escape(OperationDescription.describe(
|
||||
spec.getMethod(), spec.getResourceType(), spec.getPath())),
|
||||
// 优先落库语义动作(含登录失败标注),历史记录回退 method/path 现场推导
|
||||
escape(OperationDescription.describe(spec)),
|
||||
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
||||
escape(success ? "成功" : "失败"),
|
||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||
|
||||
+9
-3
@@ -56,16 +56,22 @@ final class AuditLogFilters {
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
||||
// 结果筛选:success = 2xx/3xx 且非登录失败标注,failure = 4xx/5xx 或登录失败
|
||||
// (登录失败的 HTTP 状态码可能为 200/302——失败回显页渲染/失败重定向,
|
||||
// 已由语义动作 login-failure 标注,见 LoginOutcome)
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
var loginFailure = Queries.equal("spec.action",
|
||||
OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
switch (resultFilter.trim().toLowerCase()) {
|
||||
case "success" -> {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
conditions.add(Queries.not(loginFailure));
|
||||
}
|
||||
case "failure" -> conditions.add(
|
||||
Queries.greaterThan("spec.statusCode", "400", true));
|
||||
case "failure" -> conditions.add(Queries.or(
|
||||
Queries.greaterThan("spec.statusCode", "400", true),
|
||||
loginFailure));
|
||||
default -> throw new IllegalArgumentException(
|
||||
"Invalid result, expect success or failure: " + resultFilter);
|
||||
}
|
||||
|
||||
+77
@@ -1,9 +1,16 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder;
|
||||
import static org.springdoc.core.fn.builders.content.Builder.contentBuilder;
|
||||
import static org.springdoc.core.fn.builders.parameter.Builder.parameterBuilder;
|
||||
import static org.springdoc.core.fn.builders.schema.Builder.schemaBuilder;
|
||||
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import java.util.List;
|
||||
import 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;
|
||||
@@ -13,6 +20,7 @@ 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.operationaudit.audit.AuditLog;
|
||||
@@ -35,6 +43,12 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
/** 每页大小上限,防止误用拖垮查询。 */
|
||||
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;
|
||||
|
||||
@@ -48,15 +62,78 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
return org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route()
|
||||
.GET("auditlogs/-/query", this::query, builder -> builder
|
||||
.operationId("ListAuditLogs")
|
||||
.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();
|
||||
}
|
||||
|
||||
+17
-8
@@ -38,9 +38,13 @@ public class AuditRecorder {
|
||||
*
|
||||
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
|
||||
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
|
||||
* @param loginFailed 登录失败标注:POST /login 结果失败(表单登录失败为
|
||||
* 302 重定向且目标含 error 参数)或失败回显
|
||||
* (GET /login?error=...,HTTP 200),语义动作标注
|
||||
* login-failure;其余请求为 false
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername) {
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
@@ -48,19 +52,20 @@ public class AuditRecorder {
|
||||
snapshot.getMethod(), snapshot.getFullPath());
|
||||
return;
|
||||
}
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||
},
|
||||
e -> {
|
||||
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
write(snapshot, capture, statusCode, username, attemptedUsername, loginFailed);
|
||||
});
|
||||
}
|
||||
|
||||
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername) {
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
try {
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername);
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername,
|
||||
loginFailed);
|
||||
client.create(auditLog)
|
||||
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e));
|
||||
@@ -147,7 +152,7 @@ public class AuditRecorder {
|
||||
}
|
||||
|
||||
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username, String attemptedUsername) {
|
||||
String username, String attemptedUsername, boolean loginFailed) {
|
||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||
|
||||
var spec = new AuditLogSpec();
|
||||
@@ -156,11 +161,15 @@ public class AuditRecorder {
|
||||
spec.setAttemptedUsername(attemptedUsername);
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选
|
||||
spec.setAction(OperationDescription.actionOf(
|
||||
// 语义动作标注(产品设计 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());
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+18
-10
@@ -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)。
|
||||
@@ -25,26 +30,29 @@ public final class CaptureRule {
|
||||
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「告警通知」):
|
||||
* 登录失败告警的触发条件——2xx 为登录成功,其余为失败;
|
||||
* 登录页 GET 与登出不算。
|
||||
* 登录失败告警的触发条件——结果由 {@link LoginOutcome} 判定(表单登录成败均为
|
||||
* 302 重定向,不能只看状态码);登录页 GET 与登出不算。
|
||||
*/
|
||||
public static boolean isLoginAttempt(String path, String method) {
|
||||
return "POST".equals(method) && LOGIN_ENDPOINT.equals(path);
|
||||
|
||||
+53
-46
@@ -3,8 +3,8 @@ package run.halo.operationaudit.audit;
|
||||
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
@@ -20,20 +20,27 @@ import run.halo.app.extension.Unstructured;
|
||||
|
||||
/**
|
||||
* 登录尝试用户名提取(功能评审 P0-1):POST {@code /login} 的请求体为表单形态、
|
||||
* 登录端点非注册模型,与 {@link ChangeCaptureManager} 的 JSON 缓存逻辑分开,
|
||||
* 为登录端点单独补一条请求体读取:缓存请求体(下游可重复读)并提取尝试的用户名。
|
||||
* 登录端点非注册模型,为登录端点单独提取尝试的用户名。
|
||||
*
|
||||
* <p>提取规则(安全边界):
|
||||
* <ul>
|
||||
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
|
||||
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
|
||||
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
|
||||
* <li>请求体经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存,
|
||||
* 与字段级变更捕获同款边界(分块传输/超限一律不读,仅不提取用户名)。</li>
|
||||
* <li>超长用户名({@value #MAX_USERNAME_LENGTH} 字符以上)视为扫描载荷,不提取。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>登录端点同时接受表单({@code application/x-www-form-urlencoded})与 JSON 请求体,
|
||||
* 两种形态均支持提取;不支持的形态与任何解析异常均静默降级为不提取(返回 null),
|
||||
* <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},与审计开关、
|
||||
* 告警开关均无关(两种消费方各自决定是否使用)。
|
||||
*/
|
||||
@@ -41,23 +48,39 @@ import run.halo.app.extension.Unstructured;
|
||||
@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。
|
||||
* 为登录请求提取尝试的用户名。返回交换对象供后续链路继续处理;返回的 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)或超限:不读请求体,避免中断流式请求
|
||||
@@ -68,7 +91,7 @@ public class LoginAttemptCapture {
|
||||
var bytes = new byte[joined.readableByteCount()];
|
||||
joined.read(bytes);
|
||||
DataBufferUtils.release(joined);
|
||||
attempt.setAttemptedUsername(extract(bytes, contentType));
|
||||
attempt.setAttemptedUsername(extractJson(bytes));
|
||||
return decorate(exchange, bytes);
|
||||
})
|
||||
.defaultIfEmpty(exchange)
|
||||
@@ -83,16 +106,16 @@ public class LoginAttemptCapture {
|
||||
if (contentType == null) {
|
||||
return false;
|
||||
}
|
||||
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
|| ChangeCaptureManager.isJson(contentType);
|
||||
return isForm(contentType) || ChangeCaptureManager.isJson(contentType);
|
||||
}
|
||||
|
||||
/** 按内容类型分发提取;任何异常均静默返回 null,绝不抛出。 */
|
||||
private static String extract(byte[] bytes, MediaType contentType) {
|
||||
try {
|
||||
if (contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
|
||||
return usernameOfForm(new String(bytes, StandardCharsets.UTF_8));
|
||||
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) {
|
||||
// 解析异常静默:不提取,不影响登录主流程
|
||||
@@ -101,28 +124,18 @@ public class LoginAttemptCapture {
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单体提取:仅取白名单字段的值(同名多值取最后一个),URL 编码解码失败回退原值。
|
||||
* 表单字段提取:仅取白名单字段的值(同名多值取最后一个,与逐字段解析语义一致);
|
||||
* 超长值视为扫描载荷不提取。
|
||||
*/
|
||||
static String usernameOfForm(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
static String usernameOfFormValues(List<String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String found = null;
|
||||
for (var pair : body.split("&")) {
|
||||
var idx = pair.indexOf('=');
|
||||
var name = safeDecode(idx < 0 ? pair : pair.substring(0, idx));
|
||||
if (!USERNAME_FIELDS.contains(name)) {
|
||||
continue;
|
||||
}
|
||||
var value = safeDecode(idx < 0 ? "" : pair.substring(idx + 1));
|
||||
found = maskIfSensitive(name, value);
|
||||
}
|
||||
return StringUtils.hasText(found) ? found : null;
|
||||
} catch (Exception e) {
|
||||
// 表单解析异常静默:不提取,不影响登录主流程
|
||||
var found = values.get(values.size() - 1);
|
||||
if (!StringUtils.hasText(found) || found.length() > MAX_USERNAME_LENGTH) {
|
||||
return null;
|
||||
}
|
||||
return maskIfSensitive(USERNAME_FIELD, found);
|
||||
}
|
||||
|
||||
/** JSON 体提取:仅取顶层白名单字段的标量值。 */
|
||||
@@ -135,7 +148,10 @@ public class LoginAttemptCapture {
|
||||
return null;
|
||||
}
|
||||
var text = value.asText();
|
||||
return StringUtils.hasText(text) ? maskIfSensitive(USERNAME_FIELD, text) : null;
|
||||
if (!StringUtils.hasText(text) || text.length() > MAX_USERNAME_LENGTH) {
|
||||
return null;
|
||||
}
|
||||
return maskIfSensitive(USERNAME_FIELD, text);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,16 +163,7 @@ public class LoginAttemptCapture {
|
||||
return ChangeDiffEngine.isSensitiveField(fieldName) ? REDACTED_VALUE : value;
|
||||
}
|
||||
|
||||
/** URL 编码解码失败(如裸 %)回退原值,尽力提取、绝不抛出。 */
|
||||
private static String safeDecode(String value) {
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游登录处理可正常读取。 */
|
||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游可重复读。 */
|
||||
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
|
||||
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
||||
@Override
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+20
-48
@@ -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;
|
||||
@@ -13,13 +12,15 @@ import org.springframework.web.server.WebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.context.ContextView;
|
||||
import run.halo.app.security.AfterSecurityWebFilter;
|
||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
|
||||
/**
|
||||
* 审计捕获过滤器(技术方案 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}。
|
||||
@@ -29,15 +30,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
* <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON
|
||||
* 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。
|
||||
*
|
||||
* <p>系统内部变更(产品设计 V2):所有写方法请求(含未被捕获规则命中的 {@code /api/**}
|
||||
* 核心模型与登录端点)均经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
||||
* <p>系统内部变更(产品设计 V2):未被捕获规则命中的写方法请求({@code /api/**}
|
||||
* 核心模型)同样经 {@link HttpWriteMarker} 登记目标资源与活动时间,供
|
||||
* {@link InternalChangeWatcher} 将请求期触发的资源变更归属到该请求,避免重复/误记录。
|
||||
*
|
||||
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
|
||||
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
|
||||
* Webhook;与审计开关相互独立。尝试的用户名(功能评审 P0-1)由
|
||||
* {@link LoginAttemptCapture} 在请求期从登录请求体白名单提取,随记录落库
|
||||
* {@code spec.attemptedUsername} 并进入告警负载。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -49,8 +44,6 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
private final AuditRecorder recorder;
|
||||
private final ChangeCaptureManager captureManager;
|
||||
private final HttpWriteMarker writeMarker;
|
||||
private final LoginAttemptCapture loginAttemptCapture;
|
||||
private final LoginFailureAlertService loginFailureAlertService;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
@@ -58,7 +51,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
var path = request.getPath().value();
|
||||
var method = request.getMethod().name();
|
||||
if (!shouldCapture(path, method)) {
|
||||
// 未命中捕获规则的写方法请求(/api/** 核心模型、登录端点等)不记录,
|
||||
// 未命中捕获规则的写方法请求(/api/** 核心模型等)不记录,
|
||||
// 但仍登记标记:请求期触发的资源变更由该请求归属
|
||||
if (CaptureRule.WRITE_METHODS.contains(method)) {
|
||||
writeMarker.onRequestStart(request);
|
||||
@@ -70,29 +63,17 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
writeMarker.onRequestStart(request);
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
var capture = new ChangeCapture();
|
||||
var loginAttempt = new LoginAttempt();
|
||||
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
|
||||
// 其余请求原样透传
|
||||
var bodyPrepared = CaptureRule.isLoginAttempt(path, method)
|
||||
? loginAttemptCapture.prepare(exchange, loginAttempt)
|
||||
: Mono.just(exchange);
|
||||
return bodyPrepared
|
||||
.flatMap(prepared -> captureManager.prepare(prepared, snapshot, capture))
|
||||
.flatMap(prepared -> chain.filter(prepared))
|
||||
return captureManager.prepare(exchange, snapshot, capture)
|
||||
.flatMap(chain::filter)
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> {
|
||||
writeMarker.onRequestComplete(request);
|
||||
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
|
||||
// 2xx 清零计数、其余累计,独立于下方审计记录决策
|
||||
if (CaptureRule.isLoginAttempt(path, method)) {
|
||||
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange),
|
||||
loginAttempt.getAttemptedUsername());
|
||||
}
|
||||
operatorOf(ctx, path).subscribe(
|
||||
var statusCode = statusOf(exchange);
|
||||
operatorOf(ctx).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
recorder.record(snapshot, capture, statusOf(exchange), username,
|
||||
loginAttempt.getAttemptedUsername());
|
||||
if (shouldRecord(username)) {
|
||||
recorder.record(snapshot, capture, statusCode, username,
|
||||
null, false);
|
||||
}
|
||||
},
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
|
||||
@@ -102,10 +83,10 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
/**
|
||||
* 从订阅上下文解析操作者用户名。
|
||||
*
|
||||
* <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))
|
||||
@@ -116,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);
|
||||
}
|
||||
@@ -131,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());
|
||||
}
|
||||
}
|
||||
|
||||
+21
@@ -64,9 +64,17 @@ final class OperationDescription {
|
||||
Map.entry("password", "password"),
|
||||
Map.entry("resetpassword", "resetpassword"));
|
||||
|
||||
/**
|
||||
* 登录失败语义动作键:POST {@code /login} 失败(重定向目标含 error 参数或 4xx/5xx)
|
||||
* 与登录失败回显(GET {@code /login?error=...},HTTP 200)落库标注,供列表红色
|
||||
* 标记、按语义动作筛选与结果筛选(前端 {@code audit.ts} 同步此键)。
|
||||
*/
|
||||
static final String LOGIN_FAILURE_ACTION = "login-failure";
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼接资源名)。 */
|
||||
private static final Map<String, String> ACTION_PHRASES = Map.ofEntries(
|
||||
Map.entry("login", "登录"),
|
||||
Map.entry(LOGIN_FAILURE_ACTION, "登录失败"),
|
||||
Map.entry("logout", "登出"),
|
||||
Map.entry("auth", "认证操作"),
|
||||
Map.entry("password", "修改密码"),
|
||||
@@ -149,6 +157,19 @@ final class OperationDescription {
|
||||
return method + resourceLabel(resourceType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 由落库 spec 推导操作中文描述(导出用):优先落库的语义动作标注(含登录失败
|
||||
* 标注——回显页 HTTP 200 无法由路径重新推导出失败),无标注或未识别时回退为
|
||||
* method/path 现场推导(与前端 {@code describeOperation} 一致)。
|
||||
*/
|
||||
static String describe(AuditLogSpec spec) {
|
||||
var phrase = describeAction(spec.getAction(), spec.getResourceType());
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
return describe(spec.getMethod(), spec.getResourceType(), spec.getPath());
|
||||
}
|
||||
|
||||
private static String resourceLabel(String resourceType) {
|
||||
return RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
|
||||
}
|
||||
|
||||
@@ -37,11 +37,14 @@ spec:
|
||||
name: enabled
|
||||
value: false
|
||||
help: 统计窗口内登录失败达到触发阈值时向 Webhook 地址推送 JSON 告警(独立于审计开关,默认关闭)
|
||||
- $formkit: text
|
||||
- $formkit: secret
|
||||
label: Webhook 地址
|
||||
name: webhookUrl
|
||||
value: ""
|
||||
help: 接收告警的 http(s) 地址,告警以 JSON POST 异步推送(失败不重试,仅记日志)
|
||||
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: 测试告警
|
||||
|
||||
@@ -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"
|
||||
|
||||
+75
-6
@@ -1,6 +1,7 @@
|
||||
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;
|
||||
@@ -8,18 +9,34 @@ 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 缓存测试(与审计设置同款模式):命中缓存、失败/缺省回退默认(告警关闭)。
|
||||
* 告警设置 TTL 缓存测试(与审计设置同款模式):命中缓存、失败/缺省回退默认(告警关闭);
|
||||
* Webhook 地址 Secret 解析:未配置引用 / Secret 不存在 / 缺字段 / 空白值均 fail closed
|
||||
* (错误信号,绝不发送),字段值去除首尾空白。
|
||||
*/
|
||||
class AlertSettingProviderTest {
|
||||
|
||||
private final ReactiveSettingFetcher fetcher = mock(ReactiveSettingFetcher.class);
|
||||
private final AlertSettingProvider provider = new AlertSettingProvider(fetcher);
|
||||
private final ReactiveExtensionClient client = mock(ReactiveExtensionClient.class);
|
||||
private final AlertSettingProvider provider = new AlertSettingProvider(fetcher, client);
|
||||
|
||||
private static AlertSettings settings(String secretName) {
|
||||
return new AlertSettings(true, secretName, 5, 5);
|
||||
}
|
||||
|
||||
private static Secret secret(String url) {
|
||||
var secret = new Secret();
|
||||
secret.setStringData(Map.of(AlertSettingProvider.WEBHOOK_URL_FIELD, url));
|
||||
return secret;
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCacheWithinTtl() {
|
||||
@@ -27,15 +44,15 @@ class AlertSettingProviderTest {
|
||||
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
|
||||
.thenAnswer(inv -> {
|
||||
fetchCount.incrementAndGet();
|
||||
return Mono.just(new AlertSettings(true, "https://hooks.example.com/x", 3, 2));
|
||||
return Mono.just(new AlertSettings(true, "webhook-secret", 3, 2));
|
||||
});
|
||||
|
||||
var first = provider.get().block();
|
||||
var second = provider.get().block();
|
||||
|
||||
assertThat(first).extracting(AlertSettings::enabled, AlertSettings::webhookUrl,
|
||||
assertThat(first).extracting(AlertSettings::enabled, AlertSettings::webhookSecretName,
|
||||
AlertSettings::thresholdCount, AlertSettings::windowMinutes)
|
||||
.containsExactly(true, "https://hooks.example.com/x", 3, 2);
|
||||
.containsExactly(true, "webhook-secret", 3, 2);
|
||||
assertThat(second).isSameAs(first);
|
||||
assertThat(fetchCount.get()).isEqualTo(1);
|
||||
}
|
||||
@@ -49,7 +66,7 @@ class AlertSettingProviderTest {
|
||||
|
||||
assertThat(settings).isEqualTo(AlertSettings.defaults());
|
||||
assertThat(settings.enabledOrDefault()).isFalse();
|
||||
assertThat(settings.webhookUrlOrDefault()).isNull();
|
||||
assertThat(settings.webhookSecretNameOrDefault()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,4 +90,56 @@ class AlertSettingProviderTest {
|
||||
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("缺少");
|
||||
}
|
||||
}
|
||||
|
||||
+19
-23
@@ -5,7 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 告警设置归一测试:缺省/非法值回退默认,Webhook 地址仅接受 http(s)。
|
||||
* 告警设置归一测试:缺省/非法值回退默认;凭据安全要求下本记录只持有 Secret 引用名
|
||||
* (真实 Webhook 地址由 AlertSettingProvider 从 Secret 解析)。
|
||||
*/
|
||||
class AlertSettingsTest {
|
||||
|
||||
@@ -14,33 +15,25 @@ class AlertSettingsTest {
|
||||
var settings = AlertSettings.defaults();
|
||||
|
||||
assertThat(settings.enabledOrDefault()).isFalse();
|
||||
assertThat(settings.webhookUrlOrDefault()).isNull();
|
||||
assertThat(settings.webhookSecretNameOrDefault()).isNull();
|
||||
assertThat(settings.thresholdCountOrDefault()).isEqualTo(5);
|
||||
assertThat(settings.windowMinutesOrDefault()).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNormalizeWebhookUrl() {
|
||||
assertThat(new AlertSettings(true, " https://hooks.example.com/x ", null, null)
|
||||
.webhookUrlOrDefault()).isEqualTo("https://hooks.example.com/x");
|
||||
assertThat(new AlertSettings(true, "http://127.0.0.1:9000/hook", null, null)
|
||||
.webhookUrlOrDefault()).isEqualTo("http://127.0.0.1:9000/hook");
|
||||
// 大写 scheme 同样接受(URL scheme 不区分大小写)
|
||||
assertThat(new AlertSettings(true, "HTTPS://hooks.example.com/x", null, null)
|
||||
.webhookUrlOrDefault()).isEqualTo("HTTPS://hooks.example.com/x");
|
||||
void shouldNormalizeSecretName() {
|
||||
assertThat(new AlertSettings(true, " operation-audit-webhook ", null, null)
|
||||
.webhookSecretNameOrDefault()).isEqualTo("operation-audit-webhook");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectNonHttpWebhookUrl() {
|
||||
assertThat(new AlertSettings(true, null, null, null).webhookUrlOrDefault()).isNull();
|
||||
assertThat(new AlertSettings(true, "", null, null).webhookUrlOrDefault()).isNull();
|
||||
assertThat(new AlertSettings(true, " ", null, null).webhookUrlOrDefault()).isNull();
|
||||
assertThat(new AlertSettings(true, "ftp://hooks.example.com", null, null)
|
||||
.webhookUrlOrDefault()).isNull();
|
||||
assertThat(new AlertSettings(true, "hooks.example.com/x", null, null)
|
||||
.webhookUrlOrDefault()).isNull();
|
||||
assertThat(new AlertSettings(true, "javascript:alert(1)", null, null)
|
||||
.webhookUrlOrDefault()).isNull();
|
||||
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
|
||||
@@ -67,8 +60,11 @@ class AlertSettingsTest {
|
||||
|
||||
@Test
|
||||
void shouldRespectExplicitEnabledFlag() {
|
||||
assertThat(new AlertSettings(null, "https://x", null, null).enabledOrDefault()).isFalse();
|
||||
assertThat(new AlertSettings(false, "https://x", null, null).enabledOrDefault()).isFalse();
|
||||
assertThat(new AlertSettings(true, "https://x", null, null).enabledOrDefault()).isTrue();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
+16
-13
@@ -16,12 +16,14 @@ import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 告警测试端点测试(功能评审 P0-2):Webhook 未配置/非法返回 400、推送结果同步返回
|
||||
* (200 + success/message)、测试负载结构(type=test 与 login-failure 区分)。
|
||||
* 告警测试端点测试(功能评审 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;
|
||||
@@ -39,28 +41,29 @@ class AlertTestEndpointTest {
|
||||
webClient = WebTestClient.bindToRouterFunction(mounted).build();
|
||||
}
|
||||
|
||||
private static AlertSettings settings(String webhookUrl) {
|
||||
return new AlertSettings(true, webhookUrl, 5, 5);
|
||||
private static AlertSettings settings(String secretName) {
|
||||
return new AlertSettings(true, secretName, 5, 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectWhenWebhookUrlMissing() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings(" ")));
|
||||
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 地址未配置或非法(需以 http(s) 开头),请先保存设置");
|
||||
"Webhook 地址未配置(需在设置中选择或创建 Secret),请先保存设置");
|
||||
|
||||
verify(sender, org.mockito.Mockito.never()).sendForResult(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnSuccessResult() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
|
||||
when(sender.sendForResult(eq("https://hooks.example.com/x"), any()))
|
||||
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)
|
||||
@@ -74,8 +77,8 @@ class AlertTestEndpointTest {
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void shouldReturnFailureResultWithoutError() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
|
||||
when(sender.sendForResult(eq("https://hooks.example.com/x"), any()))
|
||||
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)
|
||||
@@ -89,7 +92,7 @@ class AlertTestEndpointTest {
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void shouldPostTestTypePayload() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
|
||||
when(settingProvider.webhookUrl()).thenReturn(Mono.just(WEBHOOK_URL));
|
||||
when(sender.sendForResult(any(), any()))
|
||||
.thenReturn(Mono.just(AlertSendResult.ok(204)));
|
||||
|
||||
@@ -99,7 +102,7 @@ class AlertTestEndpointTest {
|
||||
var urlCaptor = ArgumentCaptor.forClass(String.class);
|
||||
var payloadCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(sender).sendForResult(urlCaptor.capture(), payloadCaptor.capture());
|
||||
assertThat(urlCaptor.getValue()).isEqualTo("https://hooks.example.com/x");
|
||||
assertThat(urlCaptor.getValue()).isEqualTo(WEBHOOK_URL);
|
||||
var payload = payloadCaptor.getValue();
|
||||
assertThat(payload.get("type")).isEqualTo(AlertTestEndpoint.TEST_TYPE);
|
||||
assertThat((String) payload.get("title")).contains("测试消息");
|
||||
|
||||
+89
-56
@@ -7,23 +7,32 @@ 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):
|
||||
* JSON POST 负载可达、非 2xx / 连接失败 / URL 非法均静默降级不抛出;
|
||||
*
|
||||
* <p>HTTP 机制经 {@code sendToTarget} 直接驱动(目标已完成校验、地址钉定)——
|
||||
* JSON POST 负载可达、非 2xx / 连接失败 / 校验失败均归一为结果或静默降级不抛出;
|
||||
* 结果化推送(功能评审 P0-2)返回送达与否 + 原因摘要,同样永不抛出。
|
||||
*
|
||||
* <p>出站安全链路经 {@code sendForResult} 驱动(真实路径):回环/内网等受限地址
|
||||
* 在 SSRF 校验阶段即拒绝(不建连),建连钉定校验地址(DNS rebinding 防护——
|
||||
* 主机名 localhost + 钉定 127.0.0.2 的用例证明建连走钉定地址而非 DNS 结果)。
|
||||
*/
|
||||
class AlertWebhookSenderTest {
|
||||
|
||||
private HttpServer server;
|
||||
|
||||
private final AlertWebhookSender sender = new AlertWebhookSender();
|
||||
private final AlertWebhookSender sender = new AlertWebhookSender(new OutboundUrlGuard());
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
@@ -32,10 +41,10 @@ class AlertWebhookSenderTest {
|
||||
}
|
||||
}
|
||||
|
||||
private HttpServer startServer(int status, AtomicReference<byte[]> body,
|
||||
/** 在指定回环地址上启动测试 HTTP 服务,返回实际端口。 */
|
||||
private int startServer(InetAddress bind, int status, AtomicReference<byte[]> body,
|
||||
AtomicReference<String> contentType, CountDownLatch received) throws Exception {
|
||||
var httpServer = HttpServer.create(
|
||||
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||
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"));
|
||||
@@ -44,18 +53,30 @@ class AlertWebhookSenderTest {
|
||||
received.countDown();
|
||||
});
|
||||
httpServer.start();
|
||||
return httpServer;
|
||||
server = httpServer;
|
||||
return httpServer.getAddress().getPort();
|
||||
}
|
||||
|
||||
/** 构造已校验钉定目标(等价守卫对公网地址放行后的产物)。 */
|
||||
private static OutboundUrlGuard.ValidatedTarget pinnedTarget(String url)
|
||||
throws Exception {
|
||||
var uri = new URI(url);
|
||||
return new OutboundUrlGuard.ValidatedTarget(uri, uri.getPort(),
|
||||
InetAddress.getByName(uri.getHost()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPostJsonPayload() throws Exception {
|
||||
void shouldPostJsonPayloadViaPinnedTarget() throws Exception {
|
||||
var body = new AtomicReference<byte[]>();
|
||||
var contentType = new AtomicReference<String>();
|
||||
var received = new CountDownLatch(1);
|
||||
server = startServer(200, body, contentType, received);
|
||||
var port = startServer(InetAddress.getLoopbackAddress(), 200, body, contentType,
|
||||
received);
|
||||
var url = "http://127.0.0.1:" + port + "/hook";
|
||||
|
||||
sender.send("http://127.0.0.1:" + server.getAddress().getPort() + "/hook",
|
||||
Map.of("title", "操作审计告警:登录失败", "failures", 3));
|
||||
// fire-and-forget 语义:订阅即异步执行,不等待结果
|
||||
sender.sendToTarget(pinnedTarget(url),
|
||||
Map.of("title", "操作审计告警:登录失败", "failures", 3)).subscribe();
|
||||
|
||||
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
@@ -66,44 +87,19 @@ class AlertWebhookSenderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowOnNon2xxResponse() throws Exception {
|
||||
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);
|
||||
server = startServer(500, body, contentType, received);
|
||||
var port = startServer(pinned, 200, body, contentType, received);
|
||||
// 目标地址与 URL 主机名刻意不同:模拟"校验时解析结果 ≠ 重绑定后的 DNS 结果"
|
||||
var target = new OutboundUrlGuard.ValidatedTarget(
|
||||
new URI("http://localhost:" + port + "/hook"), port, pinned);
|
||||
|
||||
assertThatCode(() -> sender.send(
|
||||
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of()))
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
// 500 响应同样送达(接收方先收到请求才返回 500),随后静默降级为日志
|
||||
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenTargetUnreachable() {
|
||||
// 端口 1 保留端口,连接立即被拒:异步失败仅记日志
|
||||
assertThatCode(() -> sender.send("http://127.0.0.1:1/hook", Map.of()))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenUrlMalformed() {
|
||||
assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException();
|
||||
assertThatCode(() -> sender.send(null, Map.of())).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
// ===== 结果化推送(功能评审 P0-2:测试告警端点同步反馈到设置页) =====
|
||||
|
||||
@Test
|
||||
void shouldReturnSuccessResultOn2xx() throws Exception {
|
||||
var body = new AtomicReference<byte[]>();
|
||||
var contentType = new AtomicReference<String>();
|
||||
var received = new CountDownLatch(1);
|
||||
server = startServer(200, body, contentType, received);
|
||||
|
||||
var result = sender.sendForResult(
|
||||
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of("k", "v"))
|
||||
var result = sender.sendToTarget(target, Map.of("pin", true))
|
||||
.block(java.time.Duration.ofSeconds(10));
|
||||
|
||||
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
@@ -113,26 +109,37 @@ class AlertWebhookSenderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnFailureResultOnNon2xx() throws Exception {
|
||||
void shouldNotThrowOnNon2xxResponse() throws Exception {
|
||||
var body = new AtomicReference<byte[]>();
|
||||
var contentType = new AtomicReference<String>();
|
||||
var received = new CountDownLatch(1);
|
||||
server = startServer(503, body, contentType, received);
|
||||
var port = startServer(InetAddress.getLoopbackAddress(), 500, body, contentType,
|
||||
received);
|
||||
var url = "http://127.0.0.1:" + port + "/hook";
|
||||
|
||||
var result = sender.sendForResult(
|
||||
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of())
|
||||
.block(java.time.Duration.ofSeconds(10));
|
||||
assertThatCode(() -> sender.sendToTarget(pinnedTarget(url), Map.of()).subscribe())
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
// 500 响应同样送达(接收方先收到请求才返回 500),随后静默降级为日志
|
||||
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(result).isNotNull();
|
||||
StepVerifier.create(sender.sendToTarget(pinnedTarget(url), Map.of()))
|
||||
.assertNext(result -> {
|
||||
assertThat(result.success()).isFalse();
|
||||
assertThat(result.message()).isNotBlank();
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnFailureResultWhenTargetUnreachable() {
|
||||
// 端口 1 保留端口,连接立即被拒:归一为失败结果而非错误信号
|
||||
var result = sender.sendForResult("http://127.0.0.1:1/hook", Map.of())
|
||||
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();
|
||||
@@ -140,8 +147,31 @@ class AlertWebhookSenderTest {
|
||||
assertThat(result.message()).isNotBlank();
|
||||
}
|
||||
|
||||
// ===== 出站安全链路(sendForResult:真实路径,SSRF 校验前置) =====
|
||||
|
||||
@Test
|
||||
void shouldReturnFailureResultWhenUrlMalformed() {
|
||||
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(
|
||||
@@ -149,12 +179,15 @@ class AlertWebhookSenderTest {
|
||||
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:1/hook", Map.of()))
|
||||
// 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();
|
||||
}
|
||||
|
||||
+34
-20
@@ -25,10 +25,14 @@ 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;
|
||||
@@ -40,11 +44,14 @@ class LoginFailureAlertServiceTest {
|
||||
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_URL, threshold, windowMinutes)));
|
||||
new AlertSettings(true, WEBHOOK_REF, threshold, windowMinutes)));
|
||||
}
|
||||
|
||||
private static RequestSnapshot loginSnapshot() {
|
||||
@@ -160,22 +167,24 @@ class LoginFailureAlertServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreat3xxAsFailure() {
|
||||
void shouldCountFailureFromCallbackFlag() {
|
||||
// 状态码→成败的解释已上移到 LoginOutcome(表单登录成败均为 302 重定向),
|
||||
// 服务只按回调布尔计数:false 计失败
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 302, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreat2xxAsSuccess() {
|
||||
void shouldResetCounterOnSuccessCallback() {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 200, null);
|
||||
service.onLoginResult(snapshot, 204, null);
|
||||
service.onLoginResult(snapshot, true, null);
|
||||
service.onLoginResult(snapshot, true, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
}
|
||||
@@ -185,7 +194,7 @@ class LoginFailureAlertServiceTest {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
|
||||
}
|
||||
@@ -196,7 +205,7 @@ class LoginFailureAlertServiceTest {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 401, "admin");
|
||||
service.onLoginResult(snapshot, false, "admin");
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((String) payload.get("content")).contains("尝试的账号:admin");
|
||||
@@ -209,7 +218,7 @@ class LoginFailureAlertServiceTest {
|
||||
enableAlerts(1, 5);
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((String) payload.get("content")).doesNotContain("尝试的账号");
|
||||
@@ -220,26 +229,31 @@ class LoginFailureAlertServiceTest {
|
||||
@Test
|
||||
void shouldSkipWhenAlertDisabled() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(
|
||||
new AlertSettings(false, WEBHOOK_URL, 1, 5)));
|
||||
new AlertSettings(false, WEBHOOK_REF, 1, 5)));
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
assertThat(service.failureCount).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipWhenWebhookUrlMissing() {
|
||||
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();
|
||||
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
// 地址解析失败(未配置 Secret / Secret 缺字段):静默跳过,不计数也不告警
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
assertThat(service.failureCount).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -247,7 +261,7 @@ class LoginFailureAlertServiceTest {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
var snapshot = loginSnapshot();
|
||||
|
||||
assertThatCode(() -> service.onLoginResult(snapshot, 401, null))
|
||||
assertThatCode(() -> service.onLoginResult(snapshot, false, null))
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
verify(sender, never()).send(any(), any());
|
||||
@@ -259,7 +273,7 @@ class LoginFailureAlertServiceTest {
|
||||
doThrow(new IllegalStateException("webhook broken"))
|
||||
.when(sender).send(any(), any());
|
||||
|
||||
assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401, null))
|
||||
assertThatCode(() -> service.onLoginResult(loginSnapshot(), false, null))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@@ -270,15 +284,15 @@ class LoginFailureAlertServiceTest {
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
service.onLoginResult(snapshot, 401, null);
|
||||
service.onLoginResult(snapshot, false, null);
|
||||
|
||||
var payload = capturedPayload();
|
||||
assertThat((String) payload.get("content")).doesNotContain("()");
|
||||
assertThat((Map<String, Object>) payload.get("data")).containsEntry("userAgent", null);
|
||||
}
|
||||
|
||||
/** 直接驱动 handle 用的告警设置(handle 不读设置缓存,参数须与断言一致)。 */
|
||||
/** 直接驱动 handle 用的告警设置(handle 只读开关/阈值,地址走 provider 解析)。 */
|
||||
private AlertSettings settings(int thresholdCount, int windowMinutes) {
|
||||
return new AlertSettings(true, WEBHOOK_URL, thresholdCount, 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>");
|
||||
}
|
||||
}
|
||||
+26
@@ -114,6 +114,32 @@ class AuditExportEndpointTest {
|
||||
+ ",unknown,admin,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportLoginFailureRowsAsFailureDespiteHttp2xx3xx() {
|
||||
// 登录失败标注(语义动作 login-failure):表单登录失败重定向(302)与失败回显页
|
||||
// (GET /login?error=...,200)状态码落在 2xx/3xx,结果列仍应为「失败」;
|
||||
// 描述列优先落库语义动作(登录失败),而非按路径重新推导出的「登录」
|
||||
var time = Instant.parse("2026-11-01T00:00:00Z");
|
||||
var failedFormLogin = auditLog("auditlog-1", time, "unknown", "admin", "POST", "auth",
|
||||
null, "/login", 302, "119.53.161.18", "Mozilla/5.0");
|
||||
failedFormLogin.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
var failureEcho = auditLog("auditlog-2", time.plusSeconds(60), "unknown", null, "GET",
|
||||
"auth", null, "/login?error=invalid-credential&method=local", 200, "119.53.161.18",
|
||||
"Mozilla/5.0");
|
||||
failureEcho.getSpec().setAction(OperationDescription.LOGIN_FAILURE_ACTION);
|
||||
stubSinglePage(List.of(failedFormLogin, failureEcho));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines).hasSize(3);
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",unknown,admin,POST,auth,,/login,登录失败,,失败,302,119.53.161.18,Mozilla/5.0");
|
||||
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||
+ ",unknown,,GET,auth,,/login?error=invalid-credential&method=local"
|
||||
+ ",登录失败,,失败,200,119.53.161.18,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportChangesColumnWhenRecordHasChanges() {
|
||||
var time = Instant.parse("2026-11-04T00:00:00Z");
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+22
-2
@@ -106,10 +106,30 @@ class AuditQueryEndpointTest {
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
// failure = statusCode >= 400(无上界)
|
||||
// failure = statusCode >= 400(无上界)或语义动作标注 login-failure
|
||||
// (登录失败的 HTTP 状态码可能为 200/302)
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("400");
|
||||
.contains("400")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldApplySuccessResultFilterExcludingLoginFailure() {
|
||||
webClient.get()
|
||||
.uri("/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query?result=success")
|
||||
.exchange()
|
||||
.expectStatus().isOk();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
|
||||
var condition = captor.getValue().toCondition().toString();
|
||||
// success = 2xx/3xx 且排除登录失败标注(其状态码可能落在 2xx/3xx 区间)
|
||||
assertThat(condition)
|
||||
.contains("spec.statusCode")
|
||||
.contains("spec.action")
|
||||
.contains("login-failure");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+59
-12
@@ -55,7 +55,7 @@ class AuditRecorderTest {
|
||||
.header("User-Agent", "UA-1")
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, new ChangeCapture(), 204, "admin", null);
|
||||
recorder.record(snapshot, new ChangeCapture(), 204, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -78,14 +78,15 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null);
|
||||
// XHR/JSON 登录失败(401):过滤器判定 loginFailed=true,动作标注登录失败
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null, true);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
assertThat(captor.getValue().getSpec().getUsername())
|
||||
.isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
||||
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth");
|
||||
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login");
|
||||
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login-failure");
|
||||
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@@ -93,21 +94,21 @@ class AuditRecorderTest {
|
||||
void shouldRecordAttemptedUsernameForLoginAttempt() {
|
||||
// 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan");
|
||||
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan", true);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
||||
assertThat(spec.getAttemptedUsername()).isEqualTo("zhangsan");
|
||||
assertThat(spec.getAction()).isEqualTo("login");
|
||||
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAnnotateSubActionSemanticAction() {
|
||||
recorder.record(RequestSnapshot.of(MockServerHttpRequest
|
||||
.put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish")
|
||||
.build()), new ChangeCapture(), 200, "admin", null);
|
||||
.build()), new ChangeCapture(), 200, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -115,13 +116,59 @@ class AuditRecorderTest {
|
||||
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("posts");
|
||||
}
|
||||
|
||||
// ===== 登录失败标注(LoginOutcome + 语义动作 login-failure) =====
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailedLoginAttempt() {
|
||||
// 表单登录失败(302 重定向目标含 error 参数):过滤器传入 loginFailed=true,
|
||||
// 语义动作标注 login-failure;状态码仍如实记录 302
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(302);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAnnotateLoginFailureActionOnFailureEcho() {
|
||||
// 登录失败回显(GET /login?error=... 页面渲染 HTTP 200):同样标注登录失败
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.get("http://localhost/login?error=invalid-credential&method=local")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, new ChangeCapture(), 200,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, true);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var spec = captor.getValue().getSpec();
|
||||
assertThat(spec.getAction()).isEqualTo("login-failure");
|
||||
assertThat(spec.getStatusCode()).isEqualTo(200);
|
||||
assertThat(spec.getPath()).isEqualTo("/login?error=invalid-credential&method=local");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepLoginActionOnSuccessfulLogin() {
|
||||
// 表单登录成功(302 → /uc):语义动作仍为 login,不标注登录失败
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 302,
|
||||
AuditLogSpec.UNKNOWN_USERNAME, null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
assertThat(captor.getValue().getSpec().getAction()).isEqualTo("login");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipRecordingWhenAuditDisabled() {
|
||||
when(settingProvider.get())
|
||||
.thenReturn(Mono.just(new AuditSettings(false, 30, null, null)));
|
||||
|
||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
|
||||
200, "admin", null);
|
||||
200, "admin", null, false);
|
||||
|
||||
verify(client, never()).create(any(AuditLog.class));
|
||||
}
|
||||
@@ -131,7 +178,7 @@ class AuditRecorderTest {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
new ChangeCapture(), 200, "admin", null)).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 200, "admin", null, false)).doesNotThrowAnyException();
|
||||
|
||||
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
||||
verify(client).create(any(AuditLog.class));
|
||||
@@ -143,7 +190,7 @@ class AuditRecorderTest {
|
||||
new IllegalStateException("storage unavailable")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
new ChangeCapture(), 500, "admin", null)).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 500, "admin", null, false)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -161,7 +208,7 @@ class AuditRecorderTest {
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 200, "admin", null);
|
||||
recorder.record(snapshot, capture, 200, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -186,7 +233,7 @@ class AuditRecorderTest {
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 403, "admin", null);
|
||||
recorder.record(snapshot, capture, 403, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -197,7 +244,7 @@ class AuditRecorderTest {
|
||||
@Test
|
||||
void shouldNotRecordChangesWhenContextMissing() {
|
||||
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
|
||||
new ChangeCapture(), 200, "admin", null);
|
||||
new ChangeCapture(), 200, "admin", null, false);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+6
-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
|
||||
|
||||
+72
-44
@@ -5,6 +5,7 @@ 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;
|
||||
@@ -12,13 +13,14 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/**
|
||||
* 登录尝试用户名提取测试(功能评审 P0-1):表单体解析(成功/无 username/异常静默)、
|
||||
* JSON 体提取、字段白名单(密码绝不提取)、请求体缓存后下游可重复读、
|
||||
* 分块/超限/不支持形态降级为原 exchange。
|
||||
* 登录尝试用户名提取测试(功能评审 P0-1):表单经 {@code getFormData()} 提取
|
||||
* (与下游 CSRF/登录转换器共享缓存解析结果,不消费原始 body——真实环境回归实证:
|
||||
* 缓存原始 body 会让下游 CSRF 读不到 _csrf 参数而拒绝登录)、JSON 体缓存提取、
|
||||
* 字段白名单(密码绝不提取)、超长用户名不提取、不支持形态降级为原 exchange。
|
||||
*/
|
||||
class LoginAttemptCaptureTest {
|
||||
|
||||
@@ -54,7 +56,7 @@ class LoginAttemptCaptureTest {
|
||||
return attempt;
|
||||
}
|
||||
|
||||
// ===== 表单体解析 =====
|
||||
// ===== 表单提取(经 getFormData 共享缓存,不消费原始 body) =====
|
||||
|
||||
@Test
|
||||
void shouldExtractUsernameFromFormBody() {
|
||||
@@ -86,22 +88,64 @@ class LoginAttemptCaptureTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToRawValueOnMalformedEncoding() {
|
||||
// 裸 % 等非法编码:解码失败回退原值,尽力提取且绝不抛出
|
||||
var attempt = prepare(formExchange("username=bad%zz&password=x"));
|
||||
void shouldNotTouchRawBodyForFormRequests() {
|
||||
// 表单形态绝不缓存原始 body / 装饰 exchange:prepare 后 exchange 原样透传,
|
||||
// 下游(CSRF 过滤器、表单登录转换器)经同一份 getFormData 缓存读取表单
|
||||
var exchange = formExchange("username=admin&password=secret");
|
||||
|
||||
assertThat(attempt.getAttemptedUsername()).isEqualTo("bad%zz");
|
||||
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 shouldExtractSilentlyFromGarbageBody() {
|
||||
// 解析异常静默:任何畸形输入都不抛出、不提取
|
||||
var attempt = prepare(formExchange("&&&"));
|
||||
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();
|
||||
}
|
||||
|
||||
// ===== JSON 体提取 =====
|
||||
@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() {
|
||||
@@ -117,18 +161,16 @@ class LoginAttemptCaptureTest {
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
// ===== 请求体缓存与下游可重复读 =====
|
||||
|
||||
@Test
|
||||
void shouldKeepBodyReadableDownstream() {
|
||||
var body = "username=admin&password=secret";
|
||||
var exchange = formExchange(body);
|
||||
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),登录处理可正常读取表单
|
||||
// 装饰后的请求可重复读(每次订阅独立 buffer)
|
||||
assertThat(prepared).isNotSameAs(exchange);
|
||||
var first = prepared.getRequest().getBody()
|
||||
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
||||
@@ -158,27 +200,12 @@ class LoginAttemptCaptureTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughChunkedBodyWithoutContentLength() {
|
||||
var request = MockServerHttpRequest.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(Flux.just(DefaultDataBufferFactory.sharedInstance
|
||||
.wrap("username=admin".getBytes(StandardCharsets.UTF_8))));
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
|
||||
// 分块传输(无 Content-Length):不读请求体,避免中断流式请求
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(attempt.getAttemptedUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughOversizedBody() {
|
||||
var oversized = "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES + 1);
|
||||
void shouldPassthroughOversizedJsonBody() {
|
||||
var oversized = "{\"username\":\"" + "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES)
|
||||
+ "\"}";
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(oversized.length())
|
||||
.body(oversized));
|
||||
|
||||
@@ -190,10 +217,10 @@ class LoginAttemptCaptureTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassthroughEmptyBody() {
|
||||
void shouldPassthroughEmptyJsonBody() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED));
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
var attempt = new LoginAttempt();
|
||||
var prepared = capture.prepare(exchange, attempt).block();
|
||||
@@ -228,13 +255,14 @@ class LoginAttemptCaptureTest {
|
||||
|
||||
@Test
|
||||
void shouldExtractLastUsernameWhenDuplicated() {
|
||||
assertThat(LoginAttemptCapture.usernameOfForm("username=first&username=second"))
|
||||
assertThat(LoginAttemptCapture.usernameOfFormValues(List.of("first", "second")))
|
||||
.isEqualTo("second");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForBlankFormBody() {
|
||||
assertThat(LoginAttemptCapture.usernameOfForm(null)).isNull();
|
||||
assertThat(LoginAttemptCapture.usernameOfForm(" ")).isNull();
|
||||
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();
|
||||
}
|
||||
}
|
||||
+27
-136
@@ -2,19 +2,19 @@ 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.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
@@ -23,21 +23,21 @@ import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import run.halo.operationaudit.alert.LoginFailureAlertService;
|
||||
|
||||
/**
|
||||
* 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
* {@code /apis/**} 捕获过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
|
||||
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
|
||||
* 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(2xx 成功/其余失败)。
|
||||
* 登录尝试用户名(功能评审 P0-1):POST /login 请求期提取并透传给告警与记录。
|
||||
*
|
||||
* <p>认证端点({@code /login}、{@code /logout})不在本过滤器职责内(P0 修复:它们由
|
||||
* {@link AuthEndpointAuditWebFilter} 在 Security 链之前捕获,此处透传不记录),
|
||||
* 其行为见 {@link AuthEndpointAuditWebFilterTest} 与过滤链集成测试。
|
||||
*/
|
||||
class OperationAuditWebFilterTest {
|
||||
|
||||
private AuditRecorder recorder;
|
||||
private ChangeCaptureManager captureManager;
|
||||
private HttpWriteMarker writeMarker;
|
||||
private LoginFailureAlertService loginFailureAlertService;
|
||||
private OperationAuditWebFilter filter;
|
||||
|
||||
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
||||
@@ -52,34 +52,15 @@ class OperationAuditWebFilterTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** 终止型 chain:模拟异常响应(指定状态码)后完成。 */
|
||||
private static final class FailingWebFilterChainStub implements
|
||||
org.springframework.web.server.WebFilterChain {
|
||||
private final org.springframework.http.HttpStatus status;
|
||||
|
||||
private FailingWebFilterChainStub(org.springframework.http.HttpStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(org.springframework.web.server.ServerWebExchange exchange) {
|
||||
exchange.getResponse().setStatusCode(status);
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
recorder = mock(AuditRecorder.class);
|
||||
captureManager = mock(ChangeCaptureManager.class);
|
||||
writeMarker = mock(HttpWriteMarker.class);
|
||||
loginFailureAlertService = mock(LoginFailureAlertService.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,
|
||||
new LoginAttemptCapture(), loginFailureAlertService);
|
||||
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,7 +78,7 @@ class OperationAuditWebFilterTest {
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq("admin"), isNull());
|
||||
eq("admin"), isNull(), eq(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,38 +89,27 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
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), any(ChangeCapture.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordAndAlertAttemptedUsernameOnLoginAttempt() {
|
||||
// 登录尝试用户名(功能评审 P0-1):表单体中的 username 白名单提取,
|
||||
// 随告警回调与审计记录透传;密码等其余字段绝不提取
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.contentLength("username=admin&password=secret".getBytes(StandardCharsets.UTF_8).length)
|
||||
.body("username=admin&password=secret"));
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"));
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200),
|
||||
eq("admin"));
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(writeMarker, times(2)).onRequestStart(any());
|
||||
verify(writeMarker, times(2)).onRequestComplete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,7 +121,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -168,28 +138,7 @@ class OperationAuditWebFilterTest {
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureLogoutAsAuth() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/logout")
|
||||
.build());
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
List.of(() -> "ROLE_ADMIN"));
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
||||
.verifyComplete();
|
||||
|
||||
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"),
|
||||
isNull());
|
||||
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
|
||||
.isEqualTo("auth");
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -219,7 +168,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
// 请求期创建的同一个 capture 实例被透传给记录阶段
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
|
||||
eq("admin"), isNull());
|
||||
eq("admin"), isNull(), eq(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -246,7 +195,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
verify(writeMarker).onRequestStart(any());
|
||||
verify(writeMarker).onRequestComplete(any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any(), any(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -260,62 +209,4 @@ class OperationAuditWebFilterTest {
|
||||
verify(writeMarker, never()).onRequestStart(any());
|
||||
verify(writeMarker, never()).onRequestComplete(any());
|
||||
}
|
||||
|
||||
// ===== 登录失败告警(产品设计 V2「告警通知」) =====
|
||||
|
||||
@Test
|
||||
void shouldNotifyLoginResultOnLoginAttempt() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200),
|
||||
isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotifyLoginFailureStatusOnFailedLogin() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange,
|
||||
new FailingWebFilterChainStub(org.springframework.http.HttpStatus.UNAUTHORIZED)))
|
||||
.verifyComplete();
|
||||
|
||||
// 非常响应(401)同样回调,由告警服务按失败累计
|
||||
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401),
|
||||
isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotNotifyLoginResultForLoginPageOrLogout() {
|
||||
// 登录页 GET 与登出不是登录尝试
|
||||
var loginPage = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/login")
|
||||
.build());
|
||||
StepVerifier.create(filter.filter(loginPage, CHAIN)).verifyComplete();
|
||||
|
||||
var logout = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/logout")
|
||||
.build());
|
||||
StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotNotifyLoginResultForApisRequests() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/apis/api.content.halo.run/v1alpha1/posts")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(loginFailureAlertService, never())
|
||||
.onLoginResult(any(RequestSnapshot.class), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
+29
@@ -197,6 +197,9 @@ class OperationDescriptionTest {
|
||||
@Test
|
||||
void shouldDescribeFromActionKey() {
|
||||
assertThat(OperationDescription.describeAction("login", "auth")).isEqualTo("登录");
|
||||
// 登录失败语义动作(POST /login 失败或 GET /login?error=... 失败回显)
|
||||
assertThat(OperationDescription.describeAction("login-failure", "auth"))
|
||||
.isEqualTo("登录失败");
|
||||
assertThat(OperationDescription.describeAction("logout", "auth")).isEqualTo("登出");
|
||||
assertThat(OperationDescription.describeAction("auth", "auth")).isEqualTo("认证操作");
|
||||
assertThat(OperationDescription.describeAction("create", "users")).isEqualTo("新建用户");
|
||||
@@ -215,4 +218,30 @@ class OperationDescriptionTest {
|
||||
assertThat(OperationDescription.describeAction(null, "posts")).isNull();
|
||||
assertThat(OperationDescription.describeAction("bogus", "posts")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDescribeSpecPreferingStoredAction() {
|
||||
// 落库语义动作优先:登录失败标注(回显页 HTTP 200 无法由路径重新推导出失败)
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setMethod("GET");
|
||||
spec.setResourceType("auth");
|
||||
spec.setPath("/login?error=invalid-credential&method=local");
|
||||
spec.setAction("login-failure");
|
||||
assertThat(OperationDescription.describe(spec)).isEqualTo("登录失败");
|
||||
|
||||
// 无标注(历史记录)回退 method/path 现场推导
|
||||
var legacy = new AuditLogSpec();
|
||||
legacy.setMethod("POST");
|
||||
legacy.setResourceType("auth");
|
||||
legacy.setPath("/login");
|
||||
assertThat(OperationDescription.describe(legacy)).isEqualTo("登录");
|
||||
|
||||
// 落库标注未识别时同样回退现场推导
|
||||
var bogus = new AuditLogSpec();
|
||||
bogus.setMethod("PUT");
|
||||
bogus.setResourceType("posts");
|
||||
bogus.setPath("/apis/content.halo.run/v1alpha1/posts/abc");
|
||||
bogus.setAction("bogus");
|
||||
assertThat(OperationDescription.describe(bogus)).isEqualTo("修改文章");
|
||||
}
|
||||
}
|
||||
|
||||
+199
@@ -17,6 +17,7 @@
|
||||
"@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",
|
||||
@@ -1436,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",
|
||||
@@ -1460,6 +1474,26 @@
|
||||
"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",
|
||||
@@ -1516,6 +1550,19 @@
|
||||
"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",
|
||||
@@ -1536,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",
|
||||
@@ -1599,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",
|
||||
@@ -1700,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",
|
||||
@@ -1785,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",
|
||||
@@ -1807,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",
|
||||
@@ -1848,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",
|
||||
@@ -1864,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",
|
||||
@@ -1988,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",
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"@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",
|
||||
|
||||
@@ -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";
|
||||
@@ -0,0 +1,36 @@
|
||||
/* 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.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Webhook 推送结果(成功为接收方 2xx;失败时 message 携带原因摘要)
|
||||
* @export
|
||||
* @interface AlertSendResult
|
||||
*/
|
||||
export interface AlertSendResult {
|
||||
/**
|
||||
* 是否送达(接收方 2xx)
|
||||
* @type {boolean}
|
||||
* @memberof AlertSendResult
|
||||
*/
|
||||
'success': boolean;
|
||||
/**
|
||||
* 成功时为响应状态摘要(如 HTTP 200),失败时为原因摘要
|
||||
* @type {string}
|
||||
* @memberof AlertSendResult
|
||||
*/
|
||||
'message': string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/* 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.
|
||||
*/
|
||||
|
||||
|
||||
// May contain unused imports in some cases
|
||||
// @ts-ignore
|
||||
import type { AuditLog } from './audit-log';
|
||||
|
||||
/**
|
||||
* 审计日志分页结果(ListResult<AuditLog>)
|
||||
* @export
|
||||
* @interface AuditLogList
|
||||
*/
|
||||
export interface AuditLogList {
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'page': number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'size': number;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'total': number;
|
||||
/**
|
||||
*
|
||||
* @type {Array<AuditLog>}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'items': Array<AuditLog>;
|
||||
/**
|
||||
*
|
||||
* @type {boolean}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'first'?: boolean;
|
||||
/**
|
||||
*
|
||||
* @type {boolean}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'last'?: boolean;
|
||||
/**
|
||||
*
|
||||
* @type {boolean}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'hasNext'?: boolean;
|
||||
/**
|
||||
*
|
||||
* @type {boolean}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'hasPrevious'?: boolean;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof AuditLogList
|
||||
*/
|
||||
'totalPages'?: number;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/* 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.
|
||||
*/
|
||||
|
||||
|
||||
// May contain unused imports in some cases
|
||||
// @ts-ignore
|
||||
import type { ChangeEntry } from './change-entry';
|
||||
|
||||
/**
|
||||
* 审计日志业务字段(spec)
|
||||
* @export
|
||||
* @interface AuditLogSpec
|
||||
*/
|
||||
export interface AuditLogSpec {
|
||||
/**
|
||||
* 操作者用户名;登录失败记 unknown
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'username': string;
|
||||
/**
|
||||
* 登录尝试的用户名(仅 POST /login 白名单提取落库);提取失败或非登录请求为 null
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'attemptedUsername'?: string | null;
|
||||
/**
|
||||
* HTTP 方法(动作),如 POST/PUT/DELETE/PATCH
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'method': string;
|
||||
/**
|
||||
* 语义动作键(捕获时标注落库);旧版本写入的历史记录可能缺失
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'action'?: string | null;
|
||||
/**
|
||||
* 资源类型(复数形式,如 posts/comments/users/auth)
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'resourceType': string;
|
||||
/**
|
||||
* 资源名称;集合级操作或登录端点为空
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'resourceName'?: string | null;
|
||||
/**
|
||||
* 完整请求路径(含查询串)
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'path': string;
|
||||
/**
|
||||
* 响应状态码(结果:2xx 成功,其余失败)
|
||||
* @type {number}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'statusCode': number;
|
||||
/**
|
||||
* 来源 IP
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'remoteIp': string;
|
||||
/**
|
||||
* User-Agent;系统内部变更记录为 null
|
||||
* @type {string}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'userAgent'?: string | null;
|
||||
/**
|
||||
* 字段级变更列表;历史记录或不可捕获场景缺失
|
||||
* @type {Array<ChangeEntry>}
|
||||
* @memberof AuditLogSpec
|
||||
*/
|
||||
'changes'?: Array<ChangeEntry> | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/* 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.
|
||||
*/
|
||||
|
||||
|
||||
// May contain unused imports in some cases
|
||||
// @ts-ignore
|
||||
import type { AuditLogSpec } from './audit-log-spec';
|
||||
// May contain unused imports in some cases
|
||||
// @ts-ignore
|
||||
import type { Metadata } from './metadata';
|
||||
|
||||
/**
|
||||
* 审计日志自定义模型(Extension,group audit.guichumo.com/v1alpha1)
|
||||
* @export
|
||||
* @interface AuditLog
|
||||
*/
|
||||
export interface AuditLog {
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof AuditLog
|
||||
*/
|
||||
'apiVersion': string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof AuditLog
|
||||
*/
|
||||
'kind': string;
|
||||
/**
|
||||
*
|
||||
* @type {Metadata}
|
||||
* @memberof AuditLog
|
||||
*/
|
||||
'metadata': Metadata;
|
||||
/**
|
||||
*
|
||||
* @type {AuditLogSpec}
|
||||
* @memberof AuditLog
|
||||
*/
|
||||
'spec': AuditLogSpec;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/* 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.
|
||||
*/
|
||||
|
||||
|
||||
// May contain unused imports in some cases
|
||||
// @ts-ignore
|
||||
import type { ChangeType } from './change-type';
|
||||
|
||||
/**
|
||||
* 字段级变更条目(新旧值均已在后端脱敏与截断;缺失侧为 null)
|
||||
* @export
|
||||
* @interface ChangeEntry
|
||||
*/
|
||||
export interface ChangeEntry {
|
||||
/**
|
||||
* 字段路径(点号分隔,如 spec.title)
|
||||
* @type {string}
|
||||
* @memberof ChangeEntry
|
||||
*/
|
||||
'field': string;
|
||||
/**
|
||||
*
|
||||
* @type {ChangeType}
|
||||
* @memberof ChangeEntry
|
||||
*/
|
||||
'changeType': ChangeType;
|
||||
/**
|
||||
* 变更前的值;字段为新增时缺失
|
||||
* @type {string}
|
||||
* @memberof ChangeEntry
|
||||
*/
|
||||
'oldValue'?: string | null;
|
||||
/**
|
||||
* 变更后的值;字段被移除时缺失
|
||||
* @type {string}
|
||||
* @memberof ChangeEntry
|
||||
*/
|
||||
'newValue'?: string | null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/* 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
|
||||
* @enum {string}
|
||||
*/
|
||||
|
||||
export const ChangeType = {
|
||||
Added: 'ADDED',
|
||||
Updated: 'UPDATED',
|
||||
Removed: 'REMOVED'
|
||||
} as const;
|
||||
|
||||
export type ChangeType = typeof ChangeType[keyof typeof ChangeType];
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from './alert-send-result';
|
||||
export * from './audit-log';
|
||||
export * from './audit-log-list';
|
||||
export * from './audit-log-spec';
|
||||
export * from './change-entry';
|
||||
export * from './change-type';
|
||||
export * from './metadata';
|
||||
@@ -0,0 +1,72 @@
|
||||
/* 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.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 扩展资源元数据(run.halo.app.extension.Metadata)
|
||||
* @export
|
||||
* @interface Metadata
|
||||
*/
|
||||
export interface Metadata {
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'name': string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'generateName'?: string;
|
||||
/**
|
||||
*
|
||||
* @type {{ [key: string]: string; }}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'labels'?: { [key: string]: string; };
|
||||
/**
|
||||
*
|
||||
* @type {{ [key: string]: string; }}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'annotations'?: { [key: string]: string; };
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'version'?: number;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'creationTimestamp': string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'deletionTimestamp'?: string | null;
|
||||
/**
|
||||
*
|
||||
* @type {Array<string>}
|
||||
* @memberof Metadata
|
||||
*/
|
||||
'finalizers'?: Array<string>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { axiosInstance } from '@halo-dev/api-client'
|
||||
import { AuditV1alpha1ConsoleApi } from './generated'
|
||||
|
||||
/**
|
||||
* 插件 API 客户端封装(官方 api-request 指南):
|
||||
*
|
||||
* <p>TS 类型与请求方法来自 {@link ./generated}(devtools `generateApiClient` 产物,
|
||||
* 由 build.gradle 的 openApi 管线从 Springdoc 声明生成),禁止手写或改动生成内容;
|
||||
* API 契约变更一律修改后端 SpringdocRouteBuilder 声明后重新生成。
|
||||
*
|
||||
* <p>生成类实例复用宿主 {@link axiosInstance}(自带登录态、权限失败与统一错误处理),
|
||||
* 不得另行 axios.create() 直连 /api、/apis。
|
||||
*/
|
||||
const auditApiClient = {
|
||||
audit: new AuditV1alpha1ConsoleApi(undefined, '', axiosInstance),
|
||||
}
|
||||
|
||||
export { auditApiClient }
|
||||
@@ -4,31 +4,32 @@ import { describe, expect, it } from 'vitest'
|
||||
|
||||
// 结构性回归测试:不渲染组件,仅检查 SFC 源码中的测试告警链路。
|
||||
// 「发送测试告警」为插件设置「告警通知」区的自定义 FormKit 输入(功能评审 P0-2):
|
||||
// 点击 → POST 测试告警端点(无请求体)→ 同步反馈结果提示(成功/失败两色),
|
||||
// 点击 → 生成客户端 testAlertWebhook(端点路径由后端 Springdoc 声明经
|
||||
// generateApiClient 生成,禁止手写)→ 同步反馈结果提示(成功/失败两色),
|
||||
// 期间按钮 loading。历史上验证 webhook 配置只能等真实告警触发,本测试锁定
|
||||
// 端点路径与反馈链路形态,防止路径漂移或链路残缺。
|
||||
// 生成客户端链路与反馈形态,防止链路残缺或退回裸 fetch。
|
||||
const sfc = readFileSync(
|
||||
fileURLToPath(new URL('./TestAlertButton.vue', import.meta.url)),
|
||||
'utf-8',
|
||||
)
|
||||
|
||||
describe('TestAlertButton 测试告警', () => {
|
||||
it('声明与后端一致的测试告警端点路径', () => {
|
||||
expect(sfc).toContain(
|
||||
"const TEST_ALERT_ENDPOINT = '/apis/audit.guichumo.com/v1alpha1/alerts/-/test'",
|
||||
)
|
||||
it('经生成客户端调用测试端点(不手写端点路径、不裸 fetch)', () => {
|
||||
expect(sfc).toContain('auditApiClient.audit.testAlertWebhook()')
|
||||
expect(sfc).not.toContain('/apis/audit.guichumo.com')
|
||||
expect(sfc).not.toMatch(/\bfetch\(/)
|
||||
})
|
||||
|
||||
it('点击 POST 测试告警端点,按钮 loading、防重复点击', () => {
|
||||
expect(sfc).toContain("await fetch(TEST_ALERT_ENDPOINT, { method: 'POST' })")
|
||||
it('点击触发推送,按钮 loading、防重复点击', () => {
|
||||
expect(sfc).toContain('if (sending.value)')
|
||||
expect(sfc).toMatch(/<VButton :loading="sending"[^>]*@click="sendTestAlert">/)
|
||||
expect(sfc).toContain('发送测试告警')
|
||||
})
|
||||
|
||||
it('推送结果以提示反馈:成功/失败两色,非 2xx 抛出后进失败提示', () => {
|
||||
expect(sfc).toContain('hintType.value = body.success ? \'success\' : \'error\'')
|
||||
expect(sfc).toMatch(/throw new Error\(body\.message \|\| `发送失败(HTTP \$\{response\.status\})`\)/)
|
||||
it('推送结果以提示反馈:成功/失败两色,HTTP 400 消息取后端返回的 message', () => {
|
||||
expect(sfc).toContain("hintType.value = data.success ? 'success' : 'error'")
|
||||
expect(sfc).toContain("hint.value = data.success ? `发送成功(${data.message})`")
|
||||
expect(sfc).toContain('axiosError?.response?.data?.message')
|
||||
expect(sfc).toContain("hintType.value = 'error'")
|
||||
expect(sfc).toContain('hint-success')
|
||||
expect(sfc).toContain('hint-error')
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { VButton } from '@halo-dev/components'
|
||||
import { auditApiClient } from '@/api'
|
||||
|
||||
/**
|
||||
* 「发送测试告警」自定义 FormKit 输入(功能评审 P0-2):
|
||||
* 在插件设置「告警通知」区提供手动推送入口——向当前已保存的 Webhook 地址
|
||||
* 推送一条 type=test 测试消息,并同步反馈发送结果(成功/失败 + 原因摘要)。
|
||||
* 不承载任何配置值(settings.yaml 中以 ignore: true 声明,不新增设置项)。
|
||||
* (存于 Halo Secret,设置仅持引用)推送一条 type=test 测试消息,并同步反馈
|
||||
* 发送结果(成功/失败 + 原因摘要)。不承载任何配置值(settings.yaml 中以
|
||||
* ignore: true 声明,不新增设置项)。
|
||||
*
|
||||
* <p>经生成客户端调用测试端点(ui/src/api/generated,generateApiClient 产物):
|
||||
* 400(地址未配置/Secret 缺字段等)与网络失败均归一进失败提示,信息优先取
|
||||
* 后端返回的 message。
|
||||
*/
|
||||
|
||||
/** 测试告警端点(与后端 AlertTestEndpoint 保持一致)。 */
|
||||
const TEST_ALERT_ENDPOINT = '/apis/audit.guichumo.com/v1alpha1/alerts/-/test'
|
||||
|
||||
const sending = ref(false)
|
||||
const hint = ref('')
|
||||
const hintType = ref<'success' | 'error'>('success')
|
||||
@@ -23,16 +25,19 @@ async function sendTestAlert() {
|
||||
sending.value = true
|
||||
hint.value = ''
|
||||
try {
|
||||
const response = await fetch(TEST_ALERT_ENDPOINT, { method: 'POST' })
|
||||
const body = (await response.json()) as { success?: boolean; message?: string }
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || `发送失败(HTTP ${response.status})`)
|
||||
}
|
||||
hintType.value = body.success ? 'success' : 'error'
|
||||
hint.value = body.success ? `发送成功(${body.message})` : `发送失败:${body.message}`
|
||||
const { data } = await auditApiClient.audit.testAlertWebhook()
|
||||
hintType.value = data.success ? 'success' : 'error'
|
||||
hint.value = data.success ? `发送成功(${data.message})` : `发送失败:${data.message}`
|
||||
} catch (e) {
|
||||
hintType.value = 'error'
|
||||
hint.value = e instanceof Error ? e.message : String(e)
|
||||
const axiosError = e as { response?: { status?: number; data?: { message?: string } } }
|
||||
hint.value =
|
||||
axiosError?.response?.data?.message ||
|
||||
(axiosError?.response?.status
|
||||
? `发送失败(HTTP ${axiosError.response.status})`
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: String(e))
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
deriveAction,
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
isLoginFailure,
|
||||
resultBadge,
|
||||
SEMANTIC_ACTIONS,
|
||||
SYSTEM_USERNAME,
|
||||
UNKNOWN_USERNAME,
|
||||
@@ -153,6 +155,19 @@ describe('deriveAction 语义动作推导', () => {
|
||||
expect(deriveAction('POST', 'auth', '/auth/other')).toBe('auth')
|
||||
})
|
||||
|
||||
it('登录失败回显(GET /login?error=...)推导为 login-failure', () => {
|
||||
// 登录失败后 Halo 重定向到带 error 参数的登录页,页面渲染 HTTP 200;
|
||||
// 历史记录(无落库标注)由路径中的 error 参数现场推导
|
||||
expect(deriveAction('GET', 'auth', '/login?error=invalid-credential&method=local'))
|
||||
.toBe('login-failure')
|
||||
// 兜底失败分支:error 参数无值
|
||||
expect(deriveAction('GET', 'auth', '/login?error&method=local')).toBe('login-failure')
|
||||
// 首次打开登录页(无 error 参数)不是失败回显
|
||||
expect(deriveAction('GET', 'auth', '/login?method=local')).toBe('login')
|
||||
// 含 error 字样的其他参数不算失败标记
|
||||
expect(deriveAction('GET', 'auth', '/login?errors=1')).toBe('login')
|
||||
})
|
||||
|
||||
it('子动作段优先于 HTTP 方法', () => {
|
||||
expect(deriveAction('PUT', 'posts',
|
||||
'/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish')).toBe('publish')
|
||||
@@ -219,6 +234,101 @@ describe('describeOperation 落库标注优先', () => {
|
||||
action: 'bogus',
|
||||
}))).toBe('修改文章')
|
||||
})
|
||||
|
||||
it('登录失败标注(login-failure)描述为 登录失败', () => {
|
||||
// 表单登录失败(POST /login,302)与失败回显页(GET /login?error=...,200)
|
||||
// 均落库标注,描述为 登录失败 而非按路径推导出的 登录
|
||||
expect(describeOperation(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
action: 'login-failure',
|
||||
}))).toBe('登录失败')
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
action: 'login-failure',
|
||||
}))).toBe('登录失败')
|
||||
// 历史回显记录(无落库标注)由路径现场推导,同样得到 登录失败
|
||||
expect(describeOperation(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
}))).toBe('登录失败')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isLoginFailure / resultBadge 登录失败结果展示', () => {
|
||||
it('落库标注 login-failure 判定为登录失败(HTTP 200/302 也可能是失败)', () => {
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
action: 'login-failure',
|
||||
}))).toBe(true)
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
action: 'login-failure',
|
||||
}))).toBe(true)
|
||||
})
|
||||
|
||||
it('历史回显记录(无落库标注)由路径现场推导', () => {
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
}))).toBe(true)
|
||||
// 表单登录失败的历史记录(POST /login,302)无法由路径推导,仍按登录展示
|
||||
// (升级后新记录落库标注,不再有此局限)
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
}))).toBe(false)
|
||||
// 成功登录(POST /login,302 → /uc)不是登录失败
|
||||
expect(isLoginFailure(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
action: 'login',
|
||||
}))).toBe(false)
|
||||
})
|
||||
|
||||
it('登录失败记录结果徽标为红色 失败(不显示裸状态码)', () => {
|
||||
// 失败回显页 HTTP 200:修复前显示绿色 200,误读为登录成功
|
||||
expect(resultBadge(spec({
|
||||
method: 'GET',
|
||||
resourceType: 'auth',
|
||||
path: '/login?error=invalid-credential&method=local',
|
||||
statusCode: 200,
|
||||
action: 'login-failure',
|
||||
}))).toEqual({ text: '失败', class: 'status-fail' })
|
||||
// 表单登录失败 302 重定向:同理
|
||||
expect(resultBadge(spec({
|
||||
method: 'POST',
|
||||
resourceType: 'auth',
|
||||
path: '/login',
|
||||
statusCode: 302,
|
||||
action: 'login-failure',
|
||||
}))).toEqual({ text: '失败', class: 'status-fail' })
|
||||
})
|
||||
|
||||
it('非登录记录保持原状:数字状态码徽标(2xx/3xx 绿、其余红)', () => {
|
||||
expect(resultBadge(spec({ statusCode: 200 }))).toEqual({ text: '200', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 302 }))).toEqual({ text: '302', class: 'status-ok' })
|
||||
expect(resultBadge(spec({ statusCode: 403 }))).toEqual({ text: '403', class: 'status-fail' })
|
||||
expect(resultBadge(spec({ statusCode: 500 }))).toEqual({ text: '500', class: 'status-fail' })
|
||||
expect(resultBadge(spec({ statusCode: undefined })))
|
||||
.toEqual({ text: 'undefined', class: 'status-fail' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('SEMANTIC_ACTIONS 筛选选项', () => {
|
||||
@@ -231,9 +341,9 @@ describe('SEMANTIC_ACTIONS 筛选选项', () => {
|
||||
})
|
||||
|
||||
it('覆盖全部可落库的语义动作键(view 不会被捕获规则记录,除外)', () => {
|
||||
// 全量枚举:登录/登出/认证 + 方法动作 + 全部子动作段(含 activation 归并)
|
||||
// 全量枚举:登录/登录失败/登出/认证 + 方法动作 + 全部子动作段(含 activation 归并)
|
||||
const storable = new Set([
|
||||
'login', 'logout', 'auth',
|
||||
'login', 'login-failure', 'logout', 'auth',
|
||||
'create', 'update', 'delete',
|
||||
'publish', 'unpublish', 'recycle', 'restore', 'enable', 'disable',
|
||||
'upgrade', 'uninstall', 'reload', 'reply', 'recalculate',
|
||||
|
||||
@@ -1,58 +1,14 @@
|
||||
/**
|
||||
* 审计日志的类型定义与展示辅助。
|
||||
* 审计日志的展示辅助。
|
||||
*
|
||||
* <p>模型类型(AuditLog/AuditLogSpec/ChangeEntry/ChangeType 等)不再在此手写,
|
||||
* 一律从 `@/api/generated` 导入(devtools generateApiClient 产物,与后端契约同源);
|
||||
* 本文件只保留展示与推导逻辑。
|
||||
*/
|
||||
import type { AuditLogSpec, ChangeType } from '@/api/generated'
|
||||
|
||||
export interface AuditLogSpec {
|
||||
username: string
|
||||
/** 登录尝试的用户名(功能评审 P0-1):仅 POST /login 请求提取落库,其余为 null。 */
|
||||
attemptedUsername?: string | null
|
||||
method: string
|
||||
resourceType: string
|
||||
resourceName?: string | null
|
||||
path: string
|
||||
/** 语义动作键(语义动作标注,如 login/create/publish);旧版本写入的历史记录可能缺失。 */
|
||||
action?: string | null
|
||||
statusCode: number
|
||||
remoteIp: string
|
||||
userAgent?: string | null
|
||||
/** 字段级变更列表(字段级变更 diff);历史记录或不可捕获场景缺失。 */
|
||||
changes?: AuditLogChange[] | null
|
||||
}
|
||||
|
||||
/** 字段级变更类型(与后端 ChangeType 一致)。 */
|
||||
export type AuditLogChangeType = 'ADDED' | 'UPDATED' | 'REMOVED'
|
||||
|
||||
/** 字段级变更条目(新旧值均已在后端脱敏与截断)。 */
|
||||
export interface AuditLogChange {
|
||||
/** 字段路径(点号分隔,如 spec.title)。 */
|
||||
field: string
|
||||
changeType: AuditLogChangeType
|
||||
/** 变更前的值;字段为新增时缺失。 */
|
||||
oldValue?: string | null
|
||||
/** 变更后的值;字段被移除时缺失。 */
|
||||
newValue?: string | null
|
||||
}
|
||||
|
||||
export interface AuditLog {
|
||||
metadata: {
|
||||
name: string
|
||||
creationTimestamp: string
|
||||
version?: number
|
||||
}
|
||||
spec: AuditLogSpec
|
||||
}
|
||||
|
||||
export interface ListResult<T> {
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
items: T[]
|
||||
first?: boolean
|
||||
last?: boolean
|
||||
hasNext?: boolean
|
||||
hasPrevious?: boolean
|
||||
totalPages?: number
|
||||
}
|
||||
/** 展示与推导逻辑使用的审计日志 spec 类型(generated 模型)。 */
|
||||
export type { AuditLogSpec }
|
||||
|
||||
export const UNKNOWN_USERNAME = 'unknown'
|
||||
|
||||
@@ -148,9 +104,13 @@ const SEGMENT_ACTIONS: Record<string, string> = {
|
||||
resetpassword: 'resetpassword',
|
||||
}
|
||||
|
||||
/** 登录失败语义动作键(与后端 OperationDescription.LOGIN_FAILURE_ACTION 同步)。 */
|
||||
const LOGIN_FAILURE_ACTION = 'login-failure'
|
||||
|
||||
/** 语义动作键 → 完整短语(不拼资源名)。 */
|
||||
const ACTION_PHRASES: Record<string, string> = {
|
||||
login: '登录',
|
||||
[LOGIN_FAILURE_ACTION]: '登录失败',
|
||||
logout: '登出',
|
||||
auth: '认证操作',
|
||||
password: '修改密码',
|
||||
@@ -182,6 +142,7 @@ const ACTION_VERBS: Record<string, string> = {
|
||||
*/
|
||||
export const SEMANTIC_ACTIONS: Array<{ value: string; label: string }> = [
|
||||
{ value: 'login', label: '登录' },
|
||||
{ value: 'login-failure', label: '登录失败' },
|
||||
{ value: 'logout', label: '登出' },
|
||||
{ value: 'auth', label: '认证操作' },
|
||||
{ value: 'create', label: '新建' },
|
||||
@@ -211,10 +172,32 @@ function pathWithoutQuery(path?: string | null): string {
|
||||
return queryStart >= 0 ? path.slice(0, queryStart) : path
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询串是否含 error 参数(可为无值形式 error)。
|
||||
* 登录失败回显页(GET /login?error=invalid-credential&method=...)由该参数识别。
|
||||
*/
|
||||
function hasErrorParam(path?: string | null): boolean {
|
||||
if (!path) {
|
||||
return false
|
||||
}
|
||||
const queryStart = path.indexOf('?')
|
||||
if (queryStart < 0) {
|
||||
return false
|
||||
}
|
||||
return path
|
||||
.slice(queryStart + 1)
|
||||
.split('&')
|
||||
.some((pair) => (pair.indexOf('=') < 0 ? pair : pair.slice(0, pair.indexOf('='))) === 'error')
|
||||
}
|
||||
|
||||
/**
|
||||
* 推导语义动作键(语义动作标注,与后端 OperationDescription.actionOf 保持一致):
|
||||
* 登录/登出/认证操作由路径判定,子动作段优先于 HTTP 方法,其余方法归为
|
||||
* create/update/delete/view;无法识别返回 null。
|
||||
* 登录/登录失败/登出/认证操作由路径判定(GET /login?error=... 为登录失败回显),
|
||||
* 子动作段优先于 HTTP 方法,其余方法归为 create/update/delete/view;
|
||||
* 无法识别返回 null。
|
||||
*
|
||||
* <p>历史局限:升级前落库的表单登录失败记录(POST /login,302)无法由路径重新
|
||||
* 推导出失败,仍推导为 login;仅回显页(GET,error 参数在路径中)可现场推导。
|
||||
*/
|
||||
export function deriveAction(
|
||||
method: string,
|
||||
@@ -223,7 +206,7 @@ export function deriveAction(
|
||||
): string | null {
|
||||
const cleanPath = pathWithoutQuery(path)
|
||||
if (cleanPath === '/login') {
|
||||
return 'login'
|
||||
return hasErrorParam(path) ? LOGIN_FAILURE_ACTION : 'login'
|
||||
}
|
||||
if (cleanPath === '/logout') {
|
||||
return 'logout'
|
||||
@@ -294,6 +277,39 @@ export function isSuccessful(statusCode?: number | null): boolean {
|
||||
return statusCode != null && statusCode >= 200 && statusCode < 400
|
||||
}
|
||||
|
||||
/** 结果徽标展示形态:文本与配色 class。 */
|
||||
export interface ResultBadge {
|
||||
text: string
|
||||
class: 'status-ok' | 'status-fail'
|
||||
}
|
||||
|
||||
/**
|
||||
* 结果列徽标(列表/详情共用):登录失败记录(语义动作 login-failure,HTTP 状态码可能
|
||||
* 为 200/302——失败回显页渲染/表单登录失败重定向)显示「失败」而非裸状态码,避免
|
||||
* 绿色 200/302 误读为登录成功;其余记录保持原状——按 HTTP 状态码展示
|
||||
* (2xx/3xx 绿、其余红),与既有行为一致。
|
||||
*/
|
||||
export function resultBadge(spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path'
|
||||
| 'action' | 'statusCode'>): ResultBadge {
|
||||
if (isLoginFailure(spec)) {
|
||||
return { text: '失败', class: 'status-fail' }
|
||||
}
|
||||
return {
|
||||
text: String(spec.statusCode),
|
||||
class: isSuccessful(spec.statusCode) ? 'status-ok' : 'status-fail',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为登录失败记录:优先落库语义动作标注(spec.action,POST /login 失败与
|
||||
* 失败回显均落库),历史记录回退由路径现场推导(仅回显页可推导)。
|
||||
*/
|
||||
export function isLoginFailure(spec: Pick<AuditLogSpec, 'method' | 'resourceType' | 'path'
|
||||
| 'action'>): boolean {
|
||||
const action = spec.action ?? deriveAction(spec.method, spec.resourceType, spec.path)
|
||||
return action === LOGIN_FAILURE_ACTION
|
||||
}
|
||||
|
||||
/** 变更类型 → 中文标签(未知类型回退原始值)。 */
|
||||
const CHANGE_TYPE_LABELS: Record<string, string> = {
|
||||
ADDED: '新增',
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { VButton, VSpace } from '@halo-dev/components'
|
||||
import type { AuditLog, AuditLogChangeType } from '@/utils/audit'
|
||||
import type { AuditLog, ChangeType } from '@/api/generated'
|
||||
import {
|
||||
changeTypeLabel,
|
||||
changeValueDisplay,
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
formatTime,
|
||||
isLoginFailure,
|
||||
isSuccessful,
|
||||
methodBadgeClass,
|
||||
} from '@/utils/audit'
|
||||
@@ -23,18 +24,33 @@ const emit = defineEmits<{
|
||||
|
||||
const close = () => emit('update:visible', false)
|
||||
|
||||
// 结果语义:登录失败记录(HTTP 状态码可能为 200/302)显示「登录失败」,
|
||||
// 其余按 HTTP 状态码判定成败
|
||||
const resultText = computed(() => {
|
||||
if (!props.log) {
|
||||
return '-'
|
||||
}
|
||||
if (isLoginFailure(props.log.spec)) {
|
||||
return '登录失败'
|
||||
}
|
||||
return isSuccessful(props.log.spec.statusCode) ? '成功' : '失败'
|
||||
})
|
||||
|
||||
const resultBadgeClass = computed(() => {
|
||||
if (!props.log) {
|
||||
return 'status-fail'
|
||||
}
|
||||
if (isLoginFailure(props.log.spec)) {
|
||||
return 'status-fail'
|
||||
}
|
||||
return isSuccessful(props.log.spec.statusCode) ? 'status-ok' : 'status-fail'
|
||||
})
|
||||
|
||||
/** 字段级变更(字段级变更 diff,产品设计 V2);历史记录缺失。 */
|
||||
const changes = computed(() => props.log?.spec.changes ?? [])
|
||||
|
||||
const changeBadgeClass = (changeType?: string | null): string => {
|
||||
switch (changeType as AuditLogChangeType) {
|
||||
switch (changeType as ChangeType) {
|
||||
case 'ADDED':
|
||||
return 'change-added'
|
||||
case 'REMOVED':
|
||||
@@ -105,10 +121,7 @@ const rawJson = computed(() =>
|
||||
<div class="detail-row">
|
||||
<dt>结果</dt>
|
||||
<dd>
|
||||
<span
|
||||
class="status-badge"
|
||||
:class="isSuccessful(log.spec.statusCode) ? 'status-ok' : 'status-fail'"
|
||||
>
|
||||
<span class="status-badge" :class="resultBadgeClass">
|
||||
{{ resultText }} · {{ log.spec.statusCode }}
|
||||
</span>
|
||||
</dd>
|
||||
|
||||
@@ -3,52 +3,47 @@ import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// 结构性回归测试:不渲染组件,仅检查 SFC 源码中的导出功能链路。
|
||||
// 导出为按当前筛选条件的全量 CSV 下载:工具栏「导出」按钮 → fetch 导出端点
|
||||
// (筛选参数与 query 一致,但去掉分页参数)→ blob 触发 a[download] 下载,
|
||||
// 期间按钮进入 loading、失败走顶部 VAlert 错误提示。
|
||||
// 历史上本功能不存在,本测试锁定端点路径与下载链路形态,防止路径漂移或链路残缺。
|
||||
// 导出为按当前筛选条件的全量 CSV 下载:工具栏「导出」按钮 → 生成客户端
|
||||
// exportAuditLogs(responseType: 'blob',端点路径与参数由 generateApiClient
|
||||
// 从后端声明生成,禁止手写)→ blob 触发 a[download] 下载,期间按钮进入 loading、
|
||||
// 失败走顶部 VAlert 错误提示。本测试锁定生成客户端链路形态与下载行为,
|
||||
// 防止链路残缺或退回裸 fetch。
|
||||
const sfc = readFileSync(fileURLToPath(new URL('./AuditLogList.vue', import.meta.url)), 'utf-8')
|
||||
|
||||
describe('AuditLogList 导出', () => {
|
||||
it('声明与后端一致的导出端点路径', () => {
|
||||
expect(sfc).toContain(
|
||||
"const EXPORT_ENDPOINT =\n '/apis/audit.guichumo.com/v1alpha1/auditlogs/-/export'",
|
||||
)
|
||||
it('经生成客户端导出(不手写端点路径、不裸 fetch)', () => {
|
||||
expect(sfc).toContain('auditApiClient.audit.exportAuditLogs(exportRequest')
|
||||
// 端点路径由生成客户端承载,SFC 不再出现硬编码路径
|
||||
expect(sfc).not.toContain('/apis/audit.guichumo.com')
|
||||
expect(sfc).not.toMatch(/\bfetch\(/)
|
||||
})
|
||||
|
||||
it('工具栏导出按钮:IconSave 图标、loading 绑定 exporting、点击 exportLogs', () => {
|
||||
// 导出按钮位于 VPageHeader #actions 的 VSpace 内,与「刷新」并列
|
||||
const actionsStart = sfc.indexOf('<template #actions>')
|
||||
expect(actionsStart).toBeGreaterThan(-1)
|
||||
const actionsEnd = sfc.indexOf('</VSpace>', actionsStart)
|
||||
const actions = sfc.slice(actionsStart, actionsEnd)
|
||||
expect(actions).toMatch(/<VButton :loading="exporting"[^>]*@click="exportLogs">/)
|
||||
expect(actions).toContain('<IconSave class="h-full w-full" />')
|
||||
expect(actions).toContain('导出')
|
||||
expect(actions).toContain('刷新')
|
||||
})
|
||||
|
||||
it('导出前去掉分页参数(导出为全量接口)', () => {
|
||||
it('导出请求复用查询筛选条件且不带分页参数(导出为全量接口)', () => {
|
||||
const fnStart = sfc.indexOf('async function exportLogs()')
|
||||
expect(fnStart).toBeGreaterThan(-1)
|
||||
const fn = sfc.slice(fnStart, sfc.indexOf('function resetFilter()', fnStart))
|
||||
expect(fn).toContain('new URLSearchParams(buildQuery())')
|
||||
expect(fn).toContain("params.delete('page')")
|
||||
expect(fn).toContain("params.delete('size')")
|
||||
expect(fn).toContain('const request = listRequest()')
|
||||
expect(fn).toContain('AuditV1alpha1ConsoleApiExportAuditLogsRequest')
|
||||
expect(fn).toContain('fieldSelector: request.fieldSelector')
|
||||
expect(fn).toContain('startTime: request.startTime')
|
||||
expect(fn).not.toContain('page: request.page')
|
||||
expect(fn).not.toContain('size: request.size')
|
||||
})
|
||||
|
||||
it('下载链路:fetch 非 ok 报错进 VAlert,blob → createObjectURL → a[download]', () => {
|
||||
it('二进制响应以 blob 请求(CSV 附件下载)', () => {
|
||||
const fnStart = sfc.indexOf('async function exportLogs()')
|
||||
const fn = sfc.slice(fnStart, sfc.indexOf('function resetFilter()', fnStart))
|
||||
// 错误语义与查询一致:HTTP 非 2xx 抛错并写入 error(顶部 VAlert 展示)
|
||||
expect(fn).toMatch(/throw new Error\(`导出失败(HTTP \$\{response\.status\})`\)/)
|
||||
expect(fn).toContain('error.value = e instanceof Error ? e.message : String(e)')
|
||||
expect(fn).toContain('await response.blob()')
|
||||
expect(fn).toContain("responseType: 'blob'")
|
||||
expect(fn).toContain('URL.createObjectURL(blob)')
|
||||
expect(fn).toMatch(/anchor\.download = exportFilename\(\)/)
|
||||
expect(fn).toContain('anchor.click()')
|
||||
expect(fn).toContain('URL.revokeObjectURL(url)')
|
||||
// 无论成败都复位按钮 loading
|
||||
})
|
||||
|
||||
it('失败进顶部 VAlert:错误摘要写 error,无论成败都复位按钮 loading', () => {
|
||||
const fnStart = sfc.indexOf('async function exportLogs()')
|
||||
const fn = sfc.slice(fnStart, sfc.indexOf('function resetFilter()', fnStart))
|
||||
expect(fn).toContain("error.value = errorMessage(e, '导出失败')")
|
||||
expect(fn).toMatch(/finally\s*\{\s*exporting\.value = false\s*\}/)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// 移动端适配结构性回归测试:不渲染组件,仅检查 SFC 源码。
|
||||
// 固定列宽列表合计约 69.5rem,窄屏(≤1023px:手机横竖屏 / 平板竖屏 / 半屏小窗口)
|
||||
// 下必然超出视口:题头与数据行置于同一横向滚动容器(.audit-list)整体左右滑动,
|
||||
// 列对齐关系与桌面一致;筛选栏窄屏 2 列(≤480px 手机竖屏单列)、分页条允许换行;
|
||||
// ≥1024px 维持桌面布局不变。
|
||||
// 特别注意:VEntity 是多根 Fragment 组件(tr + 可选 footer tr),其 <tr> 拿不到
|
||||
// 本组件的 scoped 作用域 ID,所有锚定 .audit-row / 行内元素 :deep 的 scoped 规则
|
||||
// 永远失配(历史上「隐藏题头 + 数据行纵向堆叠」方案因此整批失效——窄屏下字段
|
||||
// 仍按固定列宽横排并被视口截断),行内样式必须锚定自身元素 .audit-list 穿透,
|
||||
// 本测试防止该失效方案被重新引入。
|
||||
const sfc = readFileSync(fileURLToPath(new URL('./AuditLogList.vue', import.meta.url)), 'utf-8')
|
||||
|
||||
const MOBILE_QUERY = '@media (max-width: 1023px)'
|
||||
|
||||
/** 提取 max-width: 1023px 媒体查询块全文(大括号配平)。 */
|
||||
function mobileBlock(): string {
|
||||
const start = sfc.indexOf(MOBILE_QUERY)
|
||||
expect(start, `缺少 ${MOBILE_QUERY} 媒体查询`).toBeGreaterThan(-1)
|
||||
let depth = 0
|
||||
let end = -1
|
||||
for (let i = sfc.indexOf('{', start); i < sfc.length; i++) {
|
||||
if (sfc[i] === '{') depth++
|
||||
else if (sfc[i] === '}') {
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
end = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return sfc.slice(start, end)
|
||||
}
|
||||
|
||||
/** 在指定文本块内取某选择器的规则体(自 from 起首个匹配)。 */
|
||||
function ruleIn(block: string, selector: string, from = 0): string {
|
||||
const start = block.indexOf(`${selector} {`, from)
|
||||
expect(start, `块中缺少 ${selector} 规则`).toBeGreaterThan(-1)
|
||||
const end = block.indexOf('}', start)
|
||||
return block.slice(start, end)
|
||||
}
|
||||
|
||||
/** 取全局(非媒体查询)样式中某选择器的规则体。 */
|
||||
function styleRule(selector: string): string {
|
||||
const start = sfc.indexOf(`${selector} {`)
|
||||
expect(start, `缺少 ${selector} 样式规则`).toBeGreaterThan(-1)
|
||||
const end = sfc.indexOf('}', start)
|
||||
return sfc.slice(start, end)
|
||||
}
|
||||
|
||||
describe('AuditLogList 移动端适配', () => {
|
||||
it('存在 ≤1023px 窄屏断点,且位于桌面规则之后(同特异性按顺序覆盖才生效)', () => {
|
||||
const mediaStart = sfc.indexOf(MOBILE_QUERY)
|
||||
const desktopGrid = sfc.indexOf('.filter-grid {')
|
||||
expect(desktopGrid).toBeGreaterThan(-1)
|
||||
expect(mediaStart).toBeGreaterThan(desktopGrid)
|
||||
})
|
||||
|
||||
it('窄屏筛选栏改为 2 列,操作按钮独占整行并拉伸铺满', () => {
|
||||
const grid = ruleIn(mobileBlock(), '.filter-grid')
|
||||
expect(grid).toMatch(/grid-template-columns:\s*repeat\(2,\s*minmax\(0,\s*1fr\)\)/)
|
||||
const actions = ruleIn(mobileBlock(), '.filter-actions')
|
||||
expect(actions).toMatch(/grid-column:\s*1\s*\/\s*-1/)
|
||||
const stretch = ruleIn(mobileBlock(), '.filter-actions > :deep(*)')
|
||||
expect(stretch).toMatch(/flex:\s*1/)
|
||||
})
|
||||
|
||||
it('手机竖屏(≤480px)筛选栏单列,datetime-local 不被压扁', () => {
|
||||
const start = sfc.indexOf('@media (max-width: 480px)')
|
||||
expect(start, '缺少 ≤480px 单列断点').toBeGreaterThan(-1)
|
||||
expect(sfc.slice(start)).toMatch(
|
||||
/grid-template-columns:\s*minmax\(0,\s*1fr\)/,
|
||||
)
|
||||
})
|
||||
|
||||
it('题头与数据行置于同一横向滚动容器(.audit-list overflow-x: auto)', () => {
|
||||
// 模板顺序:.audit-list 包裹 .audit-header 与全部 VEntity 数据行,
|
||||
// 滑动时题头与数据列保持对齐
|
||||
const listStart = sfc.indexOf('<div class="audit-list">')
|
||||
expect(listStart, '缺少 .audit-list 滚动容器').toBeGreaterThan(-1)
|
||||
const headerStart = sfc.indexOf('<div class="audit-header">')
|
||||
const entityStart = sfc.indexOf('<VEntity')
|
||||
const listEnd = sfc.indexOf('</div>\n </template>', listStart)
|
||||
expect(headerStart).toBeGreaterThan(listStart)
|
||||
expect(entityStart).toBeGreaterThan(headerStart)
|
||||
expect(listEnd).toBeGreaterThan(entityStart)
|
||||
const rule = styleRule('.audit-list')
|
||||
expect(rule).toMatch(/overflow-x:\s*auto/)
|
||||
})
|
||||
|
||||
it('窄屏不隐藏列题头(题头随容器滑动,列对齐关系不变)', () => {
|
||||
// 历史方案曾在窄屏 display: none 隐藏题头,导致用户失去列语义,防止回归
|
||||
const headerRule = styleRule('.audit-header')
|
||||
expect(headerRule).not.toMatch(/display:\s*none/)
|
||||
expect(mobileBlock()).not.toContain('.audit-header')
|
||||
})
|
||||
|
||||
it('题头在滚动容器内随内容延伸且列宽不收缩(滑动后下划线不断裂、不与数据列错位)', () => {
|
||||
const header = styleRule('.audit-header')
|
||||
expect(header).toMatch(/min-width:\s*max-content/)
|
||||
const col = styleRule('.header-col')
|
||||
expect(col).toMatch(/flex-shrink:\s*0/)
|
||||
})
|
||||
|
||||
it('数据行保持固定列宽表格形态,无失效的行内堆叠样式', () => {
|
||||
// VEntity 的 <tr> 拿不到本组件 scoped 作用域 ID,锚定 .audit-row 的规则永远失配;
|
||||
// 窄屏块内不得出现任何 entity 行内 :deep 规则,全文件不得再有 .audit-row 选择器
|
||||
// (选择器须位于行首或上一规则之后,注释中的历史说明不受限)
|
||||
expect(mobileBlock()).not.toContain('entity-')
|
||||
expect(sfc).not.toMatch(/(?:^|[},;])\s*\.audit-row[\s:{]/)
|
||||
})
|
||||
|
||||
it('行悬停手型经自身元素 .audit-list 穿透到 VEntity 行', () => {
|
||||
const rule = styleRule('.audit-list :deep(.entity-wrapper)')
|
||||
expect(rule).toMatch(/cursor:\s*pointer/)
|
||||
})
|
||||
|
||||
it('窄屏分页条允许换行(总数与翻页控制器不横向溢出)', () => {
|
||||
const rule = ruleIn(
|
||||
mobileBlock(),
|
||||
'.audit-pagination :deep(.pagination),\n .audit-pagination :deep(.pagination__controller)',
|
||||
)
|
||||
expect(rule).toMatch(/flex-wrap:\s*wrap/)
|
||||
})
|
||||
})
|
||||
@@ -28,8 +28,8 @@ describe('AuditLogList 查看该资源历史', () => {
|
||||
})
|
||||
|
||||
it('不新增后端参数:复用现有 resourceType fieldSelector 与 keyword 模糊匹配', () => {
|
||||
// 与现有筛选/导出条件共用同一套状态——buildQuery 生成相同参数形态
|
||||
expect(sfc).toContain("params.append('fieldSelector', `spec.resourceType=${filterResourceType.value}`)")
|
||||
expect(sfc).toContain("params.set('keyword', filterKeyword.value.trim())")
|
||||
// 与现有筛选/导出条件共用同一套状态——listRequest 生成相同参数形态(生成客户端请求对象)
|
||||
expect(sfc).toContain('fieldSelector.push(`spec.resourceType=${filterResourceType.value}`)')
|
||||
expect(sfc).toContain('keyword: filterKeyword.value.trim() || undefined')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,25 +14,25 @@ import {
|
||||
IconRefreshLine,
|
||||
IconSave,
|
||||
} from '@halo-dev/components'
|
||||
import type { AuditLog, ListResult } from '@/utils/audit'
|
||||
import type {
|
||||
AuditLog,
|
||||
AuditV1alpha1ConsoleApiExportAuditLogsRequest,
|
||||
AuditV1alpha1ConsoleApiListAuditLogsRequest,
|
||||
} from '@/api/generated'
|
||||
import { auditApiClient } from '@/api'
|
||||
import {
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
formatTime,
|
||||
isSuccessful,
|
||||
localDateTimeToInstant,
|
||||
methodBadgeClass,
|
||||
resultBadge,
|
||||
SEMANTIC_ACTIONS,
|
||||
} from '@/utils/audit'
|
||||
import AuditLogDetail from './AuditLogDetail.vue'
|
||||
|
||||
/** 查询端点路径(与 AuditQueryEndpoint 保持一致)。 */
|
||||
const QUERY_ENDPOINT =
|
||||
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query'
|
||||
|
||||
/** 导出端点路径:筛选参数与 query 一致,全量 CSV 附件下载(与 AuditQueryEndpoint 保持一致)。 */
|
||||
const EXPORT_ENDPOINT =
|
||||
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/export'
|
||||
// 查询/导出走生成客户端(ui/src/api/generated,generateApiClient 产物):
|
||||
// 端点路径与参数由后端 Springdoc 声明生成,禁止在此手写或覆盖。
|
||||
|
||||
const RESOURCE_TYPES = [
|
||||
'posts', 'comments', 'users', 'roles', 'auth', 'settings', 'configmaps',
|
||||
@@ -73,54 +73,52 @@ const hasActiveFilter = computed(
|
||||
filterEndTime.value,
|
||||
)
|
||||
|
||||
function buildQuery(): string {
|
||||
const params = new URLSearchParams()
|
||||
params.set('page', String(page.value))
|
||||
params.set('size', String(size.value))
|
||||
params.set('sort', 'metadata.creationTimestamp,desc')
|
||||
/** 查询请求对象(与后端 AuditQueryEndpoint 声明一致的生成参数形态)。 */
|
||||
function listRequest(): AuditV1alpha1ConsoleApiListAuditLogsRequest {
|
||||
const fieldSelector: string[] = []
|
||||
if (filterUsername.value.trim()) {
|
||||
params.append('fieldSelector', `spec.username=${filterUsername.value.trim()}`)
|
||||
fieldSelector.push(`spec.username=${filterUsername.value.trim()}`)
|
||||
}
|
||||
if (filterResourceType.value) {
|
||||
params.append('fieldSelector', `spec.resourceType=${filterResourceType.value}`)
|
||||
fieldSelector.push(`spec.resourceType=${filterResourceType.value}`)
|
||||
}
|
||||
if (filterMethod.value) {
|
||||
params.append('fieldSelector', `spec.method=${filterMethod.value}`)
|
||||
fieldSelector.push(`spec.method=${filterMethod.value}`)
|
||||
}
|
||||
// 语义动作筛选(spec.action,捕获时标注落库;历史记录无标注不会被筛出)
|
||||
if (filterAction.value) {
|
||||
params.append('fieldSelector', `spec.action=${filterAction.value}`)
|
||||
fieldSelector.push(`spec.action=${filterAction.value}`)
|
||||
}
|
||||
if (filterResult.value) {
|
||||
params.set('result', filterResult.value)
|
||||
return {
|
||||
page: page.value,
|
||||
size: size.value,
|
||||
sort: 'metadata.creationTimestamp,desc',
|
||||
fieldSelector,
|
||||
result: filterResult.value || undefined,
|
||||
keyword: filterKeyword.value.trim() || undefined,
|
||||
startTime: localDateTimeToInstant(filterStartTime.value) ?? undefined,
|
||||
endTime: localDateTimeToInstant(filterEndTime.value) ?? undefined,
|
||||
}
|
||||
if (filterKeyword.value.trim()) {
|
||||
params.set('keyword', filterKeyword.value.trim())
|
||||
}
|
||||
const start = localDateTimeToInstant(filterStartTime.value)
|
||||
const end = localDateTimeToInstant(filterEndTime.value)
|
||||
if (start) {
|
||||
params.set('startTime', start)
|
||||
|
||||
/** 统一错误摘要:HTTP 错误取状态码(沿用旧 fetch 行为),其余取消息原文。 */
|
||||
function errorMessage(e: unknown, action: string): string {
|
||||
const status = (e as { response?: { status?: number } })?.response?.status
|
||||
if (status) {
|
||||
return `${action}(HTTP ${status})`
|
||||
}
|
||||
if (end) {
|
||||
params.set('endTime', end)
|
||||
}
|
||||
return params.toString()
|
||||
return e instanceof Error ? e.message : String(e)
|
||||
}
|
||||
|
||||
async function fetchLogs() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await fetch(`${QUERY_ENDPOINT}?${buildQuery()}`)
|
||||
if (!response.ok) {
|
||||
throw new Error(`查询失败(HTTP ${response.status})`)
|
||||
}
|
||||
const result = (await response.json()) as ListResult<AuditLog>
|
||||
logs.value = result.items ?? []
|
||||
total.value = result.total ?? 0
|
||||
const { data } = await auditApiClient.audit.listAuditLogs(listRequest())
|
||||
logs.value = data.items ?? []
|
||||
total.value = data.total ?? 0
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e)
|
||||
error.value = errorMessage(e, '查询失败')
|
||||
logs.value = []
|
||||
total.value = 0
|
||||
} finally {
|
||||
@@ -138,20 +136,24 @@ function exportFilename(): string {
|
||||
)
|
||||
}
|
||||
|
||||
/** 按当前筛选条件导出全部记录:fetch → blob → 触发下载,失败进顶部错误提示。 */
|
||||
/** 按当前筛选条件导出全部记录:生成客户端(responseType=blob)→ 触发下载,失败进顶部错误提示。 */
|
||||
async function exportLogs() {
|
||||
exporting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
// 导出为全量接口,无需分页参数
|
||||
const params = new URLSearchParams(buildQuery())
|
||||
params.delete('page')
|
||||
params.delete('size')
|
||||
const response = await fetch(`${EXPORT_ENDPOINT}?${params.toString()}`)
|
||||
if (!response.ok) {
|
||||
throw new Error(`导出失败(HTTP ${response.status})`)
|
||||
// 导出为全量接口,无需分页参数(复用查询请求,仅保留筛选条件)
|
||||
const request = listRequest()
|
||||
const exportRequest: AuditV1alpha1ConsoleApiExportAuditLogsRequest = {
|
||||
fieldSelector: request.fieldSelector,
|
||||
result: request.result,
|
||||
keyword: request.keyword,
|
||||
startTime: request.startTime,
|
||||
endTime: request.endTime,
|
||||
}
|
||||
const blob = await response.blob()
|
||||
const response = await auditApiClient.audit.exportAuditLogs(exportRequest, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
const blob = response.data
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
@@ -159,7 +161,7 @@ async function exportLogs() {
|
||||
anchor.click()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e)
|
||||
error.value = errorMessage(e, '导出失败')
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
@@ -320,6 +322,12 @@ onMounted(fetchLogs)
|
||||
</template>
|
||||
</VEmpty>
|
||||
<template v-else>
|
||||
<!-- 题头与数据行置于同一横向滚动容器:固定列宽合计约 69.5rem,
|
||||
容器窄于列表(手机/竖屏平板/半屏窗口)时整体左右滑动看全六列,
|
||||
列对齐关系与桌面完全一致;容器够宽时无溢出、无滚动条,桌面观感不变。
|
||||
:deep 规则须锚定此容器(本组件自己的元素)才能穿透到 VEntity 行内,
|
||||
VEntity 是多根 Fragment 组件,其 <tr> 拿不到本组件的 scoped 作用域 ID -->
|
||||
<div class="audit-list">
|
||||
<!-- 列题头:分组结构与内边距镜像 entity 行的两个 td,列宽与各 VEntityField 的 width 一一对应 -->
|
||||
<div class="audit-header">
|
||||
<div class="header-start">
|
||||
@@ -336,7 +344,6 @@ onMounted(fetchLogs)
|
||||
<VEntity
|
||||
v-for="log in logs"
|
||||
:key="log.metadata.name"
|
||||
class="audit-row"
|
||||
@click="openDetail(log)"
|
||||
>
|
||||
<template #start>
|
||||
@@ -380,21 +387,21 @@ onMounted(fetchLogs)
|
||||
</VEntityField>
|
||||
</template>
|
||||
<template #end>
|
||||
<!-- 结果列:徽标经 #title 插槽渲染(当前版本组件在无 title 时
|
||||
不渲染 #extra,原先徽标实际不可见) -->
|
||||
<!-- 结果列:登录失败记录(HTTP 200/302 也可能是失败,语义动作已标注)
|
||||
显示红色「失败」,避免绿色 200/302 误读为登录成功;
|
||||
徽标经 #title 插槽渲染(当前版本组件在无 title 时不渲染 #extra,
|
||||
原先徽标实际不可见) -->
|
||||
<VEntityField width="4rem">
|
||||
<template #title>
|
||||
<span
|
||||
class="status-badge"
|
||||
:class="isSuccessful(log.spec.statusCode) ? 'status-ok' : 'status-fail'"
|
||||
>
|
||||
{{ log.spec.statusCode }}
|
||||
<span class="status-badge" :class="resultBadge(log.spec).class">
|
||||
{{ resultBadge(log.spec).text }}
|
||||
</span>
|
||||
</template>
|
||||
</VEntityField>
|
||||
<VEntityField :title="log.spec.remoteIp" width="9rem" />
|
||||
</template>
|
||||
</VEntity>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
<!-- 分页条置于卡片内部末尾:白底铺满整行,与上方列表左右对齐 -->
|
||||
@@ -474,6 +481,14 @@ onMounted(fetchLogs)
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
/* 题头与数据行共用横向滚动容器(同官方 EntityList 的 w-full overflow-x-auto):
|
||||
固定列宽合计约 69.5rem,容器更窄(手机/竖屏平板/半屏窗口)时整体左右滑动;
|
||||
容器够宽时不产生滚动条,桌面观感不变。
|
||||
VEntity 行内样式一律经此自身元素 :deep 穿透:VEntity 是多根 Fragment 组件,
|
||||
其 <tr> 拿不到本组件的 scoped 作用域 ID,锚定 .audit-row 的规则永远失配。 */
|
||||
.audit-list {
|
||||
overflow-x: auto;
|
||||
}
|
||||
/* 列题头:VEntity 数据行由两个 td(entity-start-wrapper / entity-end-wrapper)组成,
|
||||
每个 td 自带 1rem 左右内边距,end 组紧跟 start 组之后(行宽由内容收缩,不铺满)。
|
||||
题头按同样结构分两组、各组自带 1rem 内边距,才能与数据列一一对齐;
|
||||
@@ -481,6 +496,9 @@ onMounted(fetchLogs)
|
||||
.audit-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
/* 滚动容器内题头盒随内容延伸(否则下划线止于可视宽度,滑动后断裂);
|
||||
容器更宽时仍为 100%,与桌面一致 */
|
||||
min-width: max-content;
|
||||
padding: 0.5rem 0;
|
||||
border-bottom: 1px solid #eaecf0;
|
||||
}
|
||||
@@ -498,6 +516,8 @@ onMounted(fetchLogs)
|
||||
font-size: 0.75rem;
|
||||
color: #666;
|
||||
white-space: nowrap;
|
||||
/* 列宽不参与 flex 收缩:窄屏下题头盒宽由内容决定,避免被压缩与数据列错位 */
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.col-username { width: 12rem; }
|
||||
.col-method { width: 6rem; }
|
||||
@@ -510,7 +530,9 @@ onMounted(fetchLogs)
|
||||
/* 错误提示位于白卡上方,与卡片留出间距 */
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.audit-row {
|
||||
/* 行悬停手型:VEntity 多根组件的 tr 无法携带本组件 scoped 作用域 ID,
|
||||
规则须锚定自身元素 .audit-list 再 :deep 穿透到行 */
|
||||
.audit-list :deep(.entity-wrapper) {
|
||||
cursor: pointer;
|
||||
}
|
||||
.row-sub {
|
||||
@@ -574,4 +596,41 @@ onMounted(fetchLogs)
|
||||
padding: 1rem;
|
||||
border-top: 1px solid #eaecf0;
|
||||
}
|
||||
|
||||
/* ===== 移动端适配(窄屏:手机 / 竖屏平板 / 半屏小窗口) =====
|
||||
桌面布局的 9 列筛选行在窄屏下每列仅剩数十像素(标签逐字换行、
|
||||
输入框被压扁),窄屏改为筛选 2 列(≤480px 手机竖屏单列)。
|
||||
列表保持题头 + 固定列宽的表格形态,由 .audit-list 整体左右滑动看全六列,
|
||||
列对齐与桌面一致。数据行纵向堆叠方案不可行:VEntity 是多根 Fragment
|
||||
组件,其 <tr> 拿不到本组件的 scoped 作用域 ID,所有锚定 .audit-row 的
|
||||
行内 :deep 规则均失配(历史方案因此整批失效),且堆叠后题头无从对齐。
|
||||
≥1024px 维持桌面布局不变。
|
||||
媒体查询置于文件末尾,同特异性规则按顺序覆盖桌面样式。 */
|
||||
@media (max-width: 1023px) {
|
||||
.audit-body {
|
||||
padding: 0.75rem 0.75rem 1.5rem;
|
||||
}
|
||||
.filter-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.filter-actions {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.filter-actions > :deep(*) {
|
||||
flex: 1;
|
||||
}
|
||||
/* 分页条(总数 + 翻页/条数控制器)窄屏下换行铺开,不横向溢出 */
|
||||
.audit-pagination :deep(.pagination),
|
||||
.audit-pagination :deep(.pagination__controller) {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
/* 手机竖屏:单列筛选,datetime-local 等宽控件不再被压扁 */
|
||||
.filter-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { viteConfig } from '@halo-dev/ui-plugin-bundler-kit/vite'
|
||||
import { fileURLToPath, URL } from 'url'
|
||||
|
||||
// 官方 ui-plugin-bundler-kit 负责外部化 vue / @halo-dev/* 依赖并输出 console/main.js
|
||||
// 官方 ui-plugin-bundler-kit 负责外部化 vue / @halo-dev/* 依赖并输出 ESM 产物
|
||||
// (requires >=2.26.0 触发 auto 判定,由 Gradle 打包进插件 jar 的 ui/ 目录)
|
||||
export default viteConfig({
|
||||
vite: {
|
||||
resolve: {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": 2,
|
||||
"skills": {
|
||||
"halo-plugin-dev": {
|
||||
"source": "halo-dev/dev-skills",
|
||||
"commit": "aad4e4fe13adbb6c612ac8a35095840380337658",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/halo-plugin-dev/SKILL.md",
|
||||
"computedHash": "4ffd83e4e51e5830e8d1db07d168b95733a485f560f9a3d88b1addbbd86dea06"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user