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