feat: 字段级变更 diff(捕获请求体与写入前状态,详情展示与 CSV 变更列)
- ChangeCaptureManager:请求期缓存 JSON 请求体(Content-Length 预检 ≤256KB, 装饰后下游可重复读)并抓取改/删操作的写入前资源状态(fetch(gvk, name), plural→GVK 经 SchemeManager 映射);全程失败静默降级为仅操作元信息 - ChangeDiffEngine:PUT 全量 diff;PATCH 双形态(JSON Patch ops 数组按 RFC 6902 + JSON Pointer 展开、对象 body 按 Merge Patch);POST 记新增、 DELETE 记移除;根级 apiVersion/kind/status 与 metadata 服务端子键降噪; 敏感字段脱敏、单值截断 200 字符、最多 30 条(汇总条兜底) - AuditLog.spec.changes(ChangeEntry 列表)仅 2xx 成功操作落库,不建索引 - 设置项新增"记录字段变更"(默认开),随审计总开关联动 - 详情抽屉新增"字段变更"区块(类型徽章 + 字段路径 + 新旧值), CSV 导出新增"变更"列(紧凑中文摘要) - 文档同步:产品设计(定位/详情/模型/局限)、技术方案(新增 D7)、README - 测试:新增 ChangeDiffEngineTest/ChangeCaptureManagerTest 与详情结构回归, 更新 Recorder/Filter/Exporter/设置相关用例;Java 120 + UI 45 全绿
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# halo-ops-audit
|
||||
|
||||
Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资源、做了什么操作、结果如何**"。
|
||||
Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资源、做了什么操作、结果如何、改了什么**"。
|
||||
|
||||
一条通用捕获规则覆盖后台全部写操作——文章、页面、评论、用户、设置、主题、插件启停、附件,
|
||||
以及登录 / 登出——无需逐资源配置;审计记录只增不改,Console 中不提供任何删除 / 修改入口。
|
||||
@@ -11,8 +11,9 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
|
||||
|---|---|
|
||||
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
||||
| 语义动作标注 | 捕获时标注语义动作键(登录/发布/恢复…),支持按其筛选;中文操作描述贯穿列表、详情与导出 |
|
||||
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含原始 JSON) |
|
||||
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码) |
|
||||
| 字段级变更 diff | 对成功的新建/修改/删除记录字段级新旧值(`spec.changes`),详情抽屉逐字段展示;敏感字段自动脱敏,JSON Patch 与 Merge Patch 均支持 |
|
||||
| Console 查看页 | 列表 + 八维筛选(操作者 / 资源类型 / 动作 / 语义动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含字段变更与原始 JSON) |
|
||||
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码,含"变更"列) |
|
||||
| 保留与清理 | 可配置保留天数(7 ~ ∞,默认 90),每日凌晨自动清理过期记录 |
|
||||
| 权限 | 默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`(verbs 仅 `get`/`list`) |
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ Halo 博客后台缺少操作追溯能力:文章被改、设置被动、评论
|
||||
|
||||
## 2. 产品定位
|
||||
|
||||
一句话:**回答"谁、在什么时候、对什么资源、做了什么操作、结果如何"**。
|
||||
一句话:**回答"谁、在什么时候、对什么资源、做了什么操作、结果如何、改了什么"**。
|
||||
|
||||
- 面向:站长(自用为主,验证稳定后考虑上架应用市场)
|
||||
- 形态:Halo 2.x 插件(Java 服务端 + Console 管理页)
|
||||
@@ -51,7 +51,7 @@ Console 左侧菜单新增"操作审计"页:
|
||||
|
||||
- 列表:时间、操作者、动作、资源、描述、结果、IP,索引分页查询
|
||||
- 筛选:按操作者、资源类型、动作、语义动作、结果、时间范围;关键字可模糊匹配资源名称/路径
|
||||
- 详情:单条记录完整字段
|
||||
- 详情:单条记录完整字段,含字段级变更(改了什么:字段路径 + 新旧值)
|
||||
- 只读:不提供任何删除/修改入口
|
||||
|
||||
### 4.3 保留与清理
|
||||
@@ -71,6 +71,7 @@ Console 左侧菜单新增"操作审计"页:
|
||||
|
||||
- 模型:`AuditLog`(group 用自有域名反写,如 `audit.<你的域名>`)
|
||||
- 索引:操作者、资源类型、动作、语义动作、结果、创建时间(支撑筛选与分页,避免内存分页);另含资源名称、完整路径两个索引,支撑关键字模糊筛选(4.2)
|
||||
- 字段级变更:`spec.changes`(字段路径、变更类型、新旧值),仅成功的建/改/删操作落库,不建索引(不参与筛选)
|
||||
- 存储由 Halo 统一管理
|
||||
|
||||
## 6. 非目标(V2+ 展望)
|
||||
@@ -78,7 +79,7 @@ Console 左侧菜单新增"操作审计"页:
|
||||
| 功能 | 说明 | 阶段 |
|
||||
|---|---|---|
|
||||
| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作:捕获时由方法/路径推导语义动作键落库(`spec.action`,含索引),Console 按语义动作筛选,中文操作描述贯穿列表、详情与导出 CSV | V2 已实现 |
|
||||
| 字段级变更 diff | 记录改了什么(需缓存请求体) | V2 |
|
||||
| 字段级变更 diff | 记录改了什么:捕获时缓存 JSON 请求体并抓取写入前资源状态,成功后计算字段级新旧值落库(`spec.changes`),详情抽屉展示、CSV 导出含"变更"列;敏感字段自动脱敏 | V2 已实现 |
|
||||
| 系统内部变更 | 定时发布等非 HTTP 触发的变更,执行者记"system" | V2 |
|
||||
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
|
||||
| 告警通知 | 登录失败告警、webhook | V2+ |
|
||||
@@ -89,6 +90,9 @@ Console 左侧菜单新增"操作审计"页:
|
||||
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2)
|
||||
- 系统内部触发的资源变更(如定时发布)暂不记录
|
||||
- 按语义动作筛选仅覆盖标注落库后的记录:升级前写入的历史记录可正常展示(描述现场推导),但不会被语义动作筛选命中
|
||||
- 字段级变更仅对 JSON 请求体(≤256KB 且带 Content-Length)与可定位到注册模型的资源抓取:非 JSON、超限、分块传输、模型未注册或旧状态获取失败时,仅记录操作元信息不记变更
|
||||
- 字段变更值单条截断 200 字符、单条记录最多 30 条(超出以汇总条兜底);字段名含 password/secret/token/credential 的值自动脱敏为 `******`
|
||||
- 字段变更只比较用户可写面:根级 `apiVersion/kind/status` 与 metadata 服务端管理子键(version/managedFields/时间戳等)不参与,服务端在写入后的二次加工(reconciler 改写)不反映在 diff 中
|
||||
- 超级管理员技术上仍可通过 API 删除审计记录(产品上不提供入口)
|
||||
- 审计写入失败静默降级为运行日志,不阻塞业务操作
|
||||
|
||||
|
||||
@@ -43,10 +43,15 @@ plugin-operation-audit/
|
||||
│ │ ├── OperationAuditPlugin.java # BasePlugin:注册/注销 Scheme 与索引
|
||||
│ │ ├── audit/
|
||||
│ │ │ ├── AuditLog.java # Extension + @GVK
|
||||
│ │ │ ├── AuditLogSpec.java
|
||||
│ │ │ ├── CaptureRule.java # 路径/方法/匿名判断(纯函数,便于测试)
|
||||
│ │ │ ├── AuditLogSpec.java # 含 changes 字段级变更列表
|
||||
│ │ │ ├── ChangeType.java # 变更类型 ADDED/UPDATED/REMOVED
|
||||
│ │ │ ├── ChangeEntry.java # 单条字段变更(field/type/old/new)
|
||||
│ │ │ ├── CaptureRule.java # 路径/方法/登录端点/匿名判断(纯函数,便于测试)
|
||||
│ │ │ ├── ResourceResolver.java # 路径 → 资源类型/名称(纯函数)
|
||||
│ │ │ ├── RequestSnapshot.java # 请求期解析的不可变快照
|
||||
│ │ │ ├── ChangeCapture.java # 请求期字段变更上下文(body/旧状态)
|
||||
│ │ │ ├── ChangeCaptureManager.java # 请求体缓存 + 写入前状态抓取(失败静默降级)
|
||||
│ │ │ ├── ChangeDiffEngine.java # 字段级 diff(纯函数:PUT/PATCH/POST/DELETE 语义)
|
||||
│ │ │ ├── OperationAuditWebFilter.java
|
||||
│ │ │ └── AuditRecorder.java # 组装 + 直写 + 降级日志
|
||||
│ │ └── housekeeping/
|
||||
@@ -132,8 +137,26 @@ rules:
|
||||
|
||||
### D6 插件设置读取
|
||||
|
||||
- `settings.yaml` 声明两个配置项:审计开关(默认开)、保留天数(默认 90,最小 7)。
|
||||
- 存储于插件关联 ConfigMap,`CaptureRule`/`RetentionCleaner` 经短 TTL 缓存(60s)读取,开关变更最多延迟 1 分钟生效——自用场景可接受,避免为实时生效引入 ConfigMap 监听器。
|
||||
- `settings.yaml` 声明配置项:审计开关(默认开)、保留天数(默认 90,最小 7)、记录字段变更(默认开)。
|
||||
- 存储于插件关联 ConfigMap,`CaptureRule`/`RetentionCleaner`/`ChangeCaptureManager` 经短 TTL 缓存(60s)读取,开关变更最多延迟 1 分钟生效——自用场景可接受,避免为实时生效引入 ConfigMap 监听器。
|
||||
|
||||
### D7 字段级变更捕获(产品设计 V2)
|
||||
|
||||
- 通道复用 D1 过滤器:命中捕获规则的请求经 `ChangeCaptureManager` 在请求期补充两类数据——
|
||||
JSON 请求体(`Content-Length ≤ 256KB`,经 `ServerHttpRequestDecorator` 缓存重建,下游可重复读)
|
||||
与写入前资源状态(`ReactiveExtensionClient.fetch(gvk, name)` 原始 JSON,plural → GVK 经
|
||||
`SchemeManager` 映射)。分块传输/超限/非 JSON 不缓存请求体;DELETE 无请求体也抓旧状态。
|
||||
- diff 语义(`ChangeDiffEngine`,纯函数):PUT 全量 diff;PATCH 双形态——数组 body 按
|
||||
JSON Patch(RFC 6902 ops + JSON Pointer,Halo 扩展路由标准 PATCH)展开,对象 body 按
|
||||
JSON Merge Patch(仅比较 body 字段、显式 null 视为删除);POST 全部记新增;DELETE 全部记移除。
|
||||
- 范围降噪:只比较用户可写面——根级 `apiVersion/kind/status` 跳过,`metadata` 仅保留
|
||||
`name/labels/annotations`;数组与超深子树整体叶子比较。空 group 的核心模型(ConfigMap 等)
|
||||
经源码级验证走 `/api/{version}/{plural}`,本就不在 `/apis/**` 捕获范围。
|
||||
- 输出约束:仅 2xx 落库(失败请求资源未实际变更);单值截断 200 字符、单条记录最多 30 条
|
||||
(汇总条兜底);字段名含 password/secret/token/credential 的值脱敏;捕获全程任何异常
|
||||
静默降级为"仅操作元信息",不影响业务(设计原则 4)。
|
||||
- 存储:`spec.changes`(`ChangeEntry` 列表:field/changeType/oldValue/newValue),
|
||||
不建索引(不参与筛选);升级前历史记录无此字段,详情展示不受影响。
|
||||
|
||||
## 5. 关键流程
|
||||
|
||||
@@ -187,8 +210,10 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
|---|---|
|
||||
| `CaptureRule` | 纯函数单测:路径/方法/登录端点/匿名组合用例 |
|
||||
| `ResourceResolver` | 纯函数单测:典型路径、深层子资源、非 `/apis` 路径 |
|
||||
| `OperationAuditWebFilter` | WebTestClient + 桩 chain(mock `ReactiveExtensionClient`,`StepVerifier`/verify):验证状态码捕获、操作者提取、匿名跳过 |
|
||||
| `AuditRecorder` | mock client:成功直写、失败降级为 warn 且不抛出 |
|
||||
| `OperationAuditWebFilter` | WebTestClient + 桩 chain(mock `ReactiveExtensionClient`,`StepVerifier`/verify):验证状态码捕获、操作者提取、匿名跳过、捕获上下文透传 |
|
||||
| `ChangeDiffEngine` | 纯函数单测:PUT/PATCH(JSON Patch 与 Merge Patch)/POST/DELETE 语义、范围降噪、脱敏、截断、封顶与空结果 |
|
||||
| `ChangeCaptureManager` | mock client/SchemeManager/设置:请求体缓存与装饰(下游可重复读)、旧状态抓取、开关降级、适用性判定 |
|
||||
| `AuditRecorder` | mock client:成功直写、失败降级为 warn 且不抛出、字段变更落库/跳过条件 |
|
||||
| `RetentionCleaner` | mock client + 固定时钟:过期批量删除、空批终止 |
|
||||
| 构建与回归 | 每里程碑 `./gradlew build` 全绿(AGENTS.md 约定) |
|
||||
| UI | MVP 仅保证构建通过,不引入组件测试(页面为标准实体列表,逻辑薄) |
|
||||
@@ -225,3 +250,7 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
> - #4 已按源码确认:实现 `AfterSecurityWebFilter`(`WebFilter` + `ExtensionPoint`)并以 `@Component` 注册即可。
|
||||
> - 2.26.1 的索引注册 API 为 `SchemeManager.register(Class, Consumer<IndexSpecs>)` + `IndexSpecs.single(...)`;
|
||||
> `QueryFactory`/`IndexAttributeFactory` 已 @Deprecated,实现使用 `Queries`/`Condition` 新体系。
|
||||
> - 字段级变更(D7):源码级证实空 group 核心模型路由为 `/api/{version}/{plural}`
|
||||
> (`ExtensionRouterFunctionFactory.PathPatternGenerator.buildExtensionPathPattern`),
|
||||
> 不在 `/apis/**` 捕获范围;扩展路由自带 PATCH(JSON Patch)与 PUT(整体替换),
|
||||
> diff 引擎按 body 形态分别处理;旧状态获取用 `fetch(gvk, name)`(`getJsonExtension` 已弃用)。
|
||||
|
||||
+3
-2
@@ -38,9 +38,9 @@ public class AuditLogCsvExporter {
|
||||
/** 每批查询条数。 */
|
||||
static final int EXPORT_BATCH_SIZE = 200;
|
||||
|
||||
/** CSV 列题头(与 UI 列表列对应)。 */
|
||||
/** CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要)。 */
|
||||
private static final String CSV_HEADER =
|
||||
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,结果,状态码,来源IP,User-Agent";
|
||||
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
|
||||
private static final DataBufferFactory BUFFER_FACTORY =
|
||||
DefaultDataBufferFactory.sharedInstance;
|
||||
@@ -111,6 +111,7 @@ public class AuditLogCsvExporter {
|
||||
escape(spec.getPath()),
|
||||
escape(OperationDescription.describe(
|
||||
spec.getMethod(), spec.getResourceType(), spec.getPath())),
|
||||
escape(ChangeDiffEngine.formatChanges(spec.getChanges())),
|
||||
escape(success ? "成功" : "失败"),
|
||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||
escape(spec.getRemoteIp()),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
@@ -41,6 +42,12 @@ public class AuditLogSpec {
|
||||
/** User-Agent。 */
|
||||
private String userAgent;
|
||||
|
||||
/**
|
||||
* 字段级变更列表(字段级变更 diff,产品设计 V2):仅成功的改/删/建操作且变更
|
||||
* 可捕获时落库;历史记录(升级前写入)与本项不可捕获时为 null。
|
||||
*/
|
||||
private List<ChangeEntry> changes;
|
||||
|
||||
/** 登录失败等无法确定操作者时的占位用户名。 */
|
||||
public static final String UNKNOWN_USERNAME = "unknown";
|
||||
}
|
||||
|
||||
+30
-6
@@ -1,6 +1,7 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -17,6 +18,9 @@ import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
* 失败静默降级为 warn 日志:不重试、不阻塞、不抛出(产品设计原则 4)。
|
||||
* 不引入内存队列:Extension 存储底层为响应式(R2DBC),连接池天然提供背压;
|
||||
* 若后续压测发现写入积压,在 Recorder 内部替换为有界队列 + worker,接口不变。
|
||||
*
|
||||
* <p>字段级变更(产品设计 V2):仅在操作成功(2xx)且 {@link ChangeCaptureManager}
|
||||
* 已捕获请求体/旧状态时,经 {@link ChangeDiffEngine} 计算 {@code spec.changes} 落库。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -32,7 +36,8 @@ public class AuditRecorder {
|
||||
* <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值,
|
||||
* 此处为防御性兜底,保证审计设置故障不影响捕获链路。
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
@@ -40,18 +45,19 @@ public class AuditRecorder {
|
||||
snapshot.getMethod(), snapshot.getFullPath());
|
||||
return;
|
||||
}
|
||||
write(snapshot, statusCode, username);
|
||||
write(snapshot, capture, statusCode, username);
|
||||
},
|
||||
e -> {
|
||||
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
write(snapshot, statusCode, username);
|
||||
write(snapshot, capture, statusCode, username);
|
||||
});
|
||||
}
|
||||
|
||||
private void write(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username) {
|
||||
try {
|
||||
var auditLog = assemble(snapshot, statusCode, username);
|
||||
var auditLog = assemble(snapshot, capture, statusCode, username);
|
||||
client.create(auditLog)
|
||||
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e));
|
||||
@@ -62,7 +68,8 @@ public class AuditRecorder {
|
||||
}
|
||||
}
|
||||
|
||||
private AuditLog assemble(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
|
||||
String username) {
|
||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||
|
||||
var spec = new AuditLogSpec();
|
||||
@@ -77,6 +84,7 @@ public class AuditRecorder {
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||
spec.setUserAgent(snapshot.getUserAgent());
|
||||
spec.setChanges(changesOf(snapshot, capture, statusCode));
|
||||
|
||||
var metadata = new Metadata();
|
||||
metadata.setName("auditlog-" + UUID.randomUUID());
|
||||
@@ -87,4 +95,20 @@ public class AuditRecorder {
|
||||
auditLog.setSpec(spec);
|
||||
return auditLog;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段级变更(产品设计 V2):仅成功操作(2xx,此时资源已实际变更)落库 diff;
|
||||
* 失败请求、未捕获变更上下文(capture 为 null 或 body/旧状态缺失)不记。
|
||||
*/
|
||||
private static List<ChangeEntry> changesOf(RequestSnapshot snapshot, ChangeCapture capture,
|
||||
Integer statusCode) {
|
||||
if (statusCode == null || statusCode < 200 || statusCode >= 300) {
|
||||
return null;
|
||||
}
|
||||
if (capture == null) {
|
||||
return null;
|
||||
}
|
||||
return ChangeDiffEngine.compute(snapshot.getMethod(), capture.getOldNode(),
|
||||
capture.getBodyNode());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 请求期捕获的字段变更上下文(产品设计 V2"字段级变更 diff")。
|
||||
*
|
||||
* <p>由 {@link ChangeCaptureManager} 在请求期填充:请求体 JSON 与(改/删时的)
|
||||
* 写入前资源状态;响应完成后由 {@link AuditRecorder} 据此计算 diff 落库。
|
||||
* 每请求一个实例,写入与读取位于不同的响应式线程,字段用 volatile 保证可见性。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public final class ChangeCapture {
|
||||
|
||||
/** 请求体解析出的 JSON;未缓存(非 JSON/空/超限)时为 null。 */
|
||||
private volatile JsonNode bodyNode;
|
||||
|
||||
/** 写入前的资源状态 JSON;POST 或获取失败时为 null。 */
|
||||
private volatile JsonNode oldNode;
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static run.halo.operationaudit.audit.CaptureRule.APIS_PREFIX;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.WRITE_METHODS;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.isAuthEndpoint;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.Unstructured;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettingProvider;
|
||||
|
||||
/**
|
||||
* 字段级变更捕获(产品设计 V2"字段级变更 diff"):
|
||||
* 在请求期缓存 JSON 请求体,并在改/删操作落库前抓取写入前的资源状态,
|
||||
* 供 {@link AuditRecorder} 在响应成功后计算字段级 diff。
|
||||
*
|
||||
* <p>捕获条件({@link #eligible}):{@code /apis/**} 写操作(登录端点排除);
|
||||
* 设置开关({@code recordChanges},随审计总开关)关闭时不捕获。其中请求体仅在
|
||||
* JSON 内容类型且大小可控时缓存(改/删的旧状态不依赖请求体,DELETE 无请求体也可抓取)。
|
||||
*
|
||||
* <p>安全边界:请求体经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存
|
||||
* (分块传输/超限/非 JSON 一律不缓存,仅记操作元信息),绝不中断流式请求;
|
||||
* 旧状态经 {@code fetch(gvk, name)} 原始 JSON 获取,失败静默跳过 diff。
|
||||
* 整个捕获过程任何异常均降级为"不记变更",不影响业务主流程(设计原则 4)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ChangeCaptureManager {
|
||||
|
||||
/** 请求体缓存上限(字节):超过不缓存、不记录字段变更。 */
|
||||
static final int MAX_BODY_BYTES = 256 * 1024;
|
||||
|
||||
private final AuditSettingProvider settingProvider;
|
||||
private final SchemeManager schemeManager;
|
||||
private final ReactiveExtensionClient client;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 捕获变更上下文,返回(可能包装了缓存请求体的)交换对象供后续链路继续处理。
|
||||
* 返回的 Mono 永不报错、永不为空:任何失败均回退原 exchange(仅不记字段变更)。
|
||||
*/
|
||||
public Mono<ServerWebExchange> prepare(ServerWebExchange exchange, RequestSnapshot snapshot,
|
||||
ChangeCapture capture) {
|
||||
if (!eligible(snapshot)) {
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
return settingProvider.get()
|
||||
.flatMap(settings -> {
|
||||
if (!settings.enabledOrDefault() || !settings.recordChangesOrDefault()) {
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
return captureContext(exchange, snapshot, capture);
|
||||
})
|
||||
.onErrorResume(e -> {
|
||||
log.warn("Failed to capture change context for {} {}, skip field diff",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
return Mono.just(exchange);
|
||||
});
|
||||
}
|
||||
|
||||
/** 变更捕获适用性:{@code /apis/**} 写操作(登录端点排除)。 */
|
||||
static boolean eligible(RequestSnapshot snapshot) {
|
||||
var path = snapshot.getPath();
|
||||
if (isAuthEndpoint(path) || !path.startsWith(APIS_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
return WRITE_METHODS.contains(snapshot.getMethod());
|
||||
}
|
||||
|
||||
/** application/json 或 application/*+json(含 merge-patch+json)。 */
|
||||
static boolean isJson(MediaType contentType) {
|
||||
if (contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
|
||||
return true;
|
||||
}
|
||||
var subtype = contentType.getSubtype();
|
||||
return subtype != null && subtype.toLowerCase(java.util.Locale.ROOT).endsWith("+json");
|
||||
}
|
||||
|
||||
private Mono<ServerWebExchange> captureContext(ServerWebExchange exchange,
|
||||
RequestSnapshot snapshot, ChangeCapture capture) {
|
||||
var contentType = exchange.getRequest().getHeaders().getContentType();
|
||||
var jsonBody = contentType != null && isJson(contentType);
|
||||
var prepared = jsonBody ? cacheBody(exchange, capture) : Mono.just(exchange);
|
||||
return prepared.flatMap(decorated -> {
|
||||
if (needsOldState(snapshot.getMethod(), jsonBody)) {
|
||||
return fetchOldState(snapshot, capture).thenReturn(decorated);
|
||||
}
|
||||
return Mono.just(decorated);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否需要写入前状态:DELETE 无请求体(记录被删内容);PUT/PATCH 仅在 JSON
|
||||
* 请求体可缓存时才有 diff 意义;POST(新建)无旧值。
|
||||
*/
|
||||
private static boolean needsOldState(String method, boolean jsonBody) {
|
||||
return switch (method) {
|
||||
case "DELETE" -> true;
|
||||
case "PUT", "PATCH" -> jsonBody;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存 JSON 请求体并返回装饰后的 exchange(下游可重复读 body);仅在调用方已判定
|
||||
* 请求体为 JSON 时进入。无 Content-Length(分块传输)或超限:不缓存,避免中断流式请求。
|
||||
*/
|
||||
private Mono<ServerWebExchange> cacheBody(ServerWebExchange exchange, ChangeCapture capture) {
|
||||
var request = exchange.getRequest();
|
||||
var contentLength = request.getHeaders().getContentLength();
|
||||
if (contentLength <= 0 || contentLength > MAX_BODY_BYTES) {
|
||||
return Mono.just(exchange);
|
||||
}
|
||||
return DataBufferUtils.join(request.getBody(), MAX_BODY_BYTES)
|
||||
.map(joined -> {
|
||||
var bytes = new byte[joined.readableByteCount()];
|
||||
joined.read(bytes);
|
||||
DataBufferUtils.release(joined);
|
||||
capture.setBodyNode(parseJson(bytes));
|
||||
return decorate(exchange, bytes);
|
||||
})
|
||||
.defaultIfEmpty(exchange);
|
||||
}
|
||||
|
||||
private JsonNode parseJson(byte[] bytes) {
|
||||
try {
|
||||
return objectMapper.readTree(bytes);
|
||||
} catch (java.io.IOException e) {
|
||||
// 非 JSON 内容或超限(StreamReadConstraints):不记字段变更,不影响记录
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游 handler 可正常读取。 */
|
||||
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
|
||||
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
|
||||
@Override
|
||||
public Flux<DataBuffer> getBody() {
|
||||
return Flux.defer(
|
||||
() -> Mono.just(exchange.getResponse().bufferFactory().wrap(body)));
|
||||
}
|
||||
};
|
||||
return exchange.mutate().request(decorated).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 改/删操作在落库前抓取写入前的资源状态;POST(新建)无旧值。
|
||||
* 仅当路径可解析出资源名且模型已注册(可定位 GVK)时获取,失败静默跳过。
|
||||
*/
|
||||
private Mono<Void> fetchOldState(RequestSnapshot snapshot, ChangeCapture capture) {
|
||||
var method = snapshot.getMethod();
|
||||
if (!"PUT".equals(method) && !"PATCH".equals(method) && !"DELETE".equals(method)) {
|
||||
return Mono.empty();
|
||||
}
|
||||
var target = resolveTarget(snapshot.getPath());
|
||||
if (target == null) {
|
||||
return Mono.empty();
|
||||
}
|
||||
// defer 包裹组装期与订阅期:client 异常(含极端情况下返回 null)一并静默降级
|
||||
return Mono.defer(() -> client.fetch(target.gvk(), target.name())
|
||||
.map(ChangeCaptureManager::toOldStateNode)
|
||||
.doOnNext(capture::setOldNode))
|
||||
.onErrorResume(e -> {
|
||||
log.debug("Failed to fetch old state for {} {}, skip field diff",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.then();
|
||||
}
|
||||
|
||||
/** Unstructured → 完整资源 JSON 树(含自定义序列化器,往返无损)。 */
|
||||
private static JsonNode toOldStateNode(Unstructured unstructured) {
|
||||
return Unstructured.OBJECT_MAPPER.valueToTree(unstructured);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从路径解析旧状态获取目标:{@code /apis/{group}/{version}/{plural}/{name}}。
|
||||
* 经 SchemeManager 将 plural 映射为 GVK;未注册的模型(含非 Extension 的
|
||||
* 自定义端点)返回 null,不获取。
|
||||
*/
|
||||
private OldStateTarget resolveTarget(String path) {
|
||||
var parts = path.split("/");
|
||||
if (parts.length < 6 || parts[5].isBlank()) {
|
||||
return null;
|
||||
}
|
||||
var group = parts[2];
|
||||
var version = parts[3];
|
||||
var plural = parts[4];
|
||||
var gvk = schemeManager.schemes().stream()
|
||||
.filter(scheme -> matches(scheme, group, version, plural))
|
||||
.map(Scheme::groupVersionKind)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
return gvk == null ? null : new OldStateTarget(gvk, parts[5]);
|
||||
}
|
||||
|
||||
private static boolean matches(Scheme scheme, String group, String version, String plural) {
|
||||
var gvk = scheme.groupVersionKind();
|
||||
return gvk.group().equals(group) && gvk.version().equals(version)
|
||||
&& scheme.plural().equals(plural);
|
||||
}
|
||||
|
||||
/** 旧状态获取目标:GVK + 资源名。 */
|
||||
private record OldStateTarget(GroupVersionKind gvk, String name) {
|
||||
}
|
||||
}
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 字段级变更 diff(纯函数,产品设计 V2"字段级变更 diff")。
|
||||
*
|
||||
* <p>输入为写入前的资源状态(存储原始 JSON,可空)与请求体 JSON(可空),
|
||||
* 按 HTTP 方法取语义:
|
||||
*
|
||||
* <table>
|
||||
* <caption>方法 → diff 语义</caption>
|
||||
* <tr><th>方法</th><th>语义</th></tr>
|
||||
* <tr><td>PUT</td><td>整体替换:新增 / 修改 / 删除全量计算</td></tr>
|
||||
* <tr><td>PATCH(数组 body)</td><td>JSON Patch(RFC 6902 ops,Halo 扩展路由的标准 PATCH):按 op 与 JSON Pointer 展开</td></tr>
|
||||
* <tr><td>PATCH(对象 body)</td><td>JSON Merge Patch:仅比较 body 中出现的字段,显式 null 视为删除该字段</td></tr>
|
||||
* <tr><td>POST</td><td>新建:所有字段记为新增(oldNode 忽略)</td></tr>
|
||||
* <tr><td>DELETE</td><td>删除:所有字段记为移除(newNode 忽略)</td></tr>
|
||||
* </table>
|
||||
*
|
||||
* <p>范围与降噪:只比较用户可写面——根级跳过 {@code apiVersion/kind/status},
|
||||
* {@code metadata} 仅保留 {@code name/labels/annotations}(version/managedFields/时间戳等
|
||||
* 服务端管理字段不参与);数组与超深子树作为整体叶子比较。
|
||||
* 输出经脱敏(敏感字段名)、截断(单值 200 字符)与封顶(30 条,超出以汇总条兜底)。
|
||||
*/
|
||||
final class ChangeDiffEngine {
|
||||
|
||||
/** 单条记录最多记录的变更条数(超出部分以汇总条兜底,保证完整性可感知)。 */
|
||||
static final int MAX_CHANGES = 30;
|
||||
|
||||
/** 单个字段值的最大记录长度,超出截断。 */
|
||||
static final int MAX_VALUE_LENGTH = 200;
|
||||
|
||||
/** 截断标记。 */
|
||||
static final String TRUNCATION_SUFFIX = "…(截断)";
|
||||
|
||||
/** 敏感字段的脱敏值。 */
|
||||
static final String REDACTED_VALUE = "******";
|
||||
|
||||
/** 对象递归比较的最大深度,超过视为叶子整体比较(防超深构造)。 */
|
||||
private static final int MAX_DEPTH = 16;
|
||||
|
||||
/** 敏感字段名片段:字段路径任一段命中即脱敏,避免密码/密钥明文落库。 */
|
||||
private static final Pattern SENSITIVE_FIELD =
|
||||
Pattern.compile("(?i)password|passwd|secret|token|credential");
|
||||
|
||||
/** 根级不参与 diff 的键:apiVersion/kind 恒定,status 由服务端管理。 */
|
||||
private static final Set<String> ROOT_SKIPPED_KEYS = Set.of("apiVersion", "kind", "status");
|
||||
|
||||
/** metadata 仅保留用户可写子键,其余(version/managedFields/时间戳等)为服务端管理。 */
|
||||
private static final Set<String> METADATA_INCLUDED_KEYS =
|
||||
Set.of("name", "labels", "annotations");
|
||||
|
||||
/** 汇总兜底条的字段名。 */
|
||||
static final String OVERFLOW_FIELD = "…";
|
||||
|
||||
/** 单侧整体缺失(新增/删除整棵子树)且另一侧非对象时,叶子条目的字段占位名。 */
|
||||
private static final String ROOT_PLACEHOLDER_FIELD = "(请求体)";
|
||||
|
||||
private ChangeDiffEngine() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算字段级变更列表。
|
||||
*
|
||||
* @param method HTTP 方法;仅 PUT/PATCH/POST/DELETE 参与计算
|
||||
* @param oldNode 写入前资源状态(POST 传 null);获取失败时 PUT/PATCH/DELETE 不计算
|
||||
* @param newNode 请求体 JSON(DELETE 传 null);缺失或非 JSON 不计算
|
||||
* @return 变更列表;无变更或无法计算返回 null(不落库 changes 字段)
|
||||
*/
|
||||
static List<ChangeEntry> compute(String method, JsonNode oldNode, JsonNode newNode) {
|
||||
var missing = MissingNode.getInstance();
|
||||
return switch (method == null ? "" : method) {
|
||||
case "POST" -> newNode == null ? null : diffTree(missing, newNode, true);
|
||||
case "DELETE" -> oldNode == null ? null : diffTree(oldNode, missing, true);
|
||||
case "PUT" ->
|
||||
(oldNode == null || newNode == null) ? null : diffTree(oldNode, newNode, true);
|
||||
// PATCH 两种形态:JSON Patch(RFC 6902 ops 数组,Halo 扩展路由的标准 PATCH)
|
||||
// 与 JSON Merge Patch(对象 body,仅比较 body 中出现的字段)
|
||||
case "PATCH" -> {
|
||||
if (oldNode == null || newNode == null) {
|
||||
yield null;
|
||||
}
|
||||
yield newNode.isArray()
|
||||
? capChanges(jsonPatchEntries(oldNode, newNode))
|
||||
: diffTree(oldNode, newNode, false);
|
||||
}
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON Patch(RFC 6902)ops 数组 → 变更条目:replace/add 按 JSON Pointer 查旧值判定
|
||||
* 新增或修改,remove 记录被删原值;move/copy/test 等少见操作整条 op 落库兜底。
|
||||
*/
|
||||
private static List<ChangeEntry> jsonPatchEntries(JsonNode oldNode, JsonNode patchOps) {
|
||||
var changes = new ArrayList<ChangeEntry>();
|
||||
for (var op : patchOps) {
|
||||
var pointer = op.path("path").asText("");
|
||||
var field = pointer.isEmpty() ? ROOT_PLACEHOLDER_FIELD
|
||||
: pointerToField(pointer);
|
||||
var opType = op.path("op").asText("");
|
||||
switch (opType) {
|
||||
case "replace", "add" -> {
|
||||
var oldValue = oldNode.at(pointer);
|
||||
var missingOld = oldValue.isMissingNode();
|
||||
addEntry(changes, field, missingOld ? ChangeType.ADDED : ChangeType.UPDATED,
|
||||
missingOld ? null : oldValue, op.get("value"));
|
||||
}
|
||||
case "remove" -> {
|
||||
var oldValue = oldNode.at(pointer);
|
||||
if (oldValue.isMissingNode()) {
|
||||
continue;
|
||||
}
|
||||
addEntry(changes, field, ChangeType.REMOVED, oldValue, null);
|
||||
}
|
||||
default ->
|
||||
// move/copy/test 等少见操作:整条 op 作为兜底记录
|
||||
addEntry(changes, field, ChangeType.UPDATED, null, op);
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
/** JSON Pointer({@code /spec/title},含 ~0/~1 转义)→ 字段路径({@code spec.title})。 */
|
||||
private static String pointerToField(String pointer) {
|
||||
var segments = new ArrayList<String>();
|
||||
for (var segment : pointer.substring(1).split("/", -1)) {
|
||||
segments.add(segment.replace("~1", "/").replace("~0", "~"));
|
||||
}
|
||||
return String.join(".", segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* 变更列表的紧凑中文摘要(导出 CSV"变更"列用):如
|
||||
* {@code 修改 spec.title:旧值 → 新值;新增 spec.cover:x;删除 spec.slug:y}。
|
||||
*/
|
||||
static String formatChanges(List<ChangeEntry> changes) {
|
||||
if (changes == null || changes.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return changes.stream()
|
||||
.map(ChangeDiffEngine::formatChange)
|
||||
.collect(Collectors.joining(";"));
|
||||
}
|
||||
|
||||
private static String formatChange(ChangeEntry change) {
|
||||
var field = change.getField();
|
||||
if (OVERFLOW_FIELD.equals(field)) {
|
||||
// 汇总兜底条:newValue 即说明文本
|
||||
return orDash(change.getNewValue());
|
||||
}
|
||||
return switch (change.getChangeType()) {
|
||||
case ADDED -> "新增 " + field + ":" + orDash(change.getNewValue());
|
||||
case UPDATED -> "修改 " + field + ":" + orDash(change.getOldValue())
|
||||
+ " → " + orDash(change.getNewValue());
|
||||
case REMOVED -> "删除 " + field + ":" + orDash(change.getOldValue());
|
||||
};
|
||||
}
|
||||
|
||||
private static String orDash(String value) {
|
||||
return value == null || value.isEmpty() ? "-" : value;
|
||||
}
|
||||
|
||||
private static List<ChangeEntry> diffTree(JsonNode oldNode, JsonNode newNode,
|
||||
boolean removalsEnabled) {
|
||||
var changes = new ArrayList<ChangeEntry>();
|
||||
collectChanges("", oldNode, newNode, removalsEnabled, 0, changes);
|
||||
if (changes.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return capChanges(changes);
|
||||
}
|
||||
|
||||
/** 条数封顶:超出 {@value #MAX_CHANGES} 条时截断并追加汇总条。 */
|
||||
private static List<ChangeEntry> capChanges(List<ChangeEntry> changes) {
|
||||
if (changes.size() <= MAX_CHANGES) {
|
||||
return changes;
|
||||
}
|
||||
var capped = new ArrayList<ChangeEntry>(changes.subList(0, MAX_CHANGES));
|
||||
var summary = new ChangeEntry();
|
||||
summary.setField(OVERFLOW_FIELD);
|
||||
summary.setChangeType(ChangeType.UPDATED);
|
||||
summary.setNewValue("变更过多,仅记录前 " + MAX_CHANGES + " 处(共 "
|
||||
+ changes.size() + " 处)");
|
||||
capped.add(summary);
|
||||
return capped;
|
||||
}
|
||||
|
||||
private static void collectChanges(String path, JsonNode oldNode, JsonNode newNode,
|
||||
boolean removalsEnabled, int depth, List<ChangeEntry> out) {
|
||||
// 对象(或单侧缺失)逐字段比较;缺失侧交由 collectObjectChanges 展开 ADDED/REMOVED
|
||||
if (depth < MAX_DEPTH && isContainerOrAbsent(oldNode) && isContainerOrAbsent(newNode)) {
|
||||
collectObjectChanges(path, oldNode, newNode, removalsEnabled, depth, out);
|
||||
return;
|
||||
}
|
||||
// 数组 / 标量 / 类型变更 / 超深子树:整体叶子比较
|
||||
if (oldNode.equals(newNode)) {
|
||||
return;
|
||||
}
|
||||
addEntry(out, path, ChangeType.UPDATED, oldNode, newNode);
|
||||
}
|
||||
|
||||
private static boolean isContainerOrAbsent(JsonNode node) {
|
||||
return node.isObject() || node.isMissingNode();
|
||||
}
|
||||
|
||||
private static void collectObjectChanges(String path, JsonNode oldNode, JsonNode newNode,
|
||||
boolean removalsEnabled, int depth, List<ChangeEntry> out) {
|
||||
// 顺序:先 body 侧(新状态)后旧侧独有(被删除)字段,展示顺序贴近最终状态
|
||||
var keys = new LinkedHashSet<String>();
|
||||
newNode.fieldNames().forEachRemaining(keys::add);
|
||||
oldNode.fieldNames().forEachRemaining(keys::add);
|
||||
|
||||
for (var key : keys) {
|
||||
if (path.isEmpty() && ROOT_SKIPPED_KEYS.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
var childPath = path.isEmpty() ? key : path + "." + key;
|
||||
var oldValue = fieldOf(oldNode, key);
|
||||
var newValue = fieldOf(newNode, key);
|
||||
|
||||
if (oldValue.isMissingNode() && newValue.isMissingNode()) {
|
||||
continue;
|
||||
}
|
||||
if (oldValue.isMissingNode()) {
|
||||
// 显式 null 等同未设置:无实际变化
|
||||
if (newValue.isNull()) {
|
||||
continue;
|
||||
}
|
||||
expandAdded(childPath, newValue, depth + 1, out);
|
||||
continue;
|
||||
}
|
||||
if (newValue.isMissingNode()) {
|
||||
// PATCH(merge patch)语义:body 未携带的字段视为未变更;null 旧值等同未设置
|
||||
if (!removalsEnabled || oldValue.isNull()) {
|
||||
continue;
|
||||
}
|
||||
expandRemoved(childPath, oldValue, depth + 1, out);
|
||||
continue;
|
||||
}
|
||||
if (newValue.isNull() || oldValue.isNull()) {
|
||||
collectNullishChange(childPath, oldValue, newValue, removalsEnabled, depth, out);
|
||||
continue;
|
||||
}
|
||||
if (oldValue.isObject() && newValue.isObject()) {
|
||||
// 进入根级 metadata 时过滤服务端管理子键
|
||||
if (path.isEmpty() && "metadata".equals(key)) {
|
||||
oldValue = filterMetadata(oldValue);
|
||||
newValue = filterMetadata(newValue);
|
||||
}
|
||||
collectChanges(childPath, oldValue, newValue, removalsEnabled, depth + 1, out);
|
||||
continue;
|
||||
}
|
||||
// 数组 / 标量 / 类型变更:整体叶子比较
|
||||
if (!oldValue.equals(newValue)) {
|
||||
addEntry(out, childPath, ChangeType.UPDATED, oldValue, newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 两侧存在显式 null 的比较:PUT 视为置空(修改),PATCH 视为删除该字段。 */
|
||||
private static void collectNullishChange(String childPath, JsonNode oldValue,
|
||||
JsonNode newValue, boolean removalsEnabled, int depth, List<ChangeEntry> out) {
|
||||
if (oldValue.isNull() && newValue.isNull()) {
|
||||
return;
|
||||
}
|
||||
if (newValue.isNull()) {
|
||||
var type = removalsEnabled ? ChangeType.UPDATED : ChangeType.REMOVED;
|
||||
addEntry(out, childPath, type, oldValue, removalsEnabled ? newValue : null);
|
||||
return;
|
||||
}
|
||||
expandAdded(childPath, newValue, depth + 1, out);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单侧新增的子树展开:对象逐字段展开为 ADDED(含根级噪音键与 metadata 服务端子键
|
||||
* 过滤),数组/标量为一条叶子条目;显式 null 视为未设置,跳过。
|
||||
*/
|
||||
private static void expandAdded(String path, JsonNode node, int depth,
|
||||
List<ChangeEntry> out) {
|
||||
if (!node.isObject() || depth >= MAX_DEPTH) {
|
||||
addEntry(out, path, ChangeType.ADDED, null, node);
|
||||
return;
|
||||
}
|
||||
var keys = new LinkedHashSet<String>();
|
||||
node.fieldNames().forEachRemaining(keys::add);
|
||||
for (var key : keys) {
|
||||
if (path.isEmpty() && ROOT_SKIPPED_KEYS.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
var childPath = path.isEmpty() ? key : path + "." + key;
|
||||
var value = node.get(key);
|
||||
if (value.isNull()) {
|
||||
continue;
|
||||
}
|
||||
if (path.isEmpty() && "metadata".equals(key)) {
|
||||
value = filterMetadata(value);
|
||||
}
|
||||
expandAdded(childPath, value, depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** 单侧移除的子树展开:与 {@link #expandAdded} 对称,展开为 REMOVED。 */
|
||||
private static void expandRemoved(String path, JsonNode node, int depth,
|
||||
List<ChangeEntry> out) {
|
||||
if (!node.isObject() || depth >= MAX_DEPTH) {
|
||||
addEntry(out, path, ChangeType.REMOVED, node, null);
|
||||
return;
|
||||
}
|
||||
var keys = new LinkedHashSet<String>();
|
||||
node.fieldNames().forEachRemaining(keys::add);
|
||||
for (var key : keys) {
|
||||
if (path.isEmpty() && ROOT_SKIPPED_KEYS.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
var childPath = path.isEmpty() ? key : path + "." + key;
|
||||
var value = node.get(key);
|
||||
if (value.isNull()) {
|
||||
continue;
|
||||
}
|
||||
if (path.isEmpty() && "metadata".equals(key)) {
|
||||
value = filterMetadata(value);
|
||||
}
|
||||
expandRemoved(childPath, value, depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** 过滤 metadata 节点:仅保留用户可写子键;非对象原样返回(交由叶子比较)。 */
|
||||
private static JsonNode filterMetadata(JsonNode metadata) {
|
||||
if (!metadata.isObject()) {
|
||||
return metadata;
|
||||
}
|
||||
var filtered = JsonNodeFactory.instance.objectNode();
|
||||
METADATA_INCLUDED_KEYS.forEach(key -> {
|
||||
var value = metadata.get(key);
|
||||
if (value != null) {
|
||||
filtered.set(key, value);
|
||||
}
|
||||
});
|
||||
return filtered;
|
||||
}
|
||||
|
||||
private static JsonNode fieldOf(JsonNode node, String key) {
|
||||
var value = node.get(key);
|
||||
return value == null ? MissingNode.getInstance() : value;
|
||||
}
|
||||
|
||||
private static void addEntry(List<ChangeEntry> out, String field, ChangeType type,
|
||||
JsonNode oldValue, JsonNode newValue) {
|
||||
var resolvedField = field.isEmpty() ? ROOT_PLACEHOLDER_FIELD : field;
|
||||
var sensitive = isSensitiveField(resolvedField);
|
||||
var entry = new ChangeEntry();
|
||||
entry.setField(resolvedField);
|
||||
entry.setChangeType(type);
|
||||
entry.setOldValue(oldValue == null ? null : formatValue(oldValue, sensitive));
|
||||
entry.setNewValue(newValue == null ? null : formatValue(newValue, sensitive));
|
||||
out.add(entry);
|
||||
}
|
||||
|
||||
/** 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。 */
|
||||
private static boolean isSensitiveField(String field) {
|
||||
for (var segment : field.split("\\.")) {
|
||||
if (SENSITIVE_FIELD.matcher(segment).find()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 标量取原文,对象/数组序列化为紧凑 JSON;统一脱敏与截断。 */
|
||||
private static String formatValue(JsonNode value, boolean sensitive) {
|
||||
if (sensitive) {
|
||||
return REDACTED_VALUE;
|
||||
}
|
||||
var text = value.isValueNode() ? value.asText() : value.toString();
|
||||
if (text.length() > MAX_VALUE_LENGTH) {
|
||||
return text.substring(0, MAX_VALUE_LENGTH) + TRUNCATION_SUFFIX;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 字段级变更条目({@code spec.changes} 的元素,产品设计 V2"字段级变更 diff")。
|
||||
*
|
||||
* <p>oldValue/newValue 均为格式化后的字符串(JSON 子树序列化或标量原文),
|
||||
* 传入前已经脱敏与截断;缺失侧为 null(如 ADDED 无 oldValue)。
|
||||
*/
|
||||
@Data
|
||||
public class ChangeEntry {
|
||||
|
||||
/** 字段路径(点号分隔,如 {@code spec.title}、{@code metadata.labels})。 */
|
||||
private String field;
|
||||
|
||||
/** 变更类型。 */
|
||||
private ChangeType changeType;
|
||||
|
||||
/** 变更前的值;字段为新增时为 null。 */
|
||||
private String oldValue;
|
||||
|
||||
/** 变更后的值;字段被移除时为 null。 */
|
||||
private String newValue;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
/**
|
||||
* 字段级变更类型(产品设计 V2"字段级变更 diff")。
|
||||
*/
|
||||
public enum ChangeType {
|
||||
|
||||
/** 新增字段(新建资源或 PUT 补充字段)。 */
|
||||
ADDED,
|
||||
|
||||
/** 字段值修改。 */
|
||||
UPDATED,
|
||||
|
||||
/** 字段被移除(PUT 删除字段、PATCH 显式置 null、资源删除)。 */
|
||||
REMOVED
|
||||
}
|
||||
+8
-2
@@ -24,6 +24,9 @@ import run.halo.app.security.AfterSecurityWebFilter;
|
||||
* 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。
|
||||
* 上下文中的值是 {@code Mono<SecurityContext>}(由 ReactorContextWebFilter 写入),
|
||||
* 可独立订阅,因此记录时再解析操作者。
|
||||
*
|
||||
* <p>字段级变更(产品设计 V2):调用 {@link ChangeCaptureManager} 在请求期缓存 JSON
|
||||
* 请求体并抓取写入前状态(失败静默回退原 exchange),响应成功后随记录落库 diff。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@@ -33,6 +36,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
private static final String ANONYMOUS_USER = "anonymousUser";
|
||||
|
||||
private final AuditRecorder recorder;
|
||||
private final ChangeCaptureManager captureManager;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
@@ -42,12 +46,14 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
return chain.filter(exchange)
|
||||
var capture = new ChangeCapture();
|
||||
return captureManager.prepare(exchange, snapshot, capture)
|
||||
.flatMap(prepared -> chain.filter(prepared))
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> operatorOf(ctx, path).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
recorder.record(snapshot, statusOf(exchange), username);
|
||||
recorder.record(snapshot, capture, statusOf(exchange), username);
|
||||
}
|
||||
},
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ })));
|
||||
|
||||
+9
-2
@@ -5,7 +5,7 @@ package run.halo.operationaudit.housekeeping;
|
||||
*
|
||||
* <p>取值全部经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值。
|
||||
*/
|
||||
public record AuditSettings(Boolean enabled, Integer retentionDays) {
|
||||
public record AuditSettings(Boolean enabled, Integer retentionDays, Boolean recordChanges) {
|
||||
|
||||
/** ConfigMap 中的配置组名。 */
|
||||
public static final String GROUP = "audit";
|
||||
@@ -19,6 +19,9 @@ public record AuditSettings(Boolean enabled, Integer retentionDays) {
|
||||
/** 审计开关默认值。 */
|
||||
public static final boolean DEFAULT_ENABLED = true;
|
||||
|
||||
/** 字段级变更记录默认值(字段级变更 diff,产品设计 V2)。 */
|
||||
public static final boolean DEFAULT_RECORD_CHANGES = true;
|
||||
|
||||
public boolean enabledOrDefault() {
|
||||
return enabled == null ? DEFAULT_ENABLED : enabled;
|
||||
}
|
||||
@@ -30,7 +33,11 @@ public record AuditSettings(Boolean enabled, Integer retentionDays) {
|
||||
return retentionDays;
|
||||
}
|
||||
|
||||
public boolean recordChangesOrDefault() {
|
||||
return recordChanges == null ? DEFAULT_RECORD_CHANGES : recordChanges;
|
||||
}
|
||||
|
||||
public static AuditSettings defaults() {
|
||||
return new AuditSettings(DEFAULT_ENABLED, DEFAULT_RETENTION_DAYS);
|
||||
return new AuditSettings(DEFAULT_ENABLED, DEFAULT_RETENTION_DAYS, DEFAULT_RECORD_CHANGES);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,11 @@ spec:
|
||||
name: enabled
|
||||
value: true
|
||||
help: 关闭后不再记录新的操作审计日志,已有记录仍可查询
|
||||
- $formkit: checkbox
|
||||
label: 记录字段变更
|
||||
name: recordChanges
|
||||
value: true
|
||||
help: 对成功的新建/修改/删除操作记录字段级新旧值(敏感字段自动脱敏),关闭后仅记录操作元信息
|
||||
- $formkit: number
|
||||
label: 保留天数
|
||||
name: retentionDays
|
||||
|
||||
+34
-5
@@ -39,7 +39,7 @@ class AuditExportEndpointTest {
|
||||
"/apis/" + AuditLog.GROUP + "/v1alpha1/auditlogs/-/export";
|
||||
|
||||
private static final String CSV_HEADER =
|
||||
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,结果,状态码,来源IP,User-Agent";
|
||||
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
|
||||
|
||||
private ReactiveExtensionClient client;
|
||||
private WebTestClient webClient;
|
||||
@@ -107,9 +107,38 @@ class AuditExportEndpointTest {
|
||||
assertThat(lines).hasSize(3); // 表头 + 2 行数据(末尾 \r\n 切出的空串不进 split 前段)
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",admin,POST,users,zhangsan,/apis/api.console.halo.run/v1alpha1/users"
|
||||
+ ",新建用户,成功,201,127.0.0.1,Mozilla/5.0");
|
||||
+ ",新建用户,,成功,201,127.0.0.1,Mozilla/5.0");
|
||||
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
|
||||
+ ",unknown,POST,auth,,/login,登录,失败,401,10.0.0.8,Mozilla/5.0");
|
||||
+ ",unknown,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExportChangesColumnWhenRecordHasChanges() {
|
||||
var time = Instant.parse("2026-11-04T00:00:00Z");
|
||||
var log = auditLog("auditlog-1", time, "admin", "PUT", "posts", "abc",
|
||||
"/apis/content.halo.run/v1alpha1/posts/abc", 200, "127.0.0.1", "UA");
|
||||
log.getSpec().setChanges(List.of(
|
||||
change(ChangeType.UPDATED, "spec.title", "旧标题", "新标题"),
|
||||
change(ChangeType.ADDED, "spec.cover", null, "c.png")));
|
||||
stubSinglePage(List.of(log));
|
||||
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
|
||||
+ ",admin,PUT,posts,abc,/apis/content.halo.run/v1alpha1/posts/abc"
|
||||
+ ",修改文章,修改 spec.title:旧标题 → 新标题;新增 spec.cover:c.png"
|
||||
+ ",成功,200,127.0.0.1,UA");
|
||||
}
|
||||
|
||||
private static ChangeEntry change(ChangeType type, String field, String oldValue,
|
||||
String newValue) {
|
||||
var entry = new ChangeEntry();
|
||||
entry.setField(field);
|
||||
entry.setChangeType(type);
|
||||
entry.setOldValue(oldValue);
|
||||
entry.setNewValue(newValue);
|
||||
return entry;
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,7 +161,7 @@ class AuditExportEndpointTest {
|
||||
assertThat(lines).hasSize(2);
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-02T00:00:00Z"))
|
||||
+ ",\"a\"\"b\",PUT,posts,'=sum(A1),\"/apis/content.halo.run/v1alpha1/posts/x,y\""
|
||||
+ ",修改文章,成功,200,127.0.0.1,'@evil");
|
||||
+ ",修改文章,,成功,200,127.0.0.1,'@evil");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -144,7 +173,7 @@ class AuditExportEndpointTest {
|
||||
var body = exportAndGetBody(EXPORT_URI);
|
||||
var lines = body.split("\r\n");
|
||||
assertThat(lines[1]).isEqualTo(expectedTimeColumn(Instant.parse("2026-11-03T00:00:00Z"))
|
||||
+ ",admin,PATCH,themes,,,修改主题,失败,,,");
|
||||
+ ",admin,PATCH,themes,,,修改主题,,失败,,,");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+70
-7
@@ -8,6 +8,7 @@ import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -21,6 +22,7 @@ import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
|
||||
/**
|
||||
* 直写降级测试(技术方案 D2):成功直写、失败降级为 warn 且不抛出、开关关闭跳过(D6)。
|
||||
* 字段级变更(产品设计 V2):成功操作且已捕获上下文时落库 diff,失败/未捕获不落库。
|
||||
*/
|
||||
class AuditRecorderTest {
|
||||
|
||||
@@ -52,7 +54,7 @@ class AuditRecorderTest {
|
||||
.header("User-Agent", "UA-1")
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, 204, "admin");
|
||||
recorder.record(snapshot, new ChangeCapture(), 204, "admin");
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -75,7 +77,7 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
||||
recorder.record(snapshotOf("/login"), 401, null);
|
||||
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -90,7 +92,7 @@ class AuditRecorderTest {
|
||||
void shouldAnnotateSubActionSemanticAction() {
|
||||
recorder.record(RequestSnapshot.of(MockServerHttpRequest
|
||||
.put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish")
|
||||
.build()), 200, "admin");
|
||||
.build()), new ChangeCapture(), 200, "admin");
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -100,9 +102,11 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldSkipRecordingWhenAuditDisabled() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(false, 30)));
|
||||
when(settingProvider.get())
|
||||
.thenReturn(Mono.just(new AuditSettings(false, 30, null)));
|
||||
|
||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), 200, "admin");
|
||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
|
||||
200, "admin");
|
||||
|
||||
verify(client, never()).create(any(AuditLog.class));
|
||||
}
|
||||
@@ -112,7 +116,7 @@ class AuditRecorderTest {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
200, "admin")).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 200, "admin")).doesNotThrowAnyException();
|
||||
|
||||
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
||||
verify(client).create(any(AuditLog.class));
|
||||
@@ -124,6 +128,65 @@ class AuditRecorderTest {
|
||||
new IllegalStateException("storage unavailable")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
500, "admin")).doesNotThrowAnyException();
|
||||
new ChangeCapture(), 500, "admin")).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordChangesOnSuccessWhenCaptured() {
|
||||
var capture = new ChangeCapture();
|
||||
var mapper = new ObjectMapper();
|
||||
var oldNode = mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "旧标题")));
|
||||
var bodyNode = mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "新标题")));
|
||||
capture.setOldNode(oldNode);
|
||||
capture.setBodyNode(bodyNode);
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.put("http://localhost/apis/content.halo.run/v1alpha1/posts/abc")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 200, "admin");
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var changes = captor.getValue().getSpec().getChanges();
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(changes.get(0).getField()).isEqualTo("spec.title");
|
||||
assertThat(changes.get(0).getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(changes.get(0).getOldValue()).isEqualTo("旧标题");
|
||||
assertThat(changes.get(0).getNewValue()).isEqualTo("新标题");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotRecordChangesOnFailedRequest() {
|
||||
var capture = new ChangeCapture();
|
||||
var mapper = new ObjectMapper();
|
||||
capture.setOldNode(mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "旧"))));
|
||||
capture.setBodyNode(mapper.valueToTree(java.util.Map.of("spec",
|
||||
java.util.Map.of("title", "新"))));
|
||||
var snapshot = RequestSnapshot.of(MockServerHttpRequest
|
||||
.put("http://localhost/apis/content.halo.run/v1alpha1/posts/abc")
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, capture, 403, "admin");
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
// 失败请求资源未实际变更:不落库字段变更
|
||||
assertThat(captor.getValue().getSpec().getChanges()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotRecordChangesWhenContextMissing() {
|
||||
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
|
||||
new ChangeCapture(), 200, "admin");
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
// 未捕获请求体/旧状态(非 JSON、超限或获取失败):不落库字段变更
|
||||
assertThat(captor.getValue().getSpec().getChanges()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import run.halo.app.extension.GroupVersionKind;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.Unstructured;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettingProvider;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
|
||||
/**
|
||||
* 字段级变更捕获测试(产品设计 V2):请求体缓存与装饰(下游可重复读)、
|
||||
* 旧状态抓取(改/删且模型已注册)、设置开关降级与适用性判定。
|
||||
*/
|
||||
class ChangeCaptureManagerTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private AuditSettingProvider settingProvider;
|
||||
private SchemeManager schemeManager;
|
||||
private ReactiveExtensionClient client;
|
||||
private ChangeCaptureManager manager;
|
||||
|
||||
/**
|
||||
* 以 {@link AuditLog}(group 非空,group/version/plural 均由 Scheme 推导)
|
||||
* 作为测试目标模型。注意空 group 的核心模型走 /api/** 路径,本就不在捕获范围。
|
||||
*/
|
||||
private Scheme targetScheme;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
settingProvider = mock(AuditSettingProvider.class);
|
||||
schemeManager = mock(SchemeManager.class);
|
||||
client = mock(ReactiveExtensionClient.class);
|
||||
manager = new ChangeCaptureManager(settingProvider, schemeManager, client, MAPPER);
|
||||
targetScheme = Scheme.buildFromType(AuditLog.class);
|
||||
when(schemeManager.schemes()).thenReturn(java.util.List.of(targetScheme));
|
||||
when(settingProvider.get()).thenReturn(Mono.just(AuditSettings.defaults()));
|
||||
}
|
||||
|
||||
private String targetPath() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
return "/apis/" + gvk.group() + "/" + gvk.version() + "/" + targetScheme.plural();
|
||||
}
|
||||
|
||||
/** 经自定义反序列化器构造 Unstructured(与 Halo 存储读取路径一致)。 */
|
||||
private static Unstructured unstructured(String json) {
|
||||
try {
|
||||
return Unstructured.OBJECT_MAPPER.readValue(json, Unstructured.class);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 适用性判定 =====
|
||||
|
||||
@Test
|
||||
void shouldCaptureWritesOnApisPaths() {
|
||||
var jsonRequest = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(2)
|
||||
.body("{}");
|
||||
var mergePatchRequest = MockServerHttpRequest
|
||||
.patch("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.parseMediaType("application/merge-patch+json"))
|
||||
.contentLength(2)
|
||||
.body("{}");
|
||||
|
||||
// merge-patch+json 同样适用(PATCH 语义按 merge patch 处理)
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(jsonRequest))).isTrue();
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(mergePatchRequest))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureAuthEndpointsOrNonApisPaths() {
|
||||
var loginRequest = MockServerHttpRequest.post("http://localhost/login")
|
||||
.contentType(MediaType.APPLICATION_JSON).contentLength(2).body("{}");
|
||||
var webRequest = MockServerHttpRequest.put("http://localhost/web/other")
|
||||
.contentType(MediaType.APPLICATION_JSON).contentLength(2).body("{}");
|
||||
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(loginRequest))).isFalse();
|
||||
assertThat(ChangeCaptureManager.eligible(RequestSnapshot.of(webRequest))).isFalse();
|
||||
}
|
||||
|
||||
// ===== 设置开关降级 =====
|
||||
|
||||
@Test
|
||||
void shouldSkipCaptureWhenRecordChangesDisabled() {
|
||||
when(settingProvider.get())
|
||||
.thenReturn(Mono.just(new AuditSettings(true, 90, false)));
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(20)
|
||||
.body("{\"data\": {\"key\": \"v\"}}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
StepVerifier.create(manager.prepare(exchange, RequestSnapshot.of(request), capture))
|
||||
.expectNextMatches(prepared -> prepared == exchange)
|
||||
.verifyComplete();
|
||||
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToPassthroughWhenPrepareFails() {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(20)
|
||||
.body("{\"data\": {\"key\": \"v\"}}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
// 捕获失败降级为原 exchange:不抛错、不影响业务请求
|
||||
StepVerifier.create(manager.prepare(exchange, RequestSnapshot.of(request), capture))
|
||||
.expectNextMatches(prepared -> prepared == exchange)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
// ===== 请求体缓存与装饰 =====
|
||||
|
||||
@Test
|
||||
void shouldCacheJsonBodyAndKeepItReadableDownstream() {
|
||||
var body = "{\"data\": {\"key\": \"配置值\"}}";
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body);
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
when(client.fetch(any(GroupVersionKind.class), any())).thenReturn(Mono.just(
|
||||
unstructured("{\"metadata\": {\"name\": \"my-cm\"}}")));
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
assertThat(capture.getBodyNode()).isNotNull();
|
||||
assertThat(capture.getBodyNode().at("/data/key").asText()).isEqualTo("配置值");
|
||||
|
||||
// 装饰后的请求可重复读(每次订阅独立 buffer)
|
||||
assertThat(prepared).isNotSameAs(exchange);
|
||||
var first = prepared.getRequest().getBody()
|
||||
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
||||
.collectList().block();
|
||||
var second = prepared.getRequest().getBody()
|
||||
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
|
||||
.collectList().block();
|
||||
assertThat(first).containsExactly(body);
|
||||
assertThat(second).containsExactly(body);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipBodyAndOldStateForNonJsonPut() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.TEXT_PLAIN)
|
||||
.contentLength(10)
|
||||
.body("plain-text");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 非 JSON 请求体:PUT 的 body 与旧状态均无 diff 意义,全部跳过
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCacheBodyWithoutContentLength() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(Flux.just(DefaultDataBufferFactory.sharedInstance
|
||||
.wrap("{\"data\": {\"key\": \"v\"}}".getBytes(StandardCharsets.UTF_8))));
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 分块传输(无 Content-Length):不缓存,避免中断流式请求
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCacheOversizedBody() {
|
||||
var oversized = "a".repeat(ChangeCaptureManager.MAX_BODY_BYTES + 1);
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(oversized.length())
|
||||
.body(oversized);
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(capture.getBodyNode()).isNull();
|
||||
}
|
||||
|
||||
// ===== 旧状态抓取 =====
|
||||
|
||||
@Test
|
||||
void shouldFetchOldStateForPutOnRegisteredScheme() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
var body = "{\"data\": {\"key\": \"新\"}}";
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
|
||||
.body(body);
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
when(client.fetch(eq(gvk), eq("my-cm"))).thenReturn(Mono.just(
|
||||
unstructured("{\"metadata\": {\"name\": \"my-cm\"}, \"data\": {\"key\": \"旧\"}}")));
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
assertThat(capture.getOldNode()).isNotNull();
|
||||
assertThat(capture.getOldNode().at("/data/key").asText()).isEqualTo("旧");
|
||||
assertThat(capture.getBodyNode().at("/data/key").asText()).isEqualTo("新");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFetchOldStateForDeleteButNotPost() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
when(client.fetch(eq(gvk), eq("my-cm"))).thenReturn(Mono.just(
|
||||
unstructured("{\"metadata\": {\"name\": \"my-cm\"}, \"data\": {\"key\": \"旧\"}}")));
|
||||
|
||||
// DELETE:需要旧状态(记录被删内容)
|
||||
var deleteRequest = MockServerHttpRequest
|
||||
.delete("http://localhost" + targetPath() + "/my-cm").build();
|
||||
var deleteCapture = new ChangeCapture();
|
||||
manager.prepare(MockServerWebExchange.from(deleteRequest),
|
||||
RequestSnapshot.of(deleteRequest), deleteCapture).block();
|
||||
assertThat(deleteCapture.getOldNode()).isNotNull();
|
||||
assertThat(deleteCapture.getOldNode().at("/data/key").asText()).isEqualTo("旧");
|
||||
|
||||
// POST(新建集合资源):无旧状态
|
||||
var postRequest = MockServerHttpRequest
|
||||
.post("http://localhost" + targetPath())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\": {\"k\": \"v\"}}");
|
||||
var postCapture = new ChangeCapture();
|
||||
manager.prepare(MockServerWebExchange.from(postRequest),
|
||||
RequestSnapshot.of(postRequest), postCapture).block();
|
||||
assertThat(postCapture.getOldNode()).isNull();
|
||||
|
||||
// 仅 DELETE 抓了一次旧状态
|
||||
verify(client, times(1)).fetch(any(GroupVersionKind.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipOldStateWhenSchemeNotRegistered() {
|
||||
// 未注册模型 → 无法定位 GVK,不抓旧状态
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost/apis/unknown.group/v1alpha1/unknowns/xyz")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
verify(client, never()).fetch(any(GroupVersionKind.class), any());
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipOldStateWhenFetchFails() {
|
||||
var gvk = targetScheme.groupVersionKind();
|
||||
when(client.fetch(eq(gvk), eq("gone")))
|
||||
.thenReturn(Mono.error(new IllegalStateException("store down")));
|
||||
var request = MockServerHttpRequest
|
||||
.delete("http://localhost" + targetPath() + "/gone").build();
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
var prepared = manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 旧状态获取失败:静默跳过 diff,请求继续(返回原 exchange)
|
||||
assertThat(prepared).isSameAs(exchange);
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipOldStateForCollectionPathWithoutResourceName() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
verify(client, never()).fetch(any(GroupVersionKind.class), any());
|
||||
assertThat(capture.getOldNode()).isNull();
|
||||
}
|
||||
|
||||
// ===== 外围保障 =====
|
||||
|
||||
@Test
|
||||
void shouldNotTouchResponse() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost" + targetPath() + "/my-cm")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.contentLength(2)
|
||||
.body("{}");
|
||||
var exchange = MockServerWebExchange.from(request);
|
||||
var capture = new ChangeCapture();
|
||||
|
||||
manager.prepare(exchange, RequestSnapshot.of(request), capture).block();
|
||||
|
||||
// 捕获过程只读请求侧,不写响应(状态码仍为未设置的 null)
|
||||
assertThat(exchange.getResponse().getStatusCode()).isNull();
|
||||
}
|
||||
}
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 字段级变更 diff 引擎测试(产品设计 V2):
|
||||
* 方法语义(PUT 全量 / PATCH merge / POST 新增 / DELETE 移除)、范围降噪
|
||||
* (根级 apiVersion/kind/status、metadata 服务端子键)、脱敏、截断、封顶与空结果。
|
||||
*/
|
||||
class ChangeDiffEngineTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static JsonNode json(String content) {
|
||||
try {
|
||||
return MAPPER.readTree(content);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ChangeEntry entry(List<ChangeEntry> changes, String field) {
|
||||
return changes.stream()
|
||||
.filter(change -> change.getField().equals(field))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
// ===== 方法语义 =====
|
||||
|
||||
@Test
|
||||
void shouldDiffPutWithUpdateAddAndRemove() {
|
||||
var old = json("""
|
||||
{"metadata": {"name": "p"}, "spec": {"title": "旧", "slug": "a", "cover": "c.png"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"metadata": {"name": "p"}, "spec": {"title": "新", "slug": "a"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
assertThat(changes).hasSize(2);
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isEqualTo("旧");
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("新");
|
||||
assertThat(entry(changes, "spec.cover").getChangeType()).isEqualTo(ChangeType.REMOVED);
|
||||
assertThat(entry(changes, "spec.cover").getOldValue()).isEqualTo("c.png");
|
||||
assertThat(entry(changes, "spec.cover").getNewValue()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTreatPatchAsMergeSemantics() {
|
||||
var old = json("""
|
||||
{"spec": {"title": "旧", "slug": "a"}}
|
||||
""");
|
||||
// merge patch 只带变更字段;slug 未携带 → 不应记为删除
|
||||
var body = json("""
|
||||
{"spec": {"title": "新"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExpandJsonPatchOpsArray() {
|
||||
// Halo 扩展路由的 PATCH 为 JSON Patch(RFC 6902 ops 数组)
|
||||
var old = json("""
|
||||
{"spec": {"title": "旧", "cover": "c.png", "slug": "a"}}
|
||||
""");
|
||||
var body = json("""
|
||||
[{"op": "replace", "path": "/spec/title", "value": "新"},
|
||||
{"op": "add", "path": "/spec/excerpt", "value": "摘要"},
|
||||
{"op": "remove", "path": "/spec/cover"}]
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isEqualTo("旧");
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("新");
|
||||
assertThat(entry(changes, "spec.excerpt").getChangeType()).isEqualTo(ChangeType.ADDED);
|
||||
assertThat(entry(changes, "spec.excerpt").getNewValue()).isEqualTo("摘要");
|
||||
assertThat(entry(changes, "spec.cover").getChangeType()).isEqualTo(ChangeType.REMOVED);
|
||||
assertThat(entry(changes, "spec.cover").getOldValue()).isEqualTo("c.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldMapJsonPatchPointerEscapes() {
|
||||
var old = json("""
|
||||
{"metadata": {"annotations": {"a/b": "旧", "x~y": "1"}}}
|
||||
""");
|
||||
var body = json("""
|
||||
[{"op": "replace", "path": "/metadata/annotations/a~1b", "value": "新"},
|
||||
{"op": "replace", "path": "/metadata/annotations/x~0y", "value": "2"}]
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(entry(changes, "metadata.annotations.a/b").getNewValue()).isEqualTo("新");
|
||||
assertThat(entry(changes, "metadata.annotations.x~y").getNewValue()).isEqualTo("2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRedactSensitiveJsonPatchTarget() {
|
||||
var old = json("""
|
||||
{"spec": {"password": "old-pw"}}
|
||||
""");
|
||||
var body = json("""
|
||||
[{"op": "replace", "path": "/spec/password", "value": "new-pw"}]
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PATCH", old, body);
|
||||
|
||||
assertThat(entry(changes, "spec.password").getOldValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
assertThat(entry(changes, "spec.password").getNewValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExpandPostBodyAsAddedFields() {
|
||||
var body = json("""
|
||||
{"metadata": {"name": "p", "labels": {"k": "v"}},
|
||||
"spec": {"title": "新文章", "content": "正文"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("POST", null, body);
|
||||
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.ADDED);
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("新文章");
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isNull();
|
||||
assertThat(entry(changes, "metadata.name").getChangeType()).isEqualTo(ChangeType.ADDED);
|
||||
assertThat(entry(changes, "metadata.name").getNewValue()).isEqualTo("p");
|
||||
assertThat(entry(changes, "metadata.labels.k").getNewValue()).isEqualTo("v");
|
||||
assertThat(changes.stream().map(ChangeEntry::getField))
|
||||
.doesNotContain("apiVersion", "kind", "status");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldExpandDeleteOldStateAsRemovedFields() {
|
||||
var old = json("""
|
||||
{"metadata": {"name": "p"}, "spec": {"title": "被删文章", "slug": "gone"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("DELETE", old, null);
|
||||
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.REMOVED);
|
||||
assertThat(entry(changes, "spec.title").getOldValue()).isEqualTo("被删文章");
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isNull();
|
||||
assertThat(entry(changes, "spec.slug").getOldValue()).isEqualTo("gone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullWhenContextMissingForPutPatchDelete() {
|
||||
var old = json("{\"spec\": {\"title\": \"x\"}}");
|
||||
var body = json("{\"spec\": {\"title\": \"y\"}}");
|
||||
|
||||
assertThat(ChangeDiffEngine.compute("PUT", null, body)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("PATCH", old, null)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("DELETE", null, null)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullForGetMethodAndMissingBody() {
|
||||
var old = json("{\"spec\": {\"title\": \"x\"}}");
|
||||
|
||||
assertThat(ChangeDiffEngine.compute("GET", old, old)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("PUT", old, null)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("POST", null, null)).isNull();
|
||||
assertThat(ChangeDiffEngine.compute("PATCH", old, null)).isNull();
|
||||
}
|
||||
|
||||
// ===== 范围与降噪 =====
|
||||
|
||||
@Test
|
||||
void shouldSkipRootNoiseAndServerManagedMetadata() {
|
||||
var old = json("""
|
||||
{"apiVersion": "content.halo.run/v1alpha1", "kind": "Post", "status": {"phase": "A"},
|
||||
"metadata": {"name": "p", "version": 3, "managedFields": [{"a": 1}],
|
||||
"creationTimestamp": "2026-01-01T00:00:00Z", "labels": {"k": "1"}},
|
||||
"spec": {"title": "旧"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"apiVersion": "content.halo.run/v1alpha1", "kind": "Post", "status": {"phase": "B"},
|
||||
"metadata": {"name": "p", "labels": {"k": "2"}},
|
||||
"spec": {"title": "新"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// 仅 metadata.labels.k 与 spec.title 两处;version/managedFields/时间戳/status 不参与
|
||||
assertThat(changes).hasSize(2);
|
||||
assertThat(entry(changes, "metadata.labels.k").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.title").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepConfigMapDataField() {
|
||||
var old = json("""
|
||||
{"metadata": {"name": "cm"}, "data": {"key": "旧配置"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"metadata": {"name": "cm"}, "data": {"key": "新配置"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// ConfigMap 的顶层 data(插件设置存储形态)必须参与 diff
|
||||
assertThat(entry(changes, "data.key").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "data.key").getOldValue()).isEqualTo("旧配置");
|
||||
assertThat(entry(changes, "data.key").getNewValue()).isEqualTo("新配置");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCompareArraysAsWholeLeaf() {
|
||||
var old = json("""
|
||||
{"spec": {"members": ["a", "b"], "tags": ["x"]}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"spec": {"members": ["a", "b"], "tags": ["x", "y"]}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// 相同数组跳过,不同数组整体一条(不做按下标配对)
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(entry(changes, "spec.tags").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.tags").getOldValue()).isEqualTo("[\"x\"]");
|
||||
assertThat(entry(changes, "spec.tags").getNewValue()).isEqualTo("[\"x\",\"y\"]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordTypeChangeAsUpdatedLeaf() {
|
||||
var old = json("""
|
||||
{"spec": {"value": {"nested": 1}}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"spec": {"value": "scalar-now"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
assertThat(changes).hasSize(1);
|
||||
assertThat(entry(changes, "spec.value").getChangeType()).isEqualTo(ChangeType.UPDATED);
|
||||
assertThat(entry(changes, "spec.value").getNewValue()).isEqualTo("scalar-now");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnNullWhenNoRealChange() {
|
||||
var old = json("""
|
||||
{"apiVersion": "v1", "kind": "Post", "status": {"a": 1},
|
||||
"metadata": {"name": "p", "version": 9}, "spec": {"title": "同"}}
|
||||
""");
|
||||
var body = json("""
|
||||
{"apiVersion": "v1", "kind": "Post", "status": {"a": 2},
|
||||
"metadata": {"name": "p"}, "spec": {"title": "同"}}
|
||||
""");
|
||||
|
||||
// 仅噪音字段(status/version)不同 → 无实际变更
|
||||
assertThat(ChangeDiffEngine.compute("PUT", old, body)).isNull();
|
||||
}
|
||||
|
||||
// ===== 脱敏、截断与封顶 =====
|
||||
|
||||
@Test
|
||||
void shouldRedactSensitiveFieldsByPathSegment() {
|
||||
var body = json("""
|
||||
{"spec": {"password": "p@ss", "accessToken": "tk-1", "title": "ok"}}
|
||||
""");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("POST", null, body);
|
||||
|
||||
assertThat(entry(changes, "spec.password").getNewValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
assertThat(entry(changes, "spec.accessToken").getNewValue())
|
||||
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
|
||||
assertThat(entry(changes, "spec.title").getNewValue()).isEqualTo("ok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTruncateLongValues() {
|
||||
var longValue = "字".repeat(ChangeDiffEngine.MAX_VALUE_LENGTH + 50);
|
||||
var body = json("{\"spec\": {\"content\": \"" + longValue + "\"}}");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("POST", null, body);
|
||||
|
||||
assertThat(entry(changes, "spec.content").getNewValue())
|
||||
.isEqualTo("字".repeat(ChangeDiffEngine.MAX_VALUE_LENGTH)
|
||||
+ ChangeDiffEngine.TRUNCATION_SUFFIX);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCapChangesWithSummaryEntry() {
|
||||
var fields = new StringBuilder();
|
||||
for (int i = 0; i < ChangeDiffEngine.MAX_CHANGES + 10; i++) {
|
||||
if (i > 0) {
|
||||
fields.append(',');
|
||||
}
|
||||
fields.append("\"f").append(i).append("\": \"v").append(i).append('"');
|
||||
}
|
||||
var old = json("{\"spec\": {}}");
|
||||
var body = json("{\"spec\": {" + fields + "}}");
|
||||
|
||||
var changes = ChangeDiffEngine.compute("PUT", old, body);
|
||||
|
||||
// 30 条实际变更 + 1 条汇总兜底
|
||||
assertThat(changes).hasSize(ChangeDiffEngine.MAX_CHANGES + 1);
|
||||
var summary = changes.get(ChangeDiffEngine.MAX_CHANGES);
|
||||
assertThat(summary.getField()).isEqualTo(ChangeDiffEngine.OVERFLOW_FIELD);
|
||||
assertThat(summary.getNewValue()).contains("共 " + (ChangeDiffEngine.MAX_CHANGES + 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFormatChangesForCsvColumn() {
|
||||
var changes = List.of(
|
||||
change(ChangeType.UPDATED, "spec.title", "旧", "新"),
|
||||
change(ChangeType.ADDED, "spec.cover", null, "c.png"),
|
||||
change(ChangeType.REMOVED, "spec.slug", "a", null));
|
||||
|
||||
assertThat(ChangeDiffEngine.formatChanges(changes))
|
||||
.isEqualTo("修改 spec.title:旧 → 新;新增 spec.cover:c.png;删除 spec.slug:a");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnEmptySummaryWhenNoChanges() {
|
||||
assertThat(ChangeDiffEngine.formatChanges(null)).isEmpty();
|
||||
assertThat(ChangeDiffEngine.formatChanges(List.of())).isEmpty();
|
||||
}
|
||||
|
||||
private static ChangeEntry change(ChangeType type, String field, String oldValue,
|
||||
String newValue) {
|
||||
var entry = new ChangeEntry();
|
||||
entry.setField(field);
|
||||
entry.setChangeType(type);
|
||||
entry.setOldValue(oldValue);
|
||||
entry.setNewValue(newValue);
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
+60
-13
@@ -6,23 +6,30 @@ import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/**
|
||||
* 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
|
||||
*/
|
||||
class OperationAuditWebFilterTest {
|
||||
|
||||
private final AuditRecorder recorder = mock(AuditRecorder.class);
|
||||
private final OperationAuditWebFilter filter = new OperationAuditWebFilter(recorder);
|
||||
private AuditRecorder recorder;
|
||||
private ChangeCaptureManager captureManager;
|
||||
private OperationAuditWebFilter filter;
|
||||
|
||||
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
||||
private static final WebFilterChainStub CHAIN = new WebFilterChainStub();
|
||||
@@ -36,6 +43,16 @@ class OperationAuditWebFilterTest {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
recorder = mock(AuditRecorder.class);
|
||||
captureManager = mock(ChangeCaptureManager.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);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureWriteWithAuthenticatedOperator() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
@@ -43,14 +60,15 @@ class OperationAuditWebFilterTest {
|
||||
.build());
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
java.util.List.of(() -> "ROLE_ADMIN"));
|
||||
List.of(() -> "ROLE_ADMIN"));
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(200), eq("admin"));
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq("admin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -61,7 +79,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,7 +91,7 @@ class OperationAuditWebFilterTest {
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
// 匿名访问 /login:无 SecurityContext → 操作者为“未知用户”,登录端点仍记录
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(200),
|
||||
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME));
|
||||
}
|
||||
|
||||
@@ -86,7 +104,7 @@ class OperationAuditWebFilterTest {
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,14 +114,14 @@ class OperationAuditWebFilterTest {
|
||||
.delete("/apis/core.halo.run/v1alpha1/users/xyz")
|
||||
.build());
|
||||
var anonymous = UsernamePasswordAuthenticationToken.authenticated(
|
||||
"anonymousUser", null, java.util.List.of());
|
||||
"anonymousUser", null, List.of());
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
verify(recorder, never()).record(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -113,17 +131,46 @@ class OperationAuditWebFilterTest {
|
||||
.build());
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
java.util.List.of());
|
||||
List.of(() -> "ROLE_ADMIN"));
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(200), eq("admin"));
|
||||
var captor = org.mockito.ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||
verify(recorder).record(captor.capture(), eq(200), eq("admin"));
|
||||
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"));
|
||||
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
|
||||
.isEqualTo("auth");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassCaptureContextToRecorder() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.put("/apis/content.halo.run/v1alpha1/posts/abc")
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Content-Length", "2")
|
||||
.body("{}"));
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
List.of(() -> "ROLE_ADMIN"));
|
||||
|
||||
// 捕获管理器返回装饰后的 exchange,并记录请求期传入的 capture 实例
|
||||
var captured = new ChangeCapture[1];
|
||||
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
|
||||
any(ChangeCapture.class)))
|
||||
.thenAnswer(inv -> {
|
||||
captured[0] = inv.getArgument(2);
|
||||
return Mono.just((ServerWebExchange) inv.getArgument(0));
|
||||
});
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
||||
.verifyComplete();
|
||||
|
||||
// 请求期创建的同一个 capture 实例被透传给记录阶段
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
|
||||
eq("admin"));
|
||||
}
|
||||
}
|
||||
|
||||
+18
-4
@@ -27,14 +27,15 @@ class AuditSettingProviderTest {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenAnswer(inv -> {
|
||||
fetchCount.incrementAndGet();
|
||||
return Mono.just(new AuditSettings(false, 30));
|
||||
return Mono.just(new AuditSettings(false, 30, null));
|
||||
});
|
||||
|
||||
var first = provider.get().block();
|
||||
var second = provider.get().block();
|
||||
|
||||
assertThat(first).extracting(AuditSettings::enabled, AuditSettings::retentionDays)
|
||||
.containsExactly(false, 30);
|
||||
assertThat(first).extracting(AuditSettings::enabled, AuditSettings::retentionDays,
|
||||
AuditSettings::recordChanges)
|
||||
.containsExactly(false, 30, null);
|
||||
assertThat(second).isSameAs(first);
|
||||
assertThat(fetchCount.get()).isEqualTo(1);
|
||||
}
|
||||
@@ -62,12 +63,25 @@ class AuditSettingProviderTest {
|
||||
@Test
|
||||
void shouldNormalizeIllegalValues() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.just(new AuditSettings(null, 1)));
|
||||
.thenReturn(Mono.just(new AuditSettings(null, 1, null)));
|
||||
|
||||
var settings = provider.get().block();
|
||||
|
||||
assertThat(settings.enabledOrDefault()).isTrue();
|
||||
assertThat(settings.retentionDaysOrDefault()).isEqualTo(90);
|
||||
assertThat(settings.recordChangesOrDefault()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDisableRecordChangesWhenExplicitlyOff() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.just(new AuditSettings(true, 90, false)));
|
||||
|
||||
var settings = provider.get().block();
|
||||
|
||||
// 字段级变更开关显式关闭:捕获阶段跳过请求体缓存与旧状态抓取
|
||||
assertThat(settings.enabledOrDefault()).isTrue();
|
||||
assertThat(settings.recordChangesOrDefault()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-2
@@ -40,7 +40,7 @@ class RetentionCleanerTest {
|
||||
new RetentionCleaner(client, settingProvider, fixedClock);
|
||||
|
||||
private void stubSettings() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 90)));
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 90, null)));
|
||||
}
|
||||
|
||||
private static AuditLog logAt(Instant creation) {
|
||||
@@ -96,7 +96,7 @@ class RetentionCleanerTest {
|
||||
|
||||
@Test
|
||||
void shouldUseRetentionDaysFromSettings() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 7)));
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 7, null)));
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, 200, 0L, List.of())));
|
||||
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AuditLogSpec } from './audit'
|
||||
import { deriveAction, describeOperation, SEMANTIC_ACTIONS } from './audit'
|
||||
import {
|
||||
changeTypeLabel,
|
||||
changeValueDisplay,
|
||||
deriveAction,
|
||||
describeOperation,
|
||||
SEMANTIC_ACTIONS,
|
||||
} from './audit'
|
||||
|
||||
// 操作描述推导(这条操作真正干了什么):由落库的语义动作标注或
|
||||
// method / resourceType / path 推导中文短语。
|
||||
@@ -238,3 +244,20 @@ describe('SEMANTIC_ACTIONS 筛选选项', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('字段级变更展示辅助', () => {
|
||||
it('changeTypeLabel:三种类型映射中文,未知回退原始值', () => {
|
||||
expect(changeTypeLabel('ADDED')).toBe('新增')
|
||||
expect(changeTypeLabel('UPDATED')).toBe('修改')
|
||||
expect(changeTypeLabel('REMOVED')).toBe('删除')
|
||||
expect(changeTypeLabel('unknown')).toBe('unknown')
|
||||
expect(changeTypeLabel(null)).toBe('修改')
|
||||
})
|
||||
|
||||
it('changeValueDisplay:缺失侧显示 ∅,其余原样', () => {
|
||||
expect(changeValueDisplay('新值')).toBe('新值')
|
||||
expect(changeValueDisplay(null)).toBe('∅')
|
||||
expect(changeValueDisplay(undefined)).toBe('∅')
|
||||
expect(changeValueDisplay('')).toBe('∅')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,6 +13,22 @@ export interface AuditLogSpec {
|
||||
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 {
|
||||
@@ -265,6 +281,25 @@ export function isSuccessful(statusCode?: number | null): boolean {
|
||||
return statusCode != null && statusCode >= 200 && statusCode < 400
|
||||
}
|
||||
|
||||
/** 变更类型 → 中文标签(未知类型回退原始值)。 */
|
||||
const CHANGE_TYPE_LABELS: Record<string, string> = {
|
||||
ADDED: '新增',
|
||||
UPDATED: '修改',
|
||||
REMOVED: '删除',
|
||||
}
|
||||
|
||||
export function changeTypeLabel(changeType?: string | null): string {
|
||||
if (!changeType) {
|
||||
return '修改'
|
||||
}
|
||||
return CHANGE_TYPE_LABELS[changeType] ?? changeType
|
||||
}
|
||||
|
||||
/** 变更值展示:缺失一侧显示为 ∅(字段不存在)。 */
|
||||
export function changeValueDisplay(value?: string | null): string {
|
||||
return value == null || value === '' ? '∅' : value
|
||||
}
|
||||
|
||||
/** datetime-local 输入值(本地时区)转 ISO-8601 Instant。 */
|
||||
export function localDateTimeToInstant(value: string): string | null {
|
||||
if (!value) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// 结构性回归测试:不渲染组件,仅检查 SFC 源码中的字段级变更展示结构。
|
||||
// 详情抽屉需在 spec.changes 存在时渲染"字段变更"区块:
|
||||
// 每条变更含类型徽章(新增/修改/删除三色)、字段路径与新旧值(缺失侧显示 ∅);
|
||||
// 无变更(历史记录)时整块不渲染。本测试防止该区块被误删或退化为通用 JSON。
|
||||
const sfc = readFileSync(
|
||||
fileURLToPath(new URL('./AuditLogDetail.vue', import.meta.url)),
|
||||
'utf-8',
|
||||
)
|
||||
|
||||
describe('AuditLogDetail 字段变更区块', () => {
|
||||
it('存在 changes 时渲染"字段变更"区块,否则不渲染', () => {
|
||||
expect(sfc).toContain('<div v-if="changes.length" class="changes">')
|
||||
expect(sfc).toContain('字段变更')
|
||||
})
|
||||
|
||||
it('每条变更渲染类型徽章与字段路径,UPDATED 展示 旧 → 新', () => {
|
||||
expect(sfc).toContain(':class="changeBadgeClass(change.changeType)"')
|
||||
expect(sfc).toContain('changeTypeLabel(change.changeType)')
|
||||
expect(sfc).toContain('{{ change.field }}')
|
||||
expect(sfc).toContain("change.changeType === 'UPDATED'")
|
||||
expect(sfc).toContain('change-arrow')
|
||||
expect(sfc).toContain('changeValueDisplay(change.oldValue)')
|
||||
expect(sfc).toContain('changeValueDisplay(change.newValue)')
|
||||
})
|
||||
|
||||
it('三种变更类型各有独立徽章配色', () => {
|
||||
expect(sfc).toContain('.change-added')
|
||||
expect(sfc).toContain('.change-updated')
|
||||
expect(sfc).toContain('.change-removed')
|
||||
})
|
||||
|
||||
it('变更区块只读:不包含任何编辑/删除入口', () => {
|
||||
// 与设计原则 3(审计自身不可篡改)一致
|
||||
expect(sfc).not.toMatch(/VButton[^>]*type="danger"/)
|
||||
expect(sfc).not.toContain('删除变更')
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { VButton, VSpace } from '@halo-dev/components'
|
||||
import type { AuditLog } from '@/utils/audit'
|
||||
import type { AuditLog, AuditLogChangeType } from '@/utils/audit'
|
||||
import {
|
||||
changeTypeLabel,
|
||||
changeValueDisplay,
|
||||
describeOperation,
|
||||
displayUsername,
|
||||
formatTime,
|
||||
@@ -28,6 +30,20 @@ const resultText = computed(() => {
|
||||
return isSuccessful(props.log.spec.statusCode) ? '成功' : '失败'
|
||||
})
|
||||
|
||||
/** 字段级变更(字段级变更 diff,产品设计 V2);历史记录缺失。 */
|
||||
const changes = computed(() => props.log?.spec.changes ?? [])
|
||||
|
||||
const changeBadgeClass = (changeType?: string | null): string => {
|
||||
switch (changeType as AuditLogChangeType) {
|
||||
case 'ADDED':
|
||||
return 'change-added'
|
||||
case 'REMOVED':
|
||||
return 'change-removed'
|
||||
default:
|
||||
return 'change-updated'
|
||||
}
|
||||
}
|
||||
|
||||
/** 详情展示的原始 JSON(只读)。 */
|
||||
const rawJson = computed(() =>
|
||||
props.log ? JSON.stringify(props.log, null, 2) : '',
|
||||
@@ -114,6 +130,41 @@ const rawJson = computed(() =>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<!-- 字段级变更(只读展示,无任何修改入口) -->
|
||||
<div v-if="changes.length" class="changes">
|
||||
<h4 class="changes-title">字段变更</h4>
|
||||
<div
|
||||
v-for="(change, index) in changes"
|
||||
:key="index"
|
||||
class="change-row"
|
||||
>
|
||||
<span
|
||||
class="change-badge"
|
||||
:class="changeBadgeClass(change.changeType)"
|
||||
>
|
||||
{{ changeTypeLabel(change.changeType) }}
|
||||
</span>
|
||||
<div class="change-body">
|
||||
<div class="mono change-field">{{ change.field }}</div>
|
||||
<div v-if="change.changeType === 'UPDATED'" class="change-values">
|
||||
<span class="break-all change-old">{{
|
||||
changeValueDisplay(change.oldValue)
|
||||
}}</span>
|
||||
<span class="change-arrow">→</span>
|
||||
<span class="break-all">{{
|
||||
changeValueDisplay(change.newValue)
|
||||
}}</span>
|
||||
</div>
|
||||
<div v-else-if="change.changeType === 'ADDED'" class="change-values">
|
||||
<span class="break-all">{{ changeValueDisplay(change.newValue) }}</span>
|
||||
</div>
|
||||
<div v-else class="change-values">
|
||||
<span class="break-all">{{ changeValueDisplay(change.oldValue) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details class="raw-json">
|
||||
<summary>原始数据</summary>
|
||||
<pre>{{ rawJson }}</pre>
|
||||
@@ -193,6 +244,67 @@ const rawJson = computed(() =>
|
||||
.break-all {
|
||||
word-break: break-all;
|
||||
}
|
||||
.changes {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
.changes-title {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: #0e1731;
|
||||
margin: 0 0 0.25rem;
|
||||
}
|
||||
.change-row {
|
||||
display: flex;
|
||||
gap: 0.625rem;
|
||||
padding: 0.5rem 0;
|
||||
border-bottom: 1px dashed #eee;
|
||||
}
|
||||
.change-badge {
|
||||
flex: 0 0 auto;
|
||||
align-self: flex-start;
|
||||
margin-top: 0.1rem;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.change-added {
|
||||
color: #0f766e;
|
||||
background: rgba(76, 203, 160, 0.15);
|
||||
}
|
||||
.change-updated {
|
||||
color: #b45309;
|
||||
background: rgba(217, 119, 6, 0.12);
|
||||
}
|
||||
.change-removed {
|
||||
color: #d71d1d;
|
||||
background: rgba(215, 29, 29, 0.12);
|
||||
}
|
||||
.change-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.change-field {
|
||||
font-size: 0.75rem;
|
||||
color: #0e1731;
|
||||
word-break: break-all;
|
||||
}
|
||||
.change-values {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.375rem;
|
||||
margin-top: 0.125rem;
|
||||
font-size: 0.75rem;
|
||||
color: #666;
|
||||
}
|
||||
.change-old {
|
||||
color: #d71d1d;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.change-arrow {
|
||||
flex: 0 0 auto;
|
||||
color: #999;
|
||||
}
|
||||
.method-badge {
|
||||
display: inline-block;
|
||||
padding: 0.1rem 0.4rem;
|
||||
|
||||
Reference in New Issue
Block a user