feat: 操作审计支持按筛选条件导出 CSV

- 后端新增导出端点 GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/export:
  筛选参数与 query 完全一致(条件构造抽取为 AuditLogFilters 共用),
  按时间升序分批(每批 200)遍历全量、流式输出 UTF-8 BOM CSV(Excel/WPS 直开),
  字段引号转义 + 公式注入防护;列含 describeOperation 移植版中文操作描述(OperationDescription)
- role-template 追加 auditlogs/export(动词仍 get/list,保持只读语义)
- Console 列表页工具栏新增「导出」按钮:按当前筛选条件 fetch → blob → a[download] 下载
- 测试:后端新增导出端点/分批取数/CSV 转义/操作描述用例(71 个全绿),
  前端新增导出链路结构性回归 spec(31 个全绿)+ vue-tsc 通过
- 文档:设计文档 V2 规划项标注已实现,README 补导出说明
This commit is contained in:
2026-11-21 21:28:03 +08:00
parent 3abd79a65f
commit 058596c0ea
13 changed files with 880 additions and 88 deletions
@@ -0,0 +1,261 @@
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import run.halo.app.extension.ListOptions;
import run.halo.app.extension.ListResult;
import run.halo.app.extension.Metadata;
import run.halo.app.extension.PageRequest;
import run.halo.app.extension.ReactiveExtensionClient;
/**
* 导出端点与 CSV 生成测试:响应头/BOM/表头/数据行、转义与注入防护、
* 全量分批取数(升序、每批 200、循环至不足一批)、非法筛选参数 400。
*/
class AuditExportEndpointTest {
private static final String EXPORT_URI =
"/apis/" + AuditLog.GROUP + "/v1alpha1/auditlogs/-/export";
private static final String CSV_HEADER =
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,结果,状态码,来源IP,User-Agent";
private ReactiveExtensionClient client;
private WebTestClient webClient;
@BeforeEach
void setUp() {
client = mock(ReactiveExtensionClient.class);
// 导出路由挂在 AuditQueryEndpoint 上(同一 builder),真实 exporter + mock client
var endpoint = new AuditQueryEndpoint(client, new AuditLogCsvExporter(client));
var mounted = org.springframework.web.reactive.function.server.RouterFunctions.nest(
org.springframework.web.reactive.function.server.RequestPredicates.path(
"/apis/" + AuditLog.GROUP + "/v1alpha1"),
endpoint.endpoint());
webClient = WebTestClient.bindToRouterFunction(mounted).build();
}
private static AuditLog auditLog(String name, Instant creationTimestamp, String username,
String method, String resourceType, String resourceName, String path,
Integer statusCode, String remoteIp, String userAgent) {
var metadata = new Metadata();
metadata.setName(name);
metadata.setCreationTimestamp(creationTimestamp);
var spec = new AuditLogSpec();
spec.setUsername(username);
spec.setMethod(method);
spec.setResourceType(resourceType);
spec.setResourceName(resourceName);
spec.setPath(path);
spec.setStatusCode(statusCode);
spec.setRemoteIp(remoteIp);
spec.setUserAgent(userAgent);
var log = new AuditLog();
log.setMetadata(metadata);
log.setSpec(spec);
return log;
}
/** 与实现一致的期望操作时间列(服务器时区)。 */
private static String expectedTimeColumn(Instant instant) {
return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault())
.format(instant);
}
private void stubSinglePage(List<AuditLog> items) {
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
.thenReturn(Mono.just(new ListResult<>(1, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
items.size(), items)));
}
@Test
void shouldExportCsvWithBomHeaderAndRows() {
var time = Instant.parse("2026-11-01T00:00:00Z");
stubSinglePage(List.of(
auditLog("auditlog-1", time, "admin", "POST", "users", "zhangsan",
"/apis/api.console.halo.run/v1alpha1/users", 201, "127.0.0.1",
"Mozilla/5.0"),
auditLog("auditlog-2", time.plusSeconds(60), "unknown", "POST", "auth", null,
"/login", 401, "10.0.0.8", "Mozilla/5.0")));
var body = exportAndGetBody(EXPORT_URI);
assertThat(body).startsWith("\uFEFF" + CSV_HEADER + "\r\n");
var lines = body.split("\r\n");
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");
assertThat(lines[2]).isEqualTo(expectedTimeColumn(time.plusSeconds(60))
+ ",unknown,POST,auth,,/login,登录,失败,401,10.0.0.8,Mozilla/5.0");
}
@Test
void shouldExportOnlyHeaderWhenNoRecords() {
stubSinglePage(List.of());
var body = exportAndGetBody(EXPORT_URI);
assertThat(body).isEqualTo("\uFEFF" + CSV_HEADER + "\r\n");
}
@Test
void shouldEscapeSpecialCharactersAndFormulaInjection() {
stubSinglePage(List.of(
// 逗号与引号需加引号且内部引号翻倍;= 开头需加单引号前缀
auditLog("auditlog-1", 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")));
var body = exportAndGetBody(EXPORT_URI);
var lines = body.split("\r\n");
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");
}
@Test
void shouldTreatNullStatusCodeAsFailureAndEmptyFields() {
stubSinglePage(List.of(
auditLog("auditlog-1", Instant.parse("2026-11-03T00:00:00Z"), "admin", "PATCH",
"themes", null, null, null, null, null)));
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,,,修改主题,失败,,,");
}
@Test
void shouldApplyFilterParamsSameAsQuery() {
stubSinglePage(List.of());
exportAndGetBody(EXPORT_URI
+ "?fieldSelector=spec.username=admin&result=failure&keyword=hello"
+ "&startTime=2026-11-01T00:00:00Z&endTime=2026-11-21T00:00:00Z");
var captor = ArgumentCaptor.forClass(ListOptions.class);
verify(client).listBy(eq(AuditLog.class), captor.capture(), any(PageRequest.class));
var condition = captor.getValue().toCondition().toString();
assertThat(condition)
.contains("spec.username")
.contains("admin")
.contains("spec.statusCode")
.contains("400")
.contains("spec.resourceName")
.contains("spec.path")
.contains("hello")
.contains("metadata.creationTimestamp")
.contains("2026-11-01T00:00:00Z")
.contains("2026-11-21T00:00:00Z");
}
@Test
void shouldRejectNonWhitelistedFieldSelector() {
webClient.get()
.uri(EXPORT_URI + "?fieldSelector=spec.userAgent=evil")
.exchange()
.expectStatus().isBadRequest();
}
@Test
void shouldRejectInvalidResultFilter() {
webClient.get()
.uri(EXPORT_URI + "?result=unknown")
.exchange()
.expectStatus().isBadRequest();
}
@Test
void shouldRejectInvalidTimeFormat() {
webClient.get()
.uri(EXPORT_URI + "?startTime=not-a-time")
.exchange()
.expectStatus().isBadRequest();
}
@Test
void shouldFetchAllInBatchesUntilShortPage() {
// 第一页满批 200 条、第二页满批、第三页不足一批:共 401 条,验证分批递归终止
var page1 = fullBatch(1);
var page2 = fullBatch(2);
var page3 = List.of(
auditLog("auditlog-401", Instant.parse("2026-11-01T00:00:00Z"), "admin", "POST",
"users", "zhangsan", "/apis/v1alpha1/users", 200, "127.0.0.1", "UA"));
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
.thenReturn(Mono.just(new ListResult<>(1, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
401, page1)),
Mono.just(new ListResult<>(2, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
401, page2)),
Mono.just(new ListResult<>(3, AuditLogCsvExporter.EXPORT_BATCH_SIZE,
401, page3)));
var exporter = new AuditLogCsvExporter(client);
StepVerifier.create(exporter.fetchAll(new ListOptions()
.setFieldSelector(run.halo.app.extension.router.selector.FieldSelector.all())))
.expectNextCount(401)
.verifyComplete();
// 三次分批查询:页码 1/2/3、批大小 200、时间升序(导出期间并发写入不打乱分页边界)
var captor = ArgumentCaptor.forClass(PageRequest.class);
verify(client, times(3)).listBy(eq(AuditLog.class), any(ListOptions.class),
captor.capture());
var pages = captor.getAllValues();
assertThat(pages).hasSize(3);
for (int i = 0; i < pages.size(); i++) {
assertThat(pages.get(i).getPageNumber()).isEqualTo(i + 1);
assertThat(pages.get(i).getPageSize())
.isEqualTo(AuditLogCsvExporter.EXPORT_BATCH_SIZE);
assertThat(pages.get(i).getSort().getOrderFor("metadata.creationTimestamp"))
.extracting(Sort.Order::getDirection)
.isEqualTo(Sort.Direction.ASC);
}
}
private List<AuditLog> fullBatch(long firstTimestampEpochSecond) {
var items = new ArrayList<AuditLog>();
for (int i = 0; i < AuditLogCsvExporter.EXPORT_BATCH_SIZE; i++) {
items.add(auditLog("auditlog-" + i,
Instant.ofEpochSecond(firstTimestampEpochSecond * 1000 + i),
"admin", "POST", "users", "user-" + i, "/apis/v1alpha1/users", 200,
"127.0.0.1", "UA"));
}
return items;
}
private String exportAndGetBody(String uri) {
var bytes = webClient.get()
.uri(uri)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.parseMediaType("text/csv;charset=UTF-8"))
.expectHeader().value(HttpHeaders.CONTENT_DISPOSITION,
disposition -> assertThat(disposition)
.startsWith("attachment; filename=audit-logs-")
.endsWith(".csv"))
.expectBody(byte[].class)
.returnResult()
.getResponseBody();
return new String(bytes, StandardCharsets.UTF_8);
}
}
@@ -30,7 +30,7 @@ class AuditQueryEndpointTest {
@BeforeEach
void setUp() {
client = mock(ReactiveExtensionClient.class);
var endpoint = new AuditQueryEndpoint(client);
var endpoint = new AuditQueryEndpoint(client, mock(AuditLogCsvExporter.class));
// 复现生产环境挂载方式(CustomEndpointsBuilder 在 /apis/{groupVersion} 下 nest)
var mounted = org.springframework.web.reactive.function.server.RouterFunctions.nest(
org.springframework.web.reactive.function.server.RequestPredicates.path(
@@ -0,0 +1,103 @@
package run.halo.operationaudit.audit;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* 操作描述推导测试:与前端 {@code ui/src/utils/audit.spec.ts} 的 describeOperation
* 用例一一对应(Java 移植版需与前端推导结果完全一致,两处需同步修改)。
*/
class OperationDescriptionTest {
@Test
void shouldDescribeLoginEndpointIncludingQuery() {
assertThat(OperationDescription.describe("POST", "auth", "/login")).isEqualTo("登录");
// GET /login?redirect_uri=... 也应识别为登录(path 含查询串)
assertThat(OperationDescription.describe("GET", "auth",
"/login?redirect_uri=https%3A%2F%2Fwww.guichumo.com%2Fconsole")).isEqualTo("登录");
}
@Test
void shouldDescribeLogoutEndpoint() {
assertThat(OperationDescription.describe("POST", "auth", "/logout")).isEqualTo("登出");
}
@Test
void shouldFallbackToAuthOperationForNonLoginLogoutAuthPath() {
assertThat(OperationDescription.describe("POST", "auth", "/auth/other"))
.isEqualTo("认证操作");
}
@Test
void shouldComposeVerbAndResourceLabel() {
assertThat(OperationDescription.describe("POST", "users",
"/apis/api.console.halo.run/v1alpha1/users")).isEqualTo("新建用户");
assertThat(OperationDescription.describe("PUT", "posts",
"/apis/content.halo.run/v1alpha1/posts/post-abc")).isEqualTo("修改文章");
assertThat(OperationDescription.describe("PATCH", "themes",
"/apis/api.console.halo.run/v1alpha1/themes/theme-abc")).isEqualTo("修改主题");
assertThat(OperationDescription.describe("DELETE", "plugins",
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc")).isEqualTo("删除插件");
}
@Test
void shouldComposeSubActionVerbAndResourceLabel() {
assertThat(OperationDescription.describe("POST", "posts",
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish")).isEqualTo("发布文章");
assertThat(OperationDescription.describe("POST", "plugins",
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/enable"))
.isEqualTo("启用插件");
assertThat(OperationDescription.describe("POST", "plugins",
"/apis/api.console.halo.run/v1alpha1/plugins/plugin-abc/disable"))
.isEqualTo("停用插件");
assertThat(OperationDescription.describe("POST", "posts",
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/recycle"))
.isEqualTo("移入回收站文章");
}
@Test
void shouldUseFullPhraseWithoutResourceName() {
assertThat(OperationDescription.describe("PUT", "users",
"/apis/api.console.halo.run/v1alpha1/users/admin/password")).isEqualTo("修改密码");
}
@Test
void shouldFallbackToBaseVerbForUnknownSubAction() {
assertThat(OperationDescription.describe("PUT", "posts",
"/apis/content.halo.run/v1alpha1/posts/post-abc/content")).isEqualTo("修改文章");
}
@Test
void shouldStripQueryBeforeParsingSubAction() {
assertThat(OperationDescription.describe("POST", "posts",
"/apis/api.console.halo.run/v1alpha1/posts/post-abc/publish?async=true"))
.isEqualTo("发布文章");
}
@Test
void shouldFallbackToRawResourceTypeForUnknownType() {
assertThat(OperationDescription.describe("POST", "workflows",
"/apis/audit.guichumo.com/v1alpha1/workflows")).isEqualTo("新建workflows");
}
@Test
void shouldFallbackToRawMethodForUnknownMethod() {
assertThat(OperationDescription.describe("TRACE", "posts",
"/apis/content.halo.run/v1alpha1/posts/post-abc")).isEqualTo("TRACE文章");
}
@Test
void shouldFallbackToVerbPlusRawPathForUnparseablePath() {
assertThat(OperationDescription.describe("DELETE", "other", "/somewhere/odd"))
.isEqualTo("删除other");
}
@Test
void shouldHandleNullPath() {
// 防御性:path 缺失时不应抛异常;资源标签来自 resourceType 映射,与 path 无关
assertThat(OperationDescription.describe("POST", "users", null)).isEqualTo("新建用户");
assertThat(OperationDescription.describe("POST", "workflows", null))
.isEqualTo("新建workflows");
}
}