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:
+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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user