feat: 捕获链路打通(里程碑 3)
- CaptureRule:/apis/** 写操作 + /login、/logout(纯函数) - ResourceResolver:路径 → 资源类型/名称(纯函数,深层子资源取前两段) - RequestSnapshot:请求期一次性解析不可变快照(D2) - OperationAuditWebFilter:AfterSecurityWebFilter 扩展点注册;操作者经 transformDeferredContextual 从订阅上下文(SecurityContext.class -> Mono)解析, 匿名判断在记录时做(D1);WebFlux 无 ThreadLocal - AuditRecorder:响应式直写 fire-and-forget,失败静默降级 warn(D2) - 28 个单测覆盖规则/解析/快照/降级/过滤器行为
This commit is contained in:
+91
@@ -0,0 +1,91 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
|
||||
/**
|
||||
* 直写降级测试(技术方案 D2):成功直写、失败降级为 warn 且不抛出。
|
||||
*/
|
||||
class AuditRecorderTest {
|
||||
|
||||
private final ReactiveExtensionClient client = mock(ReactiveExtensionClient.class);
|
||||
private final AuditRecorder recorder = new AuditRecorder(client);
|
||||
|
||||
@Test
|
||||
void shouldAssembleAndCreateAuditLog() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.just(new AuditLog()));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
.delete("http://localhost/apis/api.content.halo.run/v1alpha1/posts/xyz?foo=bar")
|
||||
.remoteAddress(new java.net.InetSocketAddress(
|
||||
java.net.InetAddress.getLoopbackAddress(), 45678))
|
||||
.header("User-Agent", "UA-1")
|
||||
.build());
|
||||
|
||||
recorder.record(snapshot, 204, "admin");
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
var auditLog = captor.getValue();
|
||||
|
||||
assertThat(auditLog.getSpec().getUsername()).isEqualTo("admin");
|
||||
assertThat(auditLog.getSpec().getMethod()).isEqualTo("DELETE");
|
||||
assertThat(auditLog.getSpec().getResourceType()).isEqualTo("posts");
|
||||
assertThat(auditLog.getSpec().getResourceName()).isEqualTo("xyz");
|
||||
assertThat(auditLog.getSpec().getPath()).isEqualTo(
|
||||
"/apis/api.content.halo.run/v1alpha1/posts/xyz?foo=bar");
|
||||
assertThat(auditLog.getSpec().getStatusCode()).isEqualTo(204);
|
||||
assertThat(auditLog.getSpec().getRemoteIp()).isEqualTo("127.0.0.1");
|
||||
assertThat(auditLog.getSpec().getUserAgent()).isEqualTo("UA-1");
|
||||
assertThat(auditLog.getMetadata().getName()).isNotBlank();
|
||||
assertThat(auditLog.getMetadata().getCreationTimestamp()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.just(new AuditLog()));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
.post("http://localhost/login").build());
|
||||
|
||||
recorder.record(snapshot, 401, null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
assertThat(captor.getValue().getSpec().getUsername())
|
||||
.isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
|
||||
assertThat(captor.getValue().getSpec().getResourceType()).isEqualTo("auth");
|
||||
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenCreateFails() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.error(
|
||||
new IllegalStateException("storage unavailable")));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
.post("http://localhost/apis/core.halo.run/v1alpha1/users").build());
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshot, 500, "admin")).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenAssemblyFails() {
|
||||
// path 为 null 会在资源解析前返回 other,不会抛异常;这里模拟客户端抛异常场景
|
||||
when(client.create(any(AuditLog.class))).thenThrow(new IllegalStateException("boom"));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
.post("http://localhost/apis/core.halo.run/v1alpha1/users").build());
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshot, 200, "admin")).doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static run.halo.operationaudit.audit.CaptureRule.shouldCapture;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 捕获规则纯函数测试(技术方案 D1)。
|
||||
*/
|
||||
class CaptureRuleTest {
|
||||
|
||||
@Test
|
||||
void shouldCaptureWriteMethodsUnderApis() {
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts", "POST")).isTrue();
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts/xyz", "PUT")).isTrue();
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts/xyz", "DELETE"))
|
||||
.isTrue();
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts/xyz", "PATCH"))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureReadMethodsUnderApis() {
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts", "GET")).isFalse();
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts", "HEAD")).isFalse();
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts", "OPTIONS")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureAuthEndpointsRegardlessOfMethod() {
|
||||
assertThat(shouldCapture("/login", "POST")).isTrue();
|
||||
assertThat(shouldCapture("/login", "GET")).isTrue();
|
||||
assertThat(shouldCapture("/logout", "POST")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureNonApisPaths() {
|
||||
assertThat(shouldCapture("/", "POST")).isFalse();
|
||||
assertThat(shouldCapture("/console", "POST")).isFalse();
|
||||
assertThat(shouldCapture("/apis", "POST")).isFalse();
|
||||
assertThat(shouldCapture("/apis", null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureNullInputs() {
|
||||
assertThat(shouldCapture(null, "POST")).isFalse();
|
||||
assertThat(shouldCapture(null, null)).isFalse();
|
||||
assertThat(shouldCapture("/apis/api.content.halo.run/v1alpha1/posts", null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDetectAuthEndpointsOnlyExactly() {
|
||||
assertThat(CaptureRule.isAuthEndpoint("/login")).isTrue();
|
||||
assertThat(CaptureRule.isAuthEndpoint("/logout")).isTrue();
|
||||
assertThat(CaptureRule.isAuthEndpoint("/loginx")).isFalse();
|
||||
assertThat(CaptureRule.isAuthEndpoint("/console/login")).isFalse();
|
||||
assertThat(CaptureRule.isAuthEndpoint(null)).isFalse();
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
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.verify;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
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 reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
/**
|
||||
* 过滤器行为测试(技术方案 §7):状态码捕获、操作者提取、匿名跳过。
|
||||
*/
|
||||
class OperationAuditWebFilterTest {
|
||||
|
||||
private final AuditRecorder recorder = mock(AuditRecorder.class);
|
||||
private final OperationAuditWebFilter filter = new OperationAuditWebFilter(recorder);
|
||||
|
||||
/** 终止型 chain:模拟正常响应(200)后完成。 */
|
||||
private static final WebFilterChainStub CHAIN = new WebFilterChainStub();
|
||||
|
||||
private static final class WebFilterChainStub implements
|
||||
org.springframework.web.server.WebFilterChain {
|
||||
@Override
|
||||
public Mono<Void> filter(org.springframework.web.server.ServerWebExchange exchange) {
|
||||
exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.OK);
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureWriteWithAuthenticatedOperator() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/apis/api.content.halo.run/v1alpha1/posts")
|
||||
.build());
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
java.util.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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotCaptureReadRequests() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.get("/apis/api.content.halo.run/v1alpha1/posts")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRecordLoginFailureAsUnknownUser() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/login")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
// 匿名访问 /login:无 SecurityContext → 操作者为“未知用户”,登录端点仍记录
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(200),
|
||||
eq(AuditLogSpec.UNKNOWN_USERNAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipAnonymousApisRequests() {
|
||||
// /apis/** 且无 SecurityContext(认证前/匿名 401 场景)→ 不记录
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/apis/api.content.halo.run/v1alpha1/posts")
|
||||
.build());
|
||||
|
||||
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSkipAnonymousPrincipalOnApisRequests() {
|
||||
// 匿名主体(anonymousUser)出现在上下文中时同样不记录
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.delete("/apis/core.halo.run/v1alpha1/users/xyz")
|
||||
.build());
|
||||
var anonymous = UsernamePasswordAuthenticationToken.authenticated(
|
||||
"anonymousUser", null, java.util.List.of());
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder, never()).record(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCaptureLogoutAsAuth() {
|
||||
var exchange = MockServerWebExchange.from(MockServerHttpRequest
|
||||
.post("/logout")
|
||||
.build());
|
||||
var authentication = UsernamePasswordAuthenticationToken.authenticated(
|
||||
User.withUsername("admin").password("unused").roles("ADMIN").build(), null,
|
||||
java.util.List.of());
|
||||
|
||||
StepVerifier.create(
|
||||
filter.filter(exchange, CHAIN)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)))
|
||||
.verifyComplete();
|
||||
|
||||
verify(recorder).record(any(RequestSnapshot.class), eq(200), eq("admin"));
|
||||
var captor = org.mockito.ArgumentCaptor.forClass(RequestSnapshot.class);
|
||||
verify(recorder).record(captor.capture(), eq(200), eq("admin"));
|
||||
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
|
||||
.isEqualTo("auth");
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import run.halo.operationaudit.audit.RequestSnapshot;
|
||||
|
||||
/**
|
||||
* 请求快照测试:请求期一次性解析(技术方案 D2)。
|
||||
*/
|
||||
class RequestSnapshotTest {
|
||||
|
||||
@Test
|
||||
void shouldParseMethodPathIpAndUserAgent() {
|
||||
var request = MockServerHttpRequest
|
||||
.post("http://localhost/apis/api.content.halo.run/v1alpha1/posts")
|
||||
.remoteAddress(new java.net.InetSocketAddress(
|
||||
java.net.InetAddress.getLoopbackAddress(), 45678))
|
||||
.header("User-Agent", "Mozilla/5.0 TestAgent")
|
||||
.build();
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
|
||||
assertThat(snapshot.getMethod()).isEqualTo("POST");
|
||||
assertThat(snapshot.getPath())
|
||||
.isEqualTo("/apis/api.content.halo.run/v1alpha1/posts");
|
||||
assertThat(snapshot.getFullPath())
|
||||
.isEqualTo("/apis/api.content.halo.run/v1alpha1/posts");
|
||||
assertThat(snapshot.getRemoteIp()).isEqualTo("127.0.0.1");
|
||||
assertThat(snapshot.getUserAgent()).isEqualTo("Mozilla/5.0 TestAgent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldKeepQueryStringInFullPathOnly() {
|
||||
var request = MockServerHttpRequest
|
||||
.put("http://localhost/apis/api.content.halo.run/v1alpha1/posts/xyz?dryRun=true")
|
||||
.build();
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
|
||||
assertThat(snapshot.getPath()).isEqualTo(
|
||||
"/apis/api.content.halo.run/v1alpha1/posts/xyz");
|
||||
assertThat(snapshot.getFullPath()).isEqualTo(
|
||||
"/apis/api.content.halo.run/v1alpha1/posts/xyz?dryRun=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackIpToUnknownWhenAbsentOrUnresolved() {
|
||||
// 默认 Mock 请求未设置 remoteAddress → unknown
|
||||
var request = MockServerHttpRequest.post("http://localhost/login").build();
|
||||
assertThat(RequestSnapshot.of(request).getRemoteIp()).isEqualTo("unknown");
|
||||
|
||||
// 未解析的地址同样降级为 unknown
|
||||
var unresolved = new java.net.InetSocketAddress("unresolved.example.invalid", 80);
|
||||
var unresolvedRequest = MockServerHttpRequest.post("http://localhost/login")
|
||||
.remoteAddress(unresolved)
|
||||
.build();
|
||||
assertThat(RequestSnapshot.of(unresolvedRequest).getRemoteIp()).isEqualTo("unknown");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleMissingUserAgent() {
|
||||
var request = MockServerHttpRequest.post("http://localhost/login").build();
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
assertThat(snapshot.getUserAgent()).isNull();
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 资源解析纯函数测试(技术方案 5.2)。
|
||||
*/
|
||||
class ResourceResolverTest {
|
||||
|
||||
@Test
|
||||
void shouldResolveCollectionPath() {
|
||||
var resolved = ResourceResolver.resolve(
|
||||
"/apis/api.content.halo.run/v1alpha1/posts");
|
||||
assertThat(resolved.resourceType()).isEqualTo("posts");
|
||||
assertThat(resolved.optionalName()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveSingleResourcePath() {
|
||||
var resolved = ResourceResolver.resolve(
|
||||
"/apis/api.content.halo.run/v1alpha1/posts/xyz");
|
||||
assertThat(resolved.resourceType()).isEqualTo("posts");
|
||||
assertThat(resolved.optionalName()).contains("xyz");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTakeFirstTwoSegmentsForDeeperSubResources() {
|
||||
var resolved = ResourceResolver.resolve(
|
||||
"/apis/api.content.halo.run/v1alpha1/posts/xyz/revisions/1");
|
||||
assertThat(resolved.resourceType()).isEqualTo("posts");
|
||||
assertThat(resolved.optionalName()).contains("xyz");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveAuthEndpoints() {
|
||||
assertThat(ResourceResolver.resolve("/login").resourceType()).isEqualTo("auth");
|
||||
assertThat(ResourceResolver.resolve("/logout").resourceType()).isEqualTo("auth");
|
||||
assertThat(ResourceResolver.resolve("/login").optionalName()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToOtherForUnrecognizedPaths() {
|
||||
assertThat(ResourceResolver.resolve("/console").resourceType()).isEqualTo("other");
|
||||
assertThat(ResourceResolver.resolve("/apis").resourceType()).isEqualTo("other");
|
||||
assertThat(ResourceResolver.resolve("/apis/api.content.halo.run/v1alpha1")
|
||||
.resourceType()).isEqualTo("other");
|
||||
assertThat(ResourceResolver.resolve(null).resourceType()).isEqualTo("other");
|
||||
assertThat(ResourceResolver.resolve("").resourceType()).isEqualTo("other");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveCoreApiGroup() {
|
||||
// /apis/{group}/{version}/{plural} 中 group 为单段(如 core组外的自定义组),
|
||||
// 例如 /apis/core.halo.run/v1alpha1/users
|
||||
var resolved = ResourceResolver.resolve("/apis/core.halo.run/v1alpha1/users/admin");
|
||||
assertThat(resolved.resourceType()).isEqualTo("users");
|
||||
assertThat(resolved.optionalName()).contains("admin");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user