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:
2026-11-21 16:21:19 +08:00
parent 3d8dad54dc
commit 95b744f6f6
10 changed files with 716 additions and 0 deletions
@@ -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);
}
}
@@ -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());
}
}
@@ -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"));
}
}
@@ -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);
}
}
}