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:
@@ -11,6 +11,7 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
| 自动捕获 | 已登录用户对 `/apis/**` 的 POST/PUT/DELETE/PATCH,另捕获 `/login`、`/logout`(含登录失败) |
|
||||||
| Console 查看页 | 列表 + 七维筛选(操作者 / 资源类型 / 动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含原始 JSON) |
|
| Console 查看页 | 列表 + 七维筛选(操作者 / 资源类型 / 动作 / 结果 / 时间区间 / 关键字)+ 分页 + 只读详情抽屉(含原始 JSON) |
|
||||||
|
| 导出 CSV | 按当前筛选条件一键导出全部记录(后端全量流式生成 UTF-8 BOM CSV,Excel/WPS 直开不乱码) |
|
||||||
| 保留与清理 | 可配置保留天数(7 ~ ∞,默认 90),每日凌晨自动清理过期记录 |
|
| 保留与清理 | 可配置保留天数(7 ~ ∞,默认 90),每日凌晨自动清理过期记录 |
|
||||||
| 权限 | 默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`(verbs 仅 `get`/`list`) |
|
| 权限 | 默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`(verbs 仅 `get`/`list`) |
|
||||||
|
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ Console 左侧菜单新增"操作审计"页:
|
|||||||
| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作 | V2 |
|
| 语义动作标注 | 区分"发布/编辑/恢复"等中文动作 | V2 |
|
||||||
| 字段级变更 diff | 记录改了什么(需缓存请求体) | V2 |
|
| 字段级变更 diff | 记录改了什么(需缓存请求体) | V2 |
|
||||||
| 系统内部变更 | 定时发布等非 HTTP 触发的变更,执行者记"system" | V2 |
|
| 系统内部变更 | 定时发布等非 HTTP 触发的变更,执行者记"system" | V2 |
|
||||||
| 导出 CSV | 按筛选条件导出 | V2 |
|
| 导出 CSV | 按筛选条件导出(后端全量流式生成 UTF-8 BOM CSV,Console 页一键下载) | V2 已实现 |
|
||||||
| 告警通知 | 登录失败告警、webhook | V2+ |
|
| 告警通知 | 登录失败告警、webhook | V2+ |
|
||||||
| 操作回滚 | 不在产品范围内 | 不做 |
|
| 操作回滚 | 不在产品范围内 | 不做 |
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
|
|||||||
另捕获 `/login`、`/logout`(登录成功/失败/登出)。
|
另捕获 `/login`、`/logout`(登录成功/失败/登出)。
|
||||||
- **审计日志查看**:Console 左侧菜单"操作审计"——列表 + 七维筛选(操作者/资源类型/动作/结果/
|
- **审计日志查看**:Console 左侧菜单"操作审计"——列表 + 七维筛选(操作者/资源类型/动作/结果/
|
||||||
时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。
|
时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。
|
||||||
|
- **导出 CSV**:列表页「导出」按钮按当前筛选条件导出全部记录——后端全量流式生成
|
||||||
|
(UTF-8 BOM + `\r\n`,Excel/WPS 双击打开中文不乱码),列与界面一致(操作时间、操作者、
|
||||||
|
动作、资源类型、资源名称、路径、操作描述、结果、状态码、来源 IP、User-Agent),
|
||||||
|
含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。
|
||||||
- **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录,
|
- **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录,
|
||||||
启动时补跑一次。
|
启动时补跑一次。
|
||||||
- **权限**:默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`
|
- **权限**:默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`
|
||||||
@@ -65,11 +69,15 @@ Console「插件 → 操作审计 → 设置」:
|
|||||||
`doFinally` 读最终状态码);存储为自定义 Extension + 索引查询,全程响应式非阻塞。
|
`doFinally` 读最终状态码);存储为自定义 Extension + 索引查询,全程响应式非阻塞。
|
||||||
- 查询走插件自有端点 `GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/query`——
|
- 查询走插件自有端点 `GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/query`——
|
||||||
经源码验证,Halo 原生列表 API 的 fieldSelector 仅支持等值操作符,不支持时间区间与
|
经源码验证,Halo 原生列表 API 的 fieldSelector 仅支持等值操作符,不支持时间区间与
|
||||||
模糊匹配(技术方案风险项 #2 证实并按预案启用自有端点)。
|
模糊匹配(技术方案风险项 #2 证实并按预案启用自有端点)。导出走同端点类的
|
||||||
|
`GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/export`:筛选参数与 query 完全一致
|
||||||
|
(共用 `AuditLogFilters`),按时间升序分批(每批 200,与保留期清理同款迭代模式)
|
||||||
|
遍历全量,流式输出 CSV——升序保证导出期间并发写入不打乱分页边界。
|
||||||
- 定时清理采用 Reactor 调度方案(技术方案风险项 #3 预案),不依赖 `@Scheduled`
|
- 定时清理采用 Reactor 调度方案(技术方案风险项 #3 预案),不依赖 `@Scheduled`
|
||||||
在插件上下文的可用性。
|
在插件上下文的可用性。
|
||||||
- 关于测试:`./gradlew test`(当前 50 个用例)覆盖捕获规则、资源解析、快照、直写降级、
|
- 关于测试:`./gradlew test`(当前 71 个用例)覆盖捕获规则、资源解析、快照、直写降级、
|
||||||
过滤器行为、查询端点参数校验、设置缓存与保留期清理;Console UI 以 vitest 断言
|
过滤器行为、查询端点参数校验、导出 CSV(BOM/表头/转义/注入防护/分批取数)、
|
||||||
|
操作描述推导(与前端 describeOperation 用例一一对应)、设置缓存与保留期清理;Console UI 以 vitest 断言
|
||||||
路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)+ 类型检查 + 构建通过为准
|
路由注册形态(必须挂在 `Root` 布局路由下,否则页面会全屏渲染)+ 类型检查 + 构建通过为准
|
||||||
(技术方案 §7,MVP 不引入组件测试)。
|
(技术方案 §7,MVP 不引入组件测试)。
|
||||||
|
|
||||||
|
|||||||
+143
@@ -0,0 +1,143 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.core.io.buffer.DataBuffer;
|
||||||
|
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||||
|
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import run.halo.app.extension.ListOptions;
|
||||||
|
import run.halo.app.extension.PageRequestImpl;
|
||||||
|
import run.halo.app.extension.ReactiveExtensionClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 审计日志 CSV 导出(按筛选条件导出,设计文档 V2 规划项)。
|
||||||
|
*
|
||||||
|
* <p>按时间升序分批遍历(每批 {@value #EXPORT_BATCH_SIZE} 条,循环至不足一批,
|
||||||
|
* 与 {@code RetentionCleaner} 的分批模式一致)拉取筛选命中的全部记录,
|
||||||
|
* 流式拼接 CSV 行输出,内存仅保留当前批。升序的原因:新记录时间戳更大、
|
||||||
|
* 总是排在末尾,导出期间并发写入不会打乱分页边界。
|
||||||
|
*
|
||||||
|
* <p>CSV 采用 UTF-8 BOM + \r\n 行结束符,Excel/WPS 双击打开中文不乱码;
|
||||||
|
* 字段做引号转义与公式注入防护(见 {@link #escape})。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AuditLogCsvExporter {
|
||||||
|
|
||||||
|
/** 每批查询条数。 */
|
||||||
|
static final int EXPORT_BATCH_SIZE = 200;
|
||||||
|
|
||||||
|
/** CSV 列题头(与 UI 列表列对应)。 */
|
||||||
|
private static final String CSV_HEADER =
|
||||||
|
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,结果,状态码,来源IP,User-Agent";
|
||||||
|
|
||||||
|
private static final DataBufferFactory BUFFER_FACTORY =
|
||||||
|
DefaultDataBufferFactory.sharedInstance;
|
||||||
|
|
||||||
|
/** 操作时间列格式(服务器时区,与 UI 列表展示格式一致)。 */
|
||||||
|
private static final DateTimeFormatter TIME_FORMATTER =
|
||||||
|
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
|
||||||
|
|
||||||
|
/** 导出文件名中的时间戳(不能含冒号/空格等文件名非法字符)。 */
|
||||||
|
private static final DateTimeFormatter FILENAME_TIME_FORMATTER =
|
||||||
|
DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault());
|
||||||
|
|
||||||
|
private final ReactiveExtensionClient client;
|
||||||
|
|
||||||
|
/** 导出为 CSV 附件下载响应(流式输出)。 */
|
||||||
|
public Mono<ServerResponse> exportResponse(ListOptions options) {
|
||||||
|
var filename = "audit-logs-" + FILENAME_TIME_FORMATTER.format(Instant.now()) + ".csv";
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.contentType(MediaType.parseMediaType("text/csv;charset=UTF-8"))
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
|
||||||
|
.body(csvLines(options)
|
||||||
|
.map(line -> BUFFER_FACTORY.wrap(line.getBytes(StandardCharsets.UTF_8))),
|
||||||
|
DataBuffer.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Flux<String> csvLines(ListOptions options) {
|
||||||
|
// 首行带 UTF-8 BOM;每行统一以 \r\n 结束(Excel/WPS 友好)
|
||||||
|
return Flux.concat(
|
||||||
|
Flux.just("\uFEFF" + CSV_HEADER),
|
||||||
|
fetchAll(options).map(this::toCsvLine))
|
||||||
|
.map(line -> line + "\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按时间升序分批遍历筛选命中的全部记录:每批 {@value #EXPORT_BATCH_SIZE} 条,
|
||||||
|
* 不足一批说明已取完(满一批时可能恰好取尽,多做一次空页查询,无害)。
|
||||||
|
*/
|
||||||
|
Flux<AuditLog> fetchAll(ListOptions options) {
|
||||||
|
return fetchBatch(options, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Flux<AuditLog> fetchBatch(ListOptions options, int page) {
|
||||||
|
var pageable = PageRequestImpl.of(page, EXPORT_BATCH_SIZE,
|
||||||
|
Sort.by(Sort.Order.asc("metadata.creationTimestamp")));
|
||||||
|
return client.listBy(AuditLog.class, options, pageable)
|
||||||
|
.flatMapMany(result -> {
|
||||||
|
var items = result.getItems() != null
|
||||||
|
? result.getItems()
|
||||||
|
: List.<AuditLog>of();
|
||||||
|
if (items.size() < EXPORT_BATCH_SIZE) {
|
||||||
|
return Flux.fromIterable(items);
|
||||||
|
}
|
||||||
|
return Flux.fromIterable(items).concatWith(fetchBatch(options, page + 1));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private String toCsvLine(AuditLog log) {
|
||||||
|
var spec = log.getSpec();
|
||||||
|
var statusCode = spec.getStatusCode();
|
||||||
|
// 结果语义与前端 isSuccessful 一致:2xx/3xx 成功,其余(含空)失败
|
||||||
|
var success = statusCode != null && statusCode >= 200 && statusCode < 400;
|
||||||
|
return String.join(",",
|
||||||
|
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||||
|
escape(spec.getUsername()),
|
||||||
|
escape(spec.getMethod()),
|
||||||
|
escape(spec.getResourceType()),
|
||||||
|
escape(spec.getResourceName()),
|
||||||
|
escape(spec.getPath()),
|
||||||
|
escape(OperationDescription.describe(
|
||||||
|
spec.getMethod(), spec.getResourceType(), spec.getPath())),
|
||||||
|
escape(success ? "成功" : "失败"),
|
||||||
|
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||||
|
escape(spec.getRemoteIp()),
|
||||||
|
escape(spec.getUserAgent()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatTime(Instant instant) {
|
||||||
|
return instant == null ? "" : TIME_FORMATTER.format(instant);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSV 字段转义:含逗号/引号/换行的字段加引号、内部引号翻倍;
|
||||||
|
* 以 =、+、-、@、Tab、CR 开头的字段加单引号前缀(公式注入防护,Excel/WPS 显示时忽略)。
|
||||||
|
*/
|
||||||
|
static String escape(String value) {
|
||||||
|
if (value == null || value.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
var first = value.charAt(0);
|
||||||
|
var safe = first == '=' || first == '+' || first == '-' || first == '@'
|
||||||
|
|| first == '\t' || first == '\r'
|
||||||
|
? "'" + value
|
||||||
|
: value;
|
||||||
|
if (safe.indexOf(',') >= 0 || safe.indexOf('"') >= 0
|
||||||
|
|| safe.indexOf('\n') >= 0 || safe.indexOf('\r') >= 0) {
|
||||||
|
return '"' + safe.replace("\"", "\"\"") + '"';
|
||||||
|
}
|
||||||
|
return safe;
|
||||||
|
}
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import org.springframework.util.MultiValueMap;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import run.halo.app.extension.ListOptions;
|
||||||
|
import run.halo.app.extension.router.selector.FieldSelector;
|
||||||
|
import run.halo.app.extension.index.query.Condition;
|
||||||
|
import run.halo.app.extension.index.query.Queries;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 审计日志查询/导出共用的筛选条件构造(技术方案 5.3):
|
||||||
|
* fieldSelector 等值筛选、关键字、结果、时间区间 → {@link ListOptions}。
|
||||||
|
*
|
||||||
|
* <p>由查询端点与导出端点共用,非法参数抛 {@link IllegalArgumentException},
|
||||||
|
* 由端点层统一转 400(错误消息与拆分前保持一致)。
|
||||||
|
*/
|
||||||
|
final class AuditLogFilters {
|
||||||
|
|
||||||
|
/** fieldSelector 支持等值筛选的字段白名单(与已注册索引一一对应)。 */
|
||||||
|
static final Set<String> FILTERABLE_FIELDS =
|
||||||
|
Set.of("spec.username", "spec.resourceType", "spec.method", "spec.statusCode");
|
||||||
|
|
||||||
|
private AuditLogFilters() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从查询参数构造筛选条件,非法参数抛 {@link IllegalArgumentException}。 */
|
||||||
|
static ListOptions fromQueryParams(MultiValueMap<String, String> params) {
|
||||||
|
var conditions = new ArrayList<Condition>();
|
||||||
|
|
||||||
|
// fieldSelector 等值筛选:field=value(多个 fieldSelector 参数叠加 AND)
|
||||||
|
for (var term : params.getOrDefault("fieldSelector", List.of())) {
|
||||||
|
var idx = term.indexOf('=');
|
||||||
|
if (idx <= 0) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Invalid fieldSelector term, expect field=value: " + term);
|
||||||
|
}
|
||||||
|
var field = term.substring(0, idx).trim();
|
||||||
|
var value = term.substring(idx + 1).trim();
|
||||||
|
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||||
|
throw new IllegalArgumentException("Field not filterable: " + field);
|
||||||
|
}
|
||||||
|
conditions.add(Queries.equal(field, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||||
|
var keyword = params.getFirst("keyword");
|
||||||
|
if (StringUtils.hasText(keyword)) {
|
||||||
|
var kw = keyword.trim();
|
||||||
|
conditions.add(Queries.or(
|
||||||
|
Queries.contains("spec.resourceName", kw),
|
||||||
|
Queries.contains("spec.path", kw)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
||||||
|
var resultFilter = params.getFirst("result");
|
||||||
|
if (StringUtils.hasText(resultFilter)) {
|
||||||
|
switch (resultFilter.trim().toLowerCase()) {
|
||||||
|
case "success" -> {
|
||||||
|
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||||
|
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||||
|
}
|
||||||
|
case "failure" -> conditions.add(
|
||||||
|
Queries.greaterThan("spec.statusCode", "400", true));
|
||||||
|
default -> throw new IllegalArgumentException(
|
||||||
|
"Invalid result, expect success or failure: " + resultFilter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 时间区间(含边界,ISO-8601 Instant)
|
||||||
|
try {
|
||||||
|
var start = parseInstant(params.getFirst("startTime"));
|
||||||
|
var end = parseInstant(params.getFirst("endTime"));
|
||||||
|
if (start != null) {
|
||||||
|
conditions.add(Queries.greaterThan("metadata.creationTimestamp",
|
||||||
|
start.toString(), true));
|
||||||
|
}
|
||||||
|
if (end != null) {
|
||||||
|
conditions.add(Queries.lessThan("metadata.creationTimestamp",
|
||||||
|
end.toString(), true));
|
||||||
|
}
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Invalid time format, expect ISO-8601 instant: " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return conditions.isEmpty()
|
||||||
|
? new ListOptions().setFieldSelector(FieldSelector.all())
|
||||||
|
: new ListOptions().setFieldSelector(
|
||||||
|
FieldSelector.of(conditions.size() == 1 ? conditions.get(0)
|
||||||
|
: Queries.and(conditions.get(0),
|
||||||
|
conditions.subList(1, conditions.size())
|
||||||
|
.toArray(Condition[]::new))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Instant parseInstant(String value) {
|
||||||
|
if (!StringUtils.hasText(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Instant.parse(value.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
-82
@@ -1,10 +1,6 @@
|
|||||||
package run.halo.operationaudit.audit;
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.format.DateTimeParseException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.data.domain.Sort;
|
import org.springframework.data.domain.Sort;
|
||||||
@@ -19,31 +15,28 @@ import run.halo.app.extension.GroupVersion;
|
|||||||
import run.halo.app.extension.ListOptions;
|
import run.halo.app.extension.ListOptions;
|
||||||
import run.halo.app.extension.PageRequestImpl;
|
import run.halo.app.extension.PageRequestImpl;
|
||||||
import run.halo.app.extension.ReactiveExtensionClient;
|
import run.halo.app.extension.ReactiveExtensionClient;
|
||||||
import run.halo.app.extension.router.selector.FieldSelector;
|
|
||||||
import run.halo.app.extension.index.query.Condition;
|
|
||||||
import run.halo.app.extension.index.query.Queries;
|
|
||||||
import run.halo.operationaudit.audit.AuditLog;
|
import run.halo.operationaudit.audit.AuditLog;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 自有查询端点(技术方案 5.3 / 风险项 #2):
|
* 自有查询/导出端点(技术方案 5.3 / 风险项 #2):
|
||||||
*
|
*
|
||||||
* <p>经源码级验证(v2.26.1 FieldSelectorConverter),Halo 原生列表 API 的 fieldSelector
|
* <p>经源码级验证(v2.26.1 FieldSelectorConverter),Halo 原生列表 API 的 fieldSelector
|
||||||
* 仅支持 =/!=/IN 等值操作符,不支持时间区间与模糊匹配,因此按技术方案预案启用插件自有
|
* 仅支持 =/!=/IN 等值操作符,不支持时间区间与模糊匹配,因此按技术方案预案启用插件自有
|
||||||
* 查询端点,内部走索引 Query 实现(无内存分页),UI 调用方式不变。
|
* 查询端点,内部走索引 Query 实现(无内存分页),UI 调用方式不变。
|
||||||
|
*
|
||||||
|
* <p>筛选条件构造抽到 {@link AuditLogFilters} 供查询(分页 JSON)与导出(全量 CSV,
|
||||||
|
* 见 {@link AuditLogCsvExporter})共用。
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class AuditQueryEndpoint implements CustomEndpoint {
|
public class AuditQueryEndpoint implements CustomEndpoint {
|
||||||
|
|
||||||
/** fieldSelector 支持等值筛选的字段白名单(与已注册索引一一对应)。 */
|
|
||||||
private static final Set<String> FILTERABLE_FIELDS =
|
|
||||||
Set.of("spec.username", "spec.resourceType", "spec.method", "spec.statusCode");
|
|
||||||
|
|
||||||
/** 每页大小上限,防止误用拖垮查询。 */
|
/** 每页大小上限,防止误用拖垮查询。 */
|
||||||
static final int MAX_PAGE_SIZE = 100;
|
static final int MAX_PAGE_SIZE = 100;
|
||||||
|
|
||||||
private final ReactiveExtensionClient client;
|
private final ReactiveExtensionClient client;
|
||||||
|
private final AuditLogCsvExporter csvExporter;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public GroupVersion groupVersion() {
|
public GroupVersion groupVersion() {
|
||||||
@@ -59,6 +52,12 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
|||||||
+ "关键字(resourceName/path 模糊)、结果(success/failure)、"
|
+ "关键字(resourceName/path 模糊)、结果(success/failure)、"
|
||||||
+ "时间区间(含边界)")
|
+ "时间区间(含边界)")
|
||||||
.build())
|
.build())
|
||||||
|
.GET("auditlogs/-/export", this::export, builder -> builder
|
||||||
|
.operationId("ExportAuditLogs")
|
||||||
|
.description("按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS "
|
||||||
|
+ "可直接打开):筛选参数与 query 完全一致,不分页全量导出,"
|
||||||
|
+ "按时间升序输出")
|
||||||
|
.build())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,77 +68,29 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
|||||||
var size = Math.min(Math.max(parseInt(params.getFirst("size"), 20), 1), MAX_PAGE_SIZE);
|
var size = Math.min(Math.max(parseInt(params.getFirst("size"), 20), 1), MAX_PAGE_SIZE);
|
||||||
var sort = parseSort(params.getFirst("sort"));
|
var sort = parseSort(params.getFirst("sort"));
|
||||||
|
|
||||||
var conditions = new ArrayList<Condition>();
|
ListOptions options;
|
||||||
|
|
||||||
// fieldSelector 等值筛选:field=value(多个 fieldSelector 参数叠加 AND)
|
|
||||||
for (var term : params.getOrDefault("fieldSelector", List.of())) {
|
|
||||||
var idx = term.indexOf('=');
|
|
||||||
if (idx <= 0) {
|
|
||||||
return badRequest("Invalid fieldSelector term, expect field=value: " + term);
|
|
||||||
}
|
|
||||||
var field = term.substring(0, idx).trim();
|
|
||||||
var value = term.substring(idx + 1).trim();
|
|
||||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
|
||||||
return badRequest("Field not filterable: " + field);
|
|
||||||
}
|
|
||||||
conditions.add(Queries.equal(field, value));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
|
||||||
var keyword = params.getFirst("keyword");
|
|
||||||
if (StringUtils.hasText(keyword)) {
|
|
||||||
var kw = keyword.trim();
|
|
||||||
conditions.add(Queries.or(
|
|
||||||
Queries.contains("spec.resourceName", kw),
|
|
||||||
Queries.contains("spec.path", kw)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
|
||||||
var resultFilter = params.getFirst("result");
|
|
||||||
if (StringUtils.hasText(resultFilter)) {
|
|
||||||
switch (resultFilter.trim().toLowerCase()) {
|
|
||||||
case "success" -> {
|
|
||||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
|
||||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
|
||||||
}
|
|
||||||
case "failure" -> conditions.add(Queries.greaterThan("spec.statusCode", "400", true));
|
|
||||||
default -> {
|
|
||||||
return badRequest("Invalid result, expect success or failure: "
|
|
||||||
+ resultFilter);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 时间区间(含边界,ISO-8601 Instant)
|
|
||||||
try {
|
try {
|
||||||
var start = parseInstant(params.getFirst("startTime"));
|
options = AuditLogFilters.fromQueryParams(params);
|
||||||
var end = parseInstant(params.getFirst("endTime"));
|
} catch (IllegalArgumentException e) {
|
||||||
if (start != null) {
|
return badRequest(e.getMessage());
|
||||||
conditions.add(Queries.greaterThan("metadata.creationTimestamp",
|
|
||||||
start.toString(), true));
|
|
||||||
}
|
|
||||||
if (end != null) {
|
|
||||||
conditions.add(Queries.lessThan("metadata.creationTimestamp",
|
|
||||||
end.toString(), true));
|
|
||||||
}
|
|
||||||
} catch (DateTimeParseException e) {
|
|
||||||
return badRequest("Invalid time format, expect ISO-8601 instant: "
|
|
||||||
+ e.getMessage());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var options = conditions.isEmpty()
|
|
||||||
? new ListOptions().setFieldSelector(FieldSelector.all())
|
|
||||||
: new ListOptions().setFieldSelector(
|
|
||||||
FieldSelector.of(conditions.size() == 1 ? conditions.get(0)
|
|
||||||
: Queries.and(conditions.get(0),
|
|
||||||
conditions.subList(1, conditions.size())
|
|
||||||
.toArray(Condition[]::new))));
|
|
||||||
|
|
||||||
var pageable = PageRequestImpl.of(page, size, sort);
|
var pageable = PageRequestImpl.of(page, size, sort);
|
||||||
return client.listBy(AuditLog.class, options, pageable)
|
return client.listBy(AuditLog.class, options, pageable)
|
||||||
.flatMap(result -> ServerResponse.ok().bodyValue(result));
|
.flatMap(result -> ServerResponse.ok().bodyValue(result));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 导出端点:筛选参数与 query 一致,全量流式 CSV 附件下载。 */
|
||||||
|
private Mono<ServerResponse> export(ServerRequest request) {
|
||||||
|
ListOptions options;
|
||||||
|
try {
|
||||||
|
options = AuditLogFilters.fromQueryParams(request.queryParams());
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return badRequest(e.getMessage());
|
||||||
|
}
|
||||||
|
return csvExporter.exportResponse(options);
|
||||||
|
}
|
||||||
|
|
||||||
private static Mono<ServerResponse> badRequest(String message) {
|
private static Mono<ServerResponse> badRequest(String message) {
|
||||||
return ServerResponse.badRequest().bodyValue(java.util.Map.of("message", message));
|
return ServerResponse.badRequest().bodyValue(java.util.Map.of("message", message));
|
||||||
}
|
}
|
||||||
@@ -169,11 +120,4 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
|||||||
var descending = parts.length < 2 || !"asc".equalsIgnoreCase(parts[1].trim());
|
var descending = parts.length < 2 || !"asc".equalsIgnoreCase(parts[1].trim());
|
||||||
return Sort.by(descending ? Sort.Order.desc(field) : Sort.Order.asc(field));
|
return Sort.by(descending ? Sort.Order.desc(field) : Sort.Order.asc(field));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Instant parseInstant(String value) {
|
|
||||||
if (!StringUtils.hasText(value)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return Instant.parse(value.trim());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+112
@@ -0,0 +1,112 @@
|
|||||||
|
package run.halo.operationaudit.audit;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作描述(这条操作真正干了什么):由 method / resourceType / path 推导中文短语,
|
||||||
|
* 如 登录、登出、新建用户、修改文章、发布文章、启用插件、修改密码。
|
||||||
|
*
|
||||||
|
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code describeOperation} 保持一致
|
||||||
|
* (同一套 RESOURCE_LABELS / METHOD_VERBS / SUB_ACTION_VERBS / SUB_ACTION_PHRASES
|
||||||
|
* 映射与子动作解析规则),两处需同步修改。推导纯用于展示/导出,不落库:
|
||||||
|
* 历史记录同样适用;未识别的子动作回退为「动词 + 资源名」,
|
||||||
|
* 未识别的资源类型直接使用原始 resourceType。
|
||||||
|
*/
|
||||||
|
final class OperationDescription {
|
||||||
|
|
||||||
|
/** 资源类型的中文展示名(未知类型回退原始值)。 */
|
||||||
|
private static final Map<String, String> RESOURCE_LABELS = Map.ofEntries(
|
||||||
|
Map.entry("posts", "文章"),
|
||||||
|
Map.entry("singlepages", "页面"),
|
||||||
|
Map.entry("comments", "评论"),
|
||||||
|
Map.entry("replies", "回复"),
|
||||||
|
Map.entry("users", "用户"),
|
||||||
|
Map.entry("roles", "角色"),
|
||||||
|
Map.entry("settings", "设置"),
|
||||||
|
Map.entry("configmaps", "配置"),
|
||||||
|
Map.entry("plugins", "插件"),
|
||||||
|
Map.entry("themes", "主题"),
|
||||||
|
Map.entry("attachments", "附件"),
|
||||||
|
Map.entry("menus", "菜单"),
|
||||||
|
Map.entry("categories", "分类"),
|
||||||
|
Map.entry("tags", "标签"));
|
||||||
|
|
||||||
|
/** 动作方法的基础动词(未知方法回退原始值)。 */
|
||||||
|
private static final Map<String, String> METHOD_VERBS = Map.of(
|
||||||
|
"POST", "新建",
|
||||||
|
"PUT", "修改",
|
||||||
|
"PATCH", "修改",
|
||||||
|
"DELETE", "删除",
|
||||||
|
"GET", "查看");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 子资源动作段({@code /apis/.../{plural}/{name}/{action}} 的 action)→ 动词,
|
||||||
|
* 与资源名拼接成短语,如 publish + 文章 = 发布文章。
|
||||||
|
*/
|
||||||
|
private static final Map<String, String> SUB_ACTION_VERBS = Map.ofEntries(
|
||||||
|
Map.entry("publish", "发布"),
|
||||||
|
Map.entry("unpublish", "取消发布"),
|
||||||
|
Map.entry("recycle", "移入回收站"),
|
||||||
|
Map.entry("restore", "恢复"),
|
||||||
|
Map.entry("enable", "启用"),
|
||||||
|
Map.entry("disable", "停用"),
|
||||||
|
Map.entry("upgrade", "升级"),
|
||||||
|
Map.entry("uninstall", "卸载"),
|
||||||
|
Map.entry("reload", "重载"),
|
||||||
|
Map.entry("activation", "启用"),
|
||||||
|
Map.entry("reply", "回复"),
|
||||||
|
Map.entry("recalculate", "重新统计"));
|
||||||
|
|
||||||
|
/** 子资源动作段 → 完整短语(不拼接资源名)。 */
|
||||||
|
private static final Map<String, String> SUB_ACTION_PHRASES = Map.of(
|
||||||
|
"password", "修改密码",
|
||||||
|
"resetpassword", "重置密码");
|
||||||
|
|
||||||
|
private OperationDescription() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 推导操作中文描述。 */
|
||||||
|
static String describe(String method, String resourceType, String path) {
|
||||||
|
var cleanPath = pathWithoutQuery(path);
|
||||||
|
if ("auth".equals(resourceType) || "/login".equals(cleanPath)
|
||||||
|
|| "/logout".equals(cleanPath)) {
|
||||||
|
if ("/login".equals(cleanPath)) {
|
||||||
|
return "登录";
|
||||||
|
}
|
||||||
|
if ("/logout".equals(cleanPath)) {
|
||||||
|
return "登出";
|
||||||
|
}
|
||||||
|
return "认证操作";
|
||||||
|
}
|
||||||
|
var label = RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
|
||||||
|
var verb = METHOD_VERBS.getOrDefault(method, method);
|
||||||
|
// /apis/{group}/{version}/{plural}/{name}/{action}:
|
||||||
|
// 去掉空段后 segments 为 [apis, group, version, plural, name, action],
|
||||||
|
// 子动作段为 segments[5]
|
||||||
|
var segments = Arrays.stream(cleanPath.split("/"))
|
||||||
|
.filter(segment -> !segment.isEmpty())
|
||||||
|
.toArray(String[]::new);
|
||||||
|
var action = segments.length >= 6 ? segments[5].toLowerCase() : null;
|
||||||
|
if (action != null) {
|
||||||
|
var phrase = SUB_ACTION_PHRASES.get(action);
|
||||||
|
if (phrase != null) {
|
||||||
|
return phrase;
|
||||||
|
}
|
||||||
|
var subVerb = SUB_ACTION_VERBS.get(action);
|
||||||
|
if (subVerb != null) {
|
||||||
|
return subVerb + label;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return verb + label;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 剥离路径的查询串(spec.path 存的是含查询串的完整路径)。 */
|
||||||
|
private static String pathWithoutQuery(String path) {
|
||||||
|
if (path == null || path.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
var queryStart = path.indexOf('?');
|
||||||
|
return queryStart >= 0 ? path.substring(0, queryStart) : path;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,8 @@ rules:
|
|||||||
# verbs 仅 get/list(技术方案 D4):被授权角色技术上也无法删除/编辑审计记录
|
# verbs 仅 get/list(技术方案 D4):被授权角色技术上也无法删除/编辑审计记录
|
||||||
# auditlogs/query 为自有查询端点 /apis/.../auditlogs/-/query 的 RBAC 资源组合
|
# auditlogs/query 为自有查询端点 /apis/.../auditlogs/-/query 的 RBAC 资源组合
|
||||||
# (资源 auditlogs + 子资源 query,请求动词 get)
|
# (资源 auditlogs + 子资源 query,请求动词 get)
|
||||||
|
# auditlogs/export 为自有导出端点 /apis/.../auditlogs/-/export 的 RBAC 资源组合
|
||||||
|
# (资源 auditlogs + 子资源 export,请求动词 get;只读导出,无写入语义)
|
||||||
- apiGroups: ["audit.guichumo.com"]
|
- apiGroups: ["audit.guichumo.com"]
|
||||||
resources: ["auditlogs", "auditlogs/query"]
|
resources: ["auditlogs", "auditlogs/query", "auditlogs/export"]
|
||||||
verbs: ["get", "list"]
|
verbs: ["get", "list"]
|
||||||
|
|||||||
+261
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -30,7 +30,7 @@ class AuditQueryEndpointTest {
|
|||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
client = mock(ReactiveExtensionClient.class);
|
client = mock(ReactiveExtensionClient.class);
|
||||||
var endpoint = new AuditQueryEndpoint(client);
|
var endpoint = new AuditQueryEndpoint(client, mock(AuditLogCsvExporter.class));
|
||||||
// 复现生产环境挂载方式(CustomEndpointsBuilder 在 /apis/{groupVersion} 下 nest)
|
// 复现生产环境挂载方式(CustomEndpointsBuilder 在 /apis/{groupVersion} 下 nest)
|
||||||
var mounted = org.springframework.web.reactive.function.server.RouterFunctions.nest(
|
var mounted = org.springframework.web.reactive.function.server.RouterFunctions.nest(
|
||||||
org.springframework.web.reactive.function.server.RequestPredicates.path(
|
org.springframework.web.reactive.function.server.RequestPredicates.path(
|
||||||
|
|||||||
+103
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
// 结构性回归测试:不渲染组件,仅检查 SFC 源码中的导出功能链路。
|
||||||
|
// 导出为按当前筛选条件的全量 CSV 下载:工具栏「导出」按钮 → fetch 导出端点
|
||||||
|
// (筛选参数与 query 一致,但去掉分页参数)→ blob 触发 a[download] 下载,
|
||||||
|
// 期间按钮进入 loading、失败走顶部 VAlert 错误提示。
|
||||||
|
// 历史上本功能不存在,本测试锁定端点路径与下载链路形态,防止路径漂移或链路残缺。
|
||||||
|
const sfc = readFileSync(fileURLToPath(new URL('./AuditLogList.vue', import.meta.url)), 'utf-8')
|
||||||
|
|
||||||
|
describe('AuditLogList 导出', () => {
|
||||||
|
it('声明与后端一致的导出端点路径', () => {
|
||||||
|
expect(sfc).toContain(
|
||||||
|
"const EXPORT_ENDPOINT =\n '/apis/audit.guichumo.com/v1alpha1/auditlogs/-/export'",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('工具栏导出按钮:IconSave 图标、loading 绑定 exporting、点击 exportLogs', () => {
|
||||||
|
// 导出按钮位于 VPageHeader #actions 的 VSpace 内,与「刷新」并列
|
||||||
|
const actionsStart = sfc.indexOf('<template #actions>')
|
||||||
|
expect(actionsStart).toBeGreaterThan(-1)
|
||||||
|
const actionsEnd = sfc.indexOf('</VSpace>', actionsStart)
|
||||||
|
const actions = sfc.slice(actionsStart, actionsEnd)
|
||||||
|
expect(actions).toMatch(/<VButton :loading="exporting"[^>]*@click="exportLogs">/)
|
||||||
|
expect(actions).toContain('<IconSave class="h-full w-full" />')
|
||||||
|
expect(actions).toContain('导出')
|
||||||
|
expect(actions).toContain('刷新')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('导出前去掉分页参数(导出为全量接口)', () => {
|
||||||
|
const fnStart = sfc.indexOf('async function exportLogs()')
|
||||||
|
expect(fnStart).toBeGreaterThan(-1)
|
||||||
|
const fn = sfc.slice(fnStart, sfc.indexOf('function resetFilter()', fnStart))
|
||||||
|
expect(fn).toContain('new URLSearchParams(buildQuery())')
|
||||||
|
expect(fn).toContain("params.delete('page')")
|
||||||
|
expect(fn).toContain("params.delete('size')")
|
||||||
|
})
|
||||||
|
|
||||||
|
it('下载链路:fetch 非 ok 报错进 VAlert,blob → createObjectURL → a[download]', () => {
|
||||||
|
const fnStart = sfc.indexOf('async function exportLogs()')
|
||||||
|
const fn = sfc.slice(fnStart, sfc.indexOf('function resetFilter()', fnStart))
|
||||||
|
// 错误语义与查询一致:HTTP 非 2xx 抛错并写入 error(顶部 VAlert 展示)
|
||||||
|
expect(fn).toMatch(/throw new Error\(`导出失败(HTTP \$\{response\.status\})`\)/)
|
||||||
|
expect(fn).toContain('error.value = e instanceof Error ? e.message : String(e)')
|
||||||
|
expect(fn).toContain('await response.blob()')
|
||||||
|
expect(fn).toContain('URL.createObjectURL(blob)')
|
||||||
|
expect(fn).toMatch(/anchor\.download = exportFilename\(\)/)
|
||||||
|
expect(fn).toContain('anchor.click()')
|
||||||
|
expect(fn).toContain('URL.revokeObjectURL(url)')
|
||||||
|
// 无论成败都复位按钮 loading
|
||||||
|
expect(fn).toMatch(/finally\s*\{\s*exporting\.value = false\s*\}/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('导出文件名不含冒号/空格(Windows 文件名非法字符)', () => {
|
||||||
|
const fnStart = sfc.indexOf('function exportFilename()')
|
||||||
|
expect(fnStart).toBeGreaterThan(-1)
|
||||||
|
const fn = sfc.slice(fnStart, sfc.indexOf('/** 按当前筛选条件导出全部记录', fnStart))
|
||||||
|
expect(fn).toContain("audit-logs-${now.getFullYear()}")
|
||||||
|
expect(fn).not.toMatch(/getMinutes\(\)\}:/) // 不出现冒号拼接
|
||||||
|
expect(fn).toMatch(/\.csv/)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
VSpace,
|
VSpace,
|
||||||
VAlert,
|
VAlert,
|
||||||
IconRefreshLine,
|
IconRefreshLine,
|
||||||
|
IconSave,
|
||||||
} from '@halo-dev/components'
|
} from '@halo-dev/components'
|
||||||
import type { AuditLog, ListResult } from '@/utils/audit'
|
import type { AuditLog, ListResult } from '@/utils/audit'
|
||||||
import {
|
import {
|
||||||
@@ -28,12 +29,17 @@ import AuditLogDetail from './AuditLogDetail.vue'
|
|||||||
const QUERY_ENDPOINT =
|
const QUERY_ENDPOINT =
|
||||||
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query'
|
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query'
|
||||||
|
|
||||||
|
/** 导出端点路径:筛选参数与 query 一致,全量 CSV 附件下载(与 AuditQueryEndpoint 保持一致)。 */
|
||||||
|
const EXPORT_ENDPOINT =
|
||||||
|
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/export'
|
||||||
|
|
||||||
const RESOURCE_TYPES = [
|
const RESOURCE_TYPES = [
|
||||||
'posts', 'comments', 'users', 'roles', 'auth', 'settings', 'configmaps',
|
'posts', 'comments', 'users', 'roles', 'auth', 'settings', 'configmaps',
|
||||||
'plugins', 'themes', 'attachments', 'menus', 'categories', 'tags',
|
'plugins', 'themes', 'attachments', 'menus', 'categories', 'tags',
|
||||||
]
|
]
|
||||||
|
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
|
const exporting = ref(false)
|
||||||
const error = ref('')
|
const error = ref('')
|
||||||
const logs = ref<AuditLog[]>([])
|
const logs = ref<AuditLog[]>([])
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
@@ -115,6 +121,43 @@ async function fetchLogs() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 导出文件名:audit-logs-<本地时间 yyyyMMdd-HHmmss>.csv(冒号/空格在文件名中非法)。 */
|
||||||
|
function exportFilename(): string {
|
||||||
|
const now = new Date()
|
||||||
|
const pad = (n: number) => String(n).padStart(2, '0')
|
||||||
|
return (
|
||||||
|
`audit-logs-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}` +
|
||||||
|
`-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.csv`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按当前筛选条件导出全部记录:fetch → blob → 触发下载,失败进顶部错误提示。 */
|
||||||
|
async function exportLogs() {
|
||||||
|
exporting.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
// 导出为全量接口,无需分页参数
|
||||||
|
const params = new URLSearchParams(buildQuery())
|
||||||
|
params.delete('page')
|
||||||
|
params.delete('size')
|
||||||
|
const response = await fetch(`${EXPORT_ENDPOINT}?${params.toString()}`)
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`导出失败(HTTP ${response.status})`)
|
||||||
|
}
|
||||||
|
const blob = await response.blob()
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const anchor = document.createElement('a')
|
||||||
|
anchor.href = url
|
||||||
|
anchor.download = exportFilename()
|
||||||
|
anchor.click()
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
} finally {
|
||||||
|
exporting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function resetFilter() {
|
function resetFilter() {
|
||||||
filterUsername.value = ''
|
filterUsername.value = ''
|
||||||
filterResourceType.value = ''
|
filterResourceType.value = ''
|
||||||
@@ -153,6 +196,12 @@ onMounted(fetchLogs)
|
|||||||
</template>
|
</template>
|
||||||
<template #actions>
|
<template #actions>
|
||||||
<VSpace>
|
<VSpace>
|
||||||
|
<VButton :loading="exporting" type="default" @click="exportLogs">
|
||||||
|
<template #icon>
|
||||||
|
<IconSave class="h-full w-full" />
|
||||||
|
</template>
|
||||||
|
导出
|
||||||
|
</VButton>
|
||||||
<VButton :loading="loading" type="default" @click="fetchLogs">
|
<VButton :loading="loading" type="default" @click="fetchLogs">
|
||||||
<template #icon>
|
<template #icon>
|
||||||
<IconRefreshLine class="h-full w-full" />
|
<IconRefreshLine class="h-full w-full" />
|
||||||
|
|||||||
Reference in New Issue
Block a user