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:
@@ -0,0 +1,63 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import run.halo.app.extension.Metadata;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
|
||||
/**
|
||||
* 组装并直写审计记录(技术方案 D2:响应式直写,fire-and-forget)。
|
||||
*
|
||||
* <p>失败静默降级为 warn 日志:不重试、不阻塞、不抛出(产品设计原则 4)。
|
||||
* 不引入内存队列:Extension 存储底层为响应式(R2DBC),连接池天然提供背压;
|
||||
* 若后续压测发现写入积压,在 Recorder 内部替换为有界队列 + worker,接口不变。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuditRecorder {
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
|
||||
/**
|
||||
* 记录一次操作。任何失败仅记 warn 日志,不影响调用方。
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
try {
|
||||
var auditLog = assemble(snapshot, statusCode, username);
|
||||
client.create(auditLog)
|
||||
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e));
|
||||
} catch (Exception e) {
|
||||
// 组装失败同样静默降级,绝不让审计影响业务主流程
|
||||
log.warn("Failed to assemble audit log for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private AuditLog assemble(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
var resolved = ResourceResolver.resolve(snapshot.getPath());
|
||||
|
||||
var spec = new AuditLogSpec();
|
||||
spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME);
|
||||
spec.setMethod(snapshot.getMethod());
|
||||
spec.setResourceType(resolved.resourceType());
|
||||
spec.setResourceName(resolved.optionalName().orElse(null));
|
||||
spec.setPath(snapshot.getFullPath());
|
||||
spec.setStatusCode(statusCode);
|
||||
spec.setRemoteIp(snapshot.getRemoteIp());
|
||||
spec.setUserAgent(snapshot.getUserAgent());
|
||||
|
||||
var metadata = new Metadata();
|
||||
metadata.setName("auditlog-" + UUID.randomUUID());
|
||||
metadata.setCreationTimestamp(Instant.now());
|
||||
|
||||
var auditLog = new AuditLog();
|
||||
auditLog.setMetadata(metadata);
|
||||
auditLog.setSpec(spec);
|
||||
return auditLog;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 捕获规则(纯函数,技术方案 D1):
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code POST/PUT/DELETE/PATCH} + 路径前缀 {@code /apis/}</li>
|
||||
* <li>或路径精确匹配 {@code /login}、{@code /logout}(登录端点不在 /apis/** 下,
|
||||
* 是“一条通用规则覆盖全部管理面操作”的唯一必要例外,需在产品文档同步注明)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>匿名判断不在请求期做,而在记录时做(技术方案 D1)。
|
||||
*/
|
||||
public final class CaptureRule {
|
||||
|
||||
public static final Set<String> WRITE_METHODS = Set.of("POST", "PUT", "DELETE", "PATCH");
|
||||
public static final Set<String> AUTH_ENDPOINTS = Set.of("/login", "/logout");
|
||||
public static final String APIS_PREFIX = "/apis/";
|
||||
|
||||
private CaptureRule() {
|
||||
}
|
||||
|
||||
/** 是否命中捕获规则。path 为不含查询串的请求路径。 */
|
||||
public static boolean shouldCapture(String path, String method) {
|
||||
if (isAuthEndpoint(path)) {
|
||||
return true;
|
||||
}
|
||||
if (path == null || !path.startsWith(APIS_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
return method != null && WRITE_METHODS.contains(method);
|
||||
}
|
||||
|
||||
/** 是否为登录/登出端点。 */
|
||||
public static boolean isAuthEndpoint(String path) {
|
||||
return path != null && AUTH_ENDPOINTS.contains(path);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import static run.halo.operationaudit.audit.CaptureRule.shouldCapture;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.server.WebFilter;
|
||||
import org.springframework.web.server.WebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.context.ContextView;
|
||||
import run.halo.app.security.AfterSecurityWebFilter;
|
||||
|
||||
/**
|
||||
* 审计捕获过滤器(技术方案 D1 / 5.1)。
|
||||
*
|
||||
* <p>以 {@link AfterSecurityWebFilter} 扩展点注册:位于 Security 过滤链最后、认证之后,
|
||||
* 可获取当前登录用户;{@code doFinally} 可读最终响应状态码。
|
||||
*
|
||||
* <p>注意 WebFlux 无 ThreadLocal:用户名提取经 {@code transformDeferredContextual} 在订阅
|
||||
* 上下文完成,不能在 {@code doFinally} 里直接读 {@code SecurityContextHolder}。
|
||||
* 上下文中的值是 {@code Mono<SecurityContext>}(由 ReactorContextWebFilter 写入),
|
||||
* 可独立订阅,因此记录时再解析操作者。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OperationAuditWebFilter implements AfterSecurityWebFilter {
|
||||
|
||||
/** Halo/Spring Security 匿名主体的默认用户名。 */
|
||||
private static final String ANONYMOUS_USER = "anonymousUser";
|
||||
|
||||
private final AuditRecorder recorder;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
var request = exchange.getRequest();
|
||||
var path = request.getPath().value();
|
||||
if (!shouldCapture(path, request.getMethod().name())) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
var snapshot = RequestSnapshot.of(request);
|
||||
return chain.filter(exchange)
|
||||
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
|
||||
signal -> operatorOf(ctx, path).subscribe(
|
||||
username -> {
|
||||
if (shouldRecord(path, username)) {
|
||||
recorder.record(snapshot, statusOf(exchange), username);
|
||||
}
|
||||
},
|
||||
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ })));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从订阅上下文解析操作者用户名。
|
||||
*
|
||||
* <p>上下文中无 SecurityContext(匿名请求)→ 空用户名;登录端点的匿名请求记“未知用户”。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Mono<String> operatorOf(ContextView ctx, String path) {
|
||||
return ctx.getOrEmpty(SecurityContext.class)
|
||||
.map(value -> ((Mono<SecurityContext>) value)
|
||||
.flatMap(sc -> Mono.justOrEmpty(sc != null ? sc.getAuthentication() : null))
|
||||
.flatMap(auth -> Mono.justOrEmpty(auth.getName()))
|
||||
.filter(StringUtils::hasText)
|
||||
.defaultIfEmpty(AuditLogSpec.UNKNOWN_USERNAME))
|
||||
.orElseGet(() -> Mono.just(AuditLogSpec.UNKNOWN_USERNAME));
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录决策(技术方案 D1):匿名判断在记录时做——
|
||||
* {@code /apis/**} 下认证后仍为匿名主体(401/403 场景)的请求跳过不记。
|
||||
*/
|
||||
private static boolean shouldRecord(String path, String username) {
|
||||
if (CaptureRule.isAuthEndpoint(path)) {
|
||||
return true;
|
||||
}
|
||||
return StringUtils.hasText(username) && !ANONYMOUS_USER.equals(username)
|
||||
&& !AuditLogSpec.UNKNOWN_USERNAME.equals(username);
|
||||
}
|
||||
|
||||
private static Integer statusOf(ServerWebExchange exchange) {
|
||||
var status = exchange.getResponse().getStatusCode();
|
||||
return status != null ? status.value() : 0;
|
||||
}
|
||||
|
||||
/** 仅供测试与未来扩展使用:判断认证主体是否匿名。 */
|
||||
static boolean isAnonymous(Authentication authentication) {
|
||||
return authentication == null || !StringUtils.hasText(authentication.getName())
|
||||
|| ANONYMOUS_USER.equals(authentication.getName());
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import lombok.Getter;
|
||||
import lombok.ToString;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 请求期一次性解析的不可变快照(技术方案 D2):路径、方法、IP、User-Agent。
|
||||
*
|
||||
* <p>Filter 在请求期只做一次字符串解析,响应完成后由 {@link AuditRecorder} 组装落库。
|
||||
*/
|
||||
@Getter
|
||||
@ToString
|
||||
public final class RequestSnapshot {
|
||||
|
||||
private final String method;
|
||||
/** 不含查询串的请求路径(用于规则匹配与资源解析)。 */
|
||||
private final String path;
|
||||
/** 含查询串的完整路径(用于审计记录兜底展示)。 */
|
||||
private final String fullPath;
|
||||
private final String remoteIp;
|
||||
private final String userAgent;
|
||||
|
||||
private RequestSnapshot(String method, String path, String fullPath, String remoteIp,
|
||||
String userAgent) {
|
||||
this.method = method;
|
||||
this.path = path;
|
||||
this.fullPath = fullPath;
|
||||
this.remoteIp = remoteIp;
|
||||
this.userAgent = userAgent;
|
||||
}
|
||||
|
||||
/** 从请求构建快照。IP 沿用 Halo HTTP 服务器解析后的地址(含 forwarding 配置)。 */
|
||||
public static RequestSnapshot of(ServerHttpRequest request) {
|
||||
var pathValue = request.getPath().value();
|
||||
var query = request.getURI().getRawQuery();
|
||||
var fullPath = StringUtils.hasText(query) ? pathValue + "?" + query : pathValue;
|
||||
var remoteAddress = request.getRemoteAddress();
|
||||
var remoteIp = remoteAddress != null && !remoteAddress.isUnresolved()
|
||||
? remoteAddress.getAddress().getHostAddress()
|
||||
: "unknown";
|
||||
return new RequestSnapshot(
|
||||
request.getMethod().name(),
|
||||
pathValue,
|
||||
fullPath,
|
||||
remoteIp,
|
||||
request.getHeaders().getFirst("User-Agent"));
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 资源解析规则(纯函数,技术方案 5.2):
|
||||
*
|
||||
* <table>
|
||||
* <caption>请求路径 → 解析结果</caption>
|
||||
* <tr><th>请求路径</th><th>解析结果</th></tr>
|
||||
* <tr><td>/apis/{group}/{version}/{plural}</td><td>resourceType = plural</td></tr>
|
||||
* <tr><td>/apis/{group}/{version}/{plural}/{name}</td><td>resourceType = plural, resourceName = name</td></tr>
|
||||
* <tr><td>更深层子资源</td><td>取前两段</td></tr>
|
||||
* <tr><td>/login、/logout</td><td>resourceType = "auth"</td></tr>
|
||||
* </table>
|
||||
*
|
||||
* <p>不追求语义完美,完整性靠 path 字段兜底。
|
||||
*/
|
||||
public final class ResourceResolver {
|
||||
|
||||
public static final String AUTH_RESOURCE_TYPE = "auth";
|
||||
public static final String OTHER_RESOURCE_TYPE = "other";
|
||||
|
||||
private ResourceResolver() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求路径解析资源类型与名称。
|
||||
*
|
||||
* @param path 不含查询串的请求路径
|
||||
*/
|
||||
public static ResolvedResource resolve(String path) {
|
||||
if (path == null || path.isBlank()) {
|
||||
return new ResolvedResource(OTHER_RESOURCE_TYPE, null);
|
||||
}
|
||||
if (CaptureRule.isAuthEndpoint(path)) {
|
||||
return new ResolvedResource(AUTH_RESOURCE_TYPE, null);
|
||||
}
|
||||
var parts = path.split("/");
|
||||
// parts: ["", "apis", group, version, plural(, name...)],plural 为 parts[4]
|
||||
if (!path.startsWith(CaptureRule.APIS_PREFIX) || parts.length < 5) {
|
||||
return new ResolvedResource(OTHER_RESOURCE_TYPE, null);
|
||||
}
|
||||
var resourceType = parts[4];
|
||||
String resourceName = parts.length >= 6 && !parts[5].isBlank() ? parts[5] : null;
|
||||
return new ResolvedResource(resourceType, resourceName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 资源解析结果。
|
||||
*
|
||||
* @param resourceType 资源类型(复数,如 posts);无法解析时为 other/auth
|
||||
* @param resourceName 资源名称;集合级操作或认证端点为 null
|
||||
*/
|
||||
public record ResolvedResource(String resourceType, String resourceName) {
|
||||
/** 资源名称的 Optional 视图;集合级操作或认证端点为空。 */
|
||||
public Optional<String> optionalName() {
|
||||
return Optional.ofNullable(resourceName);
|
||||
}
|
||||
}
|
||||
}
|
||||
+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