feat: 登录失败记录尝试的用户名(P0-1,告警/落库/CSV)

- 新增 LoginAttemptCapture:为登录端点单独缓存请求体(表单/JSON 双形态,
  Content-Length 预检 + 64KB 上限,下游可重复读),字段白名单制仅提取
  username,兜底经现有敏感字段脱敏规则(ChangeDiffEngine)复核,
  密码绝不提取落库;任何失败静默降级,不影响登录主流程
- AuditLogSpec 新增 spec.attemptedUsername(不建索引),AuditRecorder 透传落库
- 告警负载 data 新增 attemptedUsername,content 增加尝试的账号段
- CSV 导出新增"尝试用户"列(操作者之后)
- 详情抽屉展示"尝试用户"(仅登录请求落库时显示)
- 更新 README(功能/告警负载示例/已知局限移除对应条目/技术说明)
This commit is contained in:
2026-11-22 00:06:13 +08:00
parent cb86a3d305
commit 08e7bd8a12
16 changed files with 662 additions and 106 deletions
+24 -12
View File
@@ -9,7 +9,8 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
- **操作记录**:已登录用户对后台 API(`/apis/**`)的全部写操作(POST/PUT/DELETE/PATCH),
一条通用规则覆盖文章、页面、评论、用户、设置、主题、插件启停、附件等所有管理面操作;
另捕获 `/login`、`/logout`(登录成功/失败/登出)。
另捕获 `/login`、`/logout`(登录成功/失败/登出),登录请求白名单提取尝试的用户名落库
(`spec.attemptedUsername`,密码等其余字段绝不落库,登录失败时操作者记"未知用户")。
- **系统内部变更**:定时发布等非页面操作触发的资源变更经扩展模型 Watcher 通道补记,
执行者记为 "system"(Console 展示为"系统");只记录用户可写面有实际变化的更新/删除,
并附字段级新旧值,与页面/API 操作区分归属、不重复记录。
@@ -20,11 +21,11 @@ Halo 2.x 操作审计插件:回答"**谁、在什么时候、对什么资源
语义动作/结果/时间区间/关键字)+ 分页 + 只读详情抽屉(含原始 JSON)。不提供任何删除/修改入口。
- **导出 CSV**:列表页「导出」按钮按当前筛选条件导出全部记录——后端全量流式生成
(UTF-8 BOM + `\r\n`,Excel/WPS 双击打开中文不乱码),列与界面一致(操作时间、操作者、
动作、资源类型、资源名称、路径、操作描述、结果、状态码、来源 IP、User-Agent),
含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。
尝试用户、动作、资源类型、资源名称、路径、操作描述、变更、结果、状态码、来源 IP、
User-Agent),含公式注入防护;导出为只读操作,走 RBAC 资源 `auditlogs/export`。
- **登录失败告警**:统计窗口内登录失败达到阈值时向 Webhook 地址异步推送 JSON 告警
(默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零);独立于审计开关,
在插件设置「告警通知」中配置(默认关闭)。
(默认 5 分钟窗口 / 5 次,告警后窗口重开防轰炸,登录成功立即清零;内容含尝试的用户名,
可区分定向撞库与无差别扫描);独立于审计开关,在插件设置「告警通知」中配置(默认关闭)。
- **保留与清理**:插件设置(审计开关、保留天数 7~∞,默认 90),每日凌晨自动清理过期记录,
启动时补跑一次。
- **权限**:默认仅超级管理员可见;附带只读角色模板 `role-template-audit-view`
@@ -65,13 +66,21 @@ Console「插件 → 操作审计 → 设置」:
{
"type": "login-failure",
"title": "操作审计告警:登录失败",
"content": "5 分钟内出现 5 次登录失败,最近一次来自 1.2.3.4(Mozilla/5.0 ...)。
可在 Console「操作审计」查看详情。",
"content": "5 分钟内出现 5 次登录失败,最近一次来自 1.2.3.4(Mozilla/5.0 ...),
尝试的账号:admin。可在 Console「操作审计」查看详情。",
"timestamp": "2026-11-21T12:34:56Z",
"data": { "failures": 5, "windowMinutes": 5, "remoteIp": "1.2.3.4", "userAgent": "..." }
"data": {
"failures": 5,
"windowMinutes": 5,
"remoteIp": "1.2.3.4",
"userAgent": "...",
"attemptedUsername": "admin"
}
}
```
`attemptedUsername` 为登录请求体中白名单提取的尝试用户名,提取失败时为 `null`。
不内置钉钉、企业微信、飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
## 模型 group 与权限标识
@@ -86,8 +95,6 @@ Console「插件 → 操作审计 → 设置」:
## 已知局限(对应产品设计第 7 节)
- 登录失败时无法得知尝试的用户名(解析请求体留到 V2),记为"未知用户";
登录失败告警同样不含尝试的用户名,仅含失败次数与最近一次来源 IP/User-Agent。
- 系统内部变更仅覆盖更新/删除两类事件:纯内部新建(引导初始化、插件安装自建配置等)
不记录(几乎均伴随页面/API 操作,已被过滤器捕获)。
- 系统内部变更的描述由事件类型推导(更新/删除),无法像页面操作那样区分"定时发布/恢复"
@@ -126,8 +133,13 @@ Console「插件 → 操作审计 → 设置」:
(告警后重开窗口防轰炸,登录成功清零;状态为单例计数,无内存队列),设置经
`AlertSettingProvider`(60s TTL 缓存)读取、独立于审计开关;`AlertWebhookSender`
以 JSON POST 异步推送(fire-and-forget,超时 10 秒、失败不重试不抛出)。
- 关于测试:`./gradlew test`(当前 188 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、查询端点参数校验、导出 CSV
- 登录尝试用户名(功能评审 P0-1):`LoginAttemptCapture` 为登录端点单独缓存请求体
(表单/JSON 双形态,Content-Length 预检 + 64KB 上限,下游可重复读),字段白名单制
仅提取 `username` 并经现有敏感字段脱敏规则兜底,随 `spec.attemptedUsername` 落库
并进入告警负载;与审计开关、告警开关均无关(消费方各自决定是否使用)。
- 关于测试:`./gradlew test`(当前 209 个用例)覆盖捕获规则、资源解析、扩展资源路径解析、
HTTP 写标记、内部变更监听、快照、直写降级、过滤器行为、登录尝试用户名提取
(表单/JSON/白名单/脱敏兜底/降级)、查询端点参数校验、导出 CSV
(BOM/表头/转义/注入防护/分批取数)、操作描述与语义动作标注推导(与前端
describeOperation / deriveAction 用例一一对应)、设置缓存与保留期清理、登录失败告警
(阈值窗口推进/告警防轰炸/成功清零/设置归一/真实 HTTP 推送与静默降级);Console UI 以
@@ -17,8 +17,8 @@ import run.halo.operationaudit.audit.RequestSnapshot;
* 结果为 2xx 视为登录成功并立即清零计数,其余视为失败累计。告警后重开窗口(同一攻击
* 波次不会连环轰炸,下次告警需再次达到阈值);窗口过期同样重开,无失败时不累计。
*
* <p>登录失败暂无法得知尝试的用户名(产品设计已知局限,与登录记录一致),告警负载
* 仅含失败次数、窗口、最近一次来源 IP 与 User-Agent。
* <p>告警负载含失败次数、窗口、最近一次来源 IP、User-Agent 与尝试的用户名
* (功能评审 P0-1:由捕获过滤器从登录请求体白名单提取,提取失败为 null)。
*
* <p>告警开关与阈值经 {@link AlertSettingProvider} 读取(60s TTL 缓存),与审计开关
* 相互独立。任何失败仅记 warn 日志,绝不影响登录主流程(产品设计原则 4)。
@@ -40,11 +40,15 @@ public class LoginFailureAlertService {
/**
* 登录结果回调:仅处理 POST /login 请求(成功 2xx 清零计数,失败累计告警)。
* 任何失败静默降级,不影响调用方。
*
* @param attemptedUsername 尝试的用户名(功能评审 P0-1,捕获过滤器白名单提取,
* 提取失败为 null)
*/
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode) {
public void onLoginResult(RequestSnapshot snapshot, Integer statusCode,
String attemptedUsername) {
var success = statusCode != null && statusCode >= 200 && statusCode < 300;
settingProvider.get().subscribe(
settings -> handle(settings, snapshot, success, Instant.now()),
settings -> handle(settings, snapshot, success, attemptedUsername, Instant.now()),
e -> log.warn("Failed to load alert settings, skip login alert for {}",
snapshot.getFullPath(), e));
}
@@ -53,7 +57,8 @@ public class LoginFailureAlertService {
* 阈值窗口判定与告警决策。now 由调用方传入(测试可控);发送在锁外执行。
* handle 包内可见以便测试直接驱动窗口推进。
*/
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success, Instant now) {
void handle(AlertSettings settings, RequestSnapshot snapshot, boolean success,
String attemptedUsername, Instant now) {
try {
if (!settings.enabledOrDefault()) {
return;
@@ -85,7 +90,7 @@ public class LoginFailureAlertService {
failureCount = 0;
}
sender.send(url, buildPayload(failures, settings.windowMinutesOrDefault(),
snapshot.getRemoteIp(), snapshot.getUserAgent(), now));
snapshot.getRemoteIp(), snapshot.getUserAgent(), attemptedUsername, now));
} catch (Exception e) {
// 告警为旁路功能,任何异常静默降级,绝不影响登录主流程
log.warn("Failed to handle login failure alert for {}",
@@ -98,16 +103,19 @@ public class LoginFailureAlertService {
* data 供程序化消费方取结构化字段。
*/
static Map<String, Object> buildPayload(int failures, int windowMinutes, String remoteIp,
String userAgent, Instant timestamp) {
String userAgent, String attemptedUsername, Instant timestamp) {
var content = windowMinutes + " 分钟内出现 " + failures + " 次登录失败,最近一次来自 "
+ remoteIp + (userAgent != null && !userAgent.isBlank()
? "(" + userAgent + ")" : "")
+ (attemptedUsername != null && !attemptedUsername.isBlank()
? ",尝试的账号:" + attemptedUsername : "")
+ "。可在 Console「操作审计」查看详情。";
var data = new LinkedHashMap<String, Object>();
data.put("failures", failures);
data.put("windowMinutes", windowMinutes);
data.put("remoteIp", remoteIp);
data.put("userAgent", userAgent);
data.put("attemptedUsername", attemptedUsername);
var payload = new LinkedHashMap<String, Object>();
payload.put("type", "login-failure");
payload.put("title", "操作审计告警:登录失败");
@@ -38,9 +38,12 @@ public class AuditLogCsvExporter {
/** 每批查询条数。 */
static final int EXPORT_BATCH_SIZE = 200;
/** CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要)。 */
/**
* CSV 列题头(与 UI 列表列对应;"变更"列为字段级变更紧凑摘要,
* "尝试用户"列为登录尝试的用户名,功能评审 P0-1)。
*/
private static final String CSV_HEADER =
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
"操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
private static final DataBufferFactory BUFFER_FACTORY =
DefaultDataBufferFactory.sharedInstance;
@@ -105,6 +108,7 @@ public class AuditLogCsvExporter {
return String.join(",",
escape(formatTime(log.getMetadata().getCreationTimestamp())),
escape(spec.getUsername()),
escape(spec.getAttemptedUsername()),
escape(spec.getMethod()),
escape(spec.getResourceType()),
escape(spec.getResourceName()),
@@ -14,6 +14,14 @@ public class AuditLogSpec {
/** 操作者用户名;登录失败记 {@link #UNKNOWN_USERNAME}。 */
private String username;
/**
* 登录尝试的用户名(功能评审 P0-1):仅 POST {@code /login} 请求从表单/JSON 请求体
* 白名单提取落库(密码等其余字段绝不提取);登录失败时操作者为
* {@link #UNKNOWN_USERNAME},本字段用于区分定向撞库与无差别扫描。
* 提取失败或非登录请求为 null;不建索引(无需按其筛选)。
*/
private String attemptedUsername;
/** HTTP 方法(动作),如 POST/PUT/DELETE/PATCH。 */
private String method;
@@ -35,9 +35,12 @@ public class AuditRecorder {
*
* <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值,
* 此处为防御性兜底,保证审计设置故障不影响捕获链路。
*
* @param attemptedUsername 登录尝试的用户名(功能评审 P0-1,仅 POST /login 请求
* 由 {@link LoginAttemptCapture} 提取,其余请求为 null)
*/
public void record(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) {
String username, String attemptedUsername) {
settingProvider.get().subscribe(
settings -> {
if (!settings.enabledOrDefault()) {
@@ -45,19 +48,19 @@ public class AuditRecorder {
snapshot.getMethod(), snapshot.getFullPath());
return;
}
write(snapshot, capture, statusCode, username);
write(snapshot, capture, statusCode, username, attemptedUsername);
},
e -> {
log.warn("Failed to load audit settings, record with defaults for {} {}",
snapshot.getMethod(), snapshot.getFullPath(), e);
write(snapshot, capture, statusCode, username);
write(snapshot, capture, statusCode, username, attemptedUsername);
});
}
private void write(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) {
String username, String attemptedUsername) {
try {
var auditLog = assemble(snapshot, capture, statusCode, username);
var auditLog = assemble(snapshot, capture, statusCode, username, attemptedUsername);
client.create(auditLog)
.subscribe(null, e -> log.warn("Failed to write audit log for {} {}",
snapshot.getMethod(), snapshot.getFullPath(), e));
@@ -144,11 +147,13 @@ public class AuditRecorder {
}
private AuditLog assemble(RequestSnapshot snapshot, ChangeCapture capture, Integer statusCode,
String username) {
String username, String attemptedUsername) {
var resolved = ResourceResolver.resolve(snapshot.getPath());
var spec = new AuditLogSpec();
spec.setUsername(username != null ? username : AuditLogSpec.UNKNOWN_USERNAME);
// 登录尝试用户名(功能评审 P0-1):仅登录请求由捕获器提取,其余请求为 null
spec.setAttemptedUsername(attemptedUsername);
spec.setMethod(snapshot.getMethod());
spec.setResourceType(resolved.resourceType());
// 语义动作标注(产品设计 V2):捕获时推导落库,供按语义动作筛选
@@ -366,8 +366,11 @@ final class ChangeDiffEngine {
out.add(entry);
}
/** 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。 */
private static boolean isSensitiveField(String field) {
/**
* 字段路径任一段命中敏感片段即脱敏(如 spec.password、metadata.annotations.x-token)。
* 包内可见:登录尝试用户名提取({@link LoginAttemptCapture})兜底复用同一规则。
*/
static boolean isSensitiveField(String field) {
for (var segment : field.split("\\.")) {
if (SENSITIVE_FIELD.matcher(segment).find()) {
return true;
@@ -0,0 +1,16 @@
package run.halo.operationaudit.audit;
import lombok.Getter;
import lombok.Setter;
/**
* 登录尝试上下文(功能评审 P0-1):请求期由 {@link LoginAttemptCapture} 一次性提取
* 尝试的用户名,响应完成后由捕获过滤器消费(落库 {@code spec.attemptedUsername} 与
* 告警负载)。非登录请求或提取失败时保持 null。
*/
public class LoginAttempt {
@Getter
@Setter
private volatile String attemptedUsername;
}
@@ -0,0 +1,170 @@
package run.halo.operationaudit.audit;
import static run.halo.operationaudit.audit.ChangeDiffEngine.REDACTED_VALUE;
import com.fasterxml.jackson.databind.JsonNode;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import run.halo.app.extension.Unstructured;
/**
* 登录尝试用户名提取(功能评审 P0-1):POST {@code /login} 的请求体为表单形态、
* 登录端点非注册模型,与 {@link ChangeCaptureManager} 的 JSON 缓存逻辑分开,
* 为登录端点单独补一条请求体读取:缓存请求体(下游可重复读)并提取尝试的用户名。
*
* <p>提取规则(安全边界):
* <ul>
* <li>字段白名单制:仅提取 {@code username},密码等其余字段绝不提取、绝不落库;</li>
* <li>兜底约束:提取值经现有敏感字段脱敏规则({@link ChangeDiffEngine})复核,
* 命中敏感字段名的值一律以 {@value ChangeDiffEngine#REDACTED_VALUE} 代替;</li>
* <li>请求体经 Content-Length 预检后以 {@value #MAX_BODY_BYTES} 字节为上限缓存,
* 与字段级变更捕获同款边界(分块传输/超限一律不读,仅不提取用户名)。</li>
* </ul>
*
* <p>登录端点同时接受表单({@code application/x-www-form-urlencoded})与 JSON 请求体,
* 两种形态均支持提取;不支持的形态与任何解析异常均静默降级为不提取(返回 null),
* 绝不影响登录主流程(设计原则 4)。提取结果写入 {@link LoginAttempt},与审计开关、
* 告警开关均无关(两种消费方各自决定是否使用)。
*/
@Slf4j
@Component
public class LoginAttemptCapture {
/** 登录请求体缓存上限(字节):登录表单极小,上限远小于字段级变更捕获。 */
static final int MAX_BODY_BYTES = 64 * 1024;
/** 提取字段白名单:仅用户名。密码等任何其他字段绝不提取。 */
static final Set<String> USERNAME_FIELDS = Set.of("username");
private static final String USERNAME_FIELD = "username";
/**
* 为登录请求缓存请求体并提取尝试的用户名。返回(可能包装了缓存请求体的)交换对象
* 供后续链路继续处理;返回的 Mono 永不报错、永不为空:任何失败均回退原 exchange。
*/
public Mono<ServerWebExchange> prepare(ServerWebExchange exchange, LoginAttempt attempt) {
var contentType = exchange.getRequest().getHeaders().getContentType();
if (!supported(contentType)) {
return Mono.just(exchange);
}
var contentLength = exchange.getRequest().getHeaders().getContentLength();
if (contentLength <= 0 || contentLength > MAX_BODY_BYTES) {
// 分块传输(无 Content-Length)或超限:不读请求体,避免中断流式请求
return Mono.just(exchange);
}
return DataBufferUtils.join(exchange.getRequest().getBody(), MAX_BODY_BYTES)
.map(joined -> {
var bytes = new byte[joined.readableByteCount()];
joined.read(bytes);
DataBufferUtils.release(joined);
attempt.setAttemptedUsername(extract(bytes, contentType));
return decorate(exchange, bytes);
})
.defaultIfEmpty(exchange)
.onErrorResume(e -> {
log.warn("Failed to capture login attempt body for username extraction", e);
return Mono.just(exchange);
});
}
/** 支持提取的请求体形态:表单或 JSON(登录端点仅接受这两种)。 */
static boolean supported(MediaType contentType) {
if (contentType == null) {
return false;
}
return contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)
|| ChangeCaptureManager.isJson(contentType);
}
/** 按内容类型分发提取;任何异常均静默返回 null,绝不抛出。 */
private static String extract(byte[] bytes, MediaType contentType) {
try {
if (contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
return usernameOfForm(new String(bytes, StandardCharsets.UTF_8));
}
return usernameOfJson(Unstructured.OBJECT_MAPPER.readTree(bytes));
} catch (Exception e) {
// 解析异常静默:不提取,不影响登录主流程
return null;
}
}
/**
* 表单体提取:仅取白名单字段的值(同名多值取最后一个),URL 编码解码失败回退原值。
*/
static String usernameOfForm(String body) {
if (body == null || body.isBlank()) {
return null;
}
try {
String found = null;
for (var pair : body.split("&")) {
var idx = pair.indexOf('=');
var name = safeDecode(idx < 0 ? pair : pair.substring(0, idx));
if (!USERNAME_FIELDS.contains(name)) {
continue;
}
var value = safeDecode(idx < 0 ? "" : pair.substring(idx + 1));
found = maskIfSensitive(name, value);
}
return StringUtils.hasText(found) ? found : null;
} catch (Exception e) {
// 表单解析异常静默:不提取,不影响登录主流程
return null;
}
}
/** JSON 体提取:仅取顶层白名单字段的标量值。 */
static String usernameOfJson(JsonNode root) {
if (root == null || !root.isObject()) {
return null;
}
var value = root.path(USERNAME_FIELD);
if (!value.isValueNode()) {
return null;
}
var text = value.asText();
return StringUtils.hasText(text) ? maskIfSensitive(USERNAME_FIELD, text) : null;
}
/**
* 兜底脱敏:白名单保证仅提取 username,若未来白名单调整后字段名命中现有敏感字段
* 规则({@link ChangeDiffEngine}),提取值一律以 {@value ChangeDiffEngine#REDACTED_VALUE}
* 代替,密码/密钥绝不落库。
*/
static String maskIfSensitive(String fieldName, String value) {
return ChangeDiffEngine.isSensitiveField(fieldName) ? REDACTED_VALUE : value;
}
/** URL 编码解码失败(如裸 %)回退原值,尽力提取、绝不抛出。 */
private static String safeDecode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (Exception e) {
return value;
}
}
/** 用缓存字节重建请求体(每次订阅独立 buffer),下游登录处理可正常读取。 */
private static ServerWebExchange decorate(ServerWebExchange exchange, byte[] body) {
var decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public Flux<DataBuffer> getBody() {
return Flux.defer(
() -> Mono.just(exchange.getResponse().bufferFactory().wrap(body)));
}
};
return exchange.mutate().request(decorated).build();
}
}
@@ -35,7 +35,9 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
*
* <p>登录失败告警(产品设计 V2「告警通知」):POST {@code /login} 请求结束时将结果
* (2xx 成功 / 其余失败)回调给 {@code LoginFailureAlertService},按阈值窗口推送
* Webhook;与审计开关相互独立。
* Webhook;与审计开关相互独立。尝试的用户名(功能评审 P0-1)由
* {@link LoginAttemptCapture} 在请求期从登录请求体白名单提取,随记录落库
* {@code spec.attemptedUsername} 并进入告警负载。
*/
@Component
@RequiredArgsConstructor
@@ -47,6 +49,7 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
private final AuditRecorder recorder;
private final ChangeCaptureManager captureManager;
private final HttpWriteMarker writeMarker;
private final LoginAttemptCapture loginAttemptCapture;
private final LoginFailureAlertService loginFailureAlertService;
@Override
@@ -67,7 +70,14 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
writeMarker.onRequestStart(request);
var snapshot = RequestSnapshot.of(request);
var capture = new ChangeCapture();
return captureManager.prepare(exchange, snapshot, capture)
var loginAttempt = new LoginAttempt();
// 登录请求先缓存请求体并提取尝试的用户名(P0-1),下游登录处理可重复读;
// 其余请求原样透传
var bodyPrepared = CaptureRule.isLoginAttempt(path, method)
? loginAttemptCapture.prepare(exchange, loginAttempt)
: Mono.just(exchange);
return bodyPrepared
.flatMap(prepared -> captureManager.prepare(prepared, snapshot, capture))
.flatMap(prepared -> chain.filter(prepared))
.transformDeferredContextual((mono, ctx) -> mono.doFinally(
signal -> {
@@ -75,12 +85,14 @@ public class OperationAuditWebFilter implements AfterSecurityWebFilter {
// 登录失败告警(产品设计 V2):POST /login 结束即回调结果,
// 2xx 清零计数、其余累计,独立于下方审计记录决策
if (CaptureRule.isLoginAttempt(path, method)) {
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange));
loginFailureAlertService.onLoginResult(snapshot, statusOf(exchange),
loginAttempt.getAttemptedUsername());
}
operatorOf(ctx, path).subscribe(
username -> {
if (shouldRecord(path, username)) {
recorder.record(snapshot, capture, statusOf(exchange), username);
recorder.record(snapshot, capture, statusOf(exchange), username,
loginAttempt.getAttemptedUsername());
}
},
e -> { /* 操作者解析失败同样静默:不打断响应,不重复抛出 */ });
@@ -67,12 +67,12 @@ class LoginFailureAlertServiceTest {
var snapshot = loginSnapshot();
var now = Instant.now();
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
verify(sender, never()).send(any(), any());
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, null, now);
var payload = capturedPayload();
assertThat(payload.get("type")).isEqualTo("login-failure");
@@ -86,7 +86,8 @@ class LoginFailureAlertServiceTest {
.containsEntry("failures", 3)
.containsEntry("windowMinutes", 5)
.containsEntry("remoteIp", "127.0.0.1")
.containsEntry("userAgent", "UA-1");
.containsEntry("userAgent", "UA-1")
.containsEntry("attemptedUsername", null);
}
@Test
@@ -96,11 +97,11 @@ class LoginFailureAlertServiceTest {
var now = Instant.now();
// 达到阈值告警一次后窗口重开:后续失败需重新累计,不会连环告警
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
verify(sender, times(1)).send(any(), any());
}
@@ -111,11 +112,11 @@ class LoginFailureAlertServiceTest {
var snapshot = loginSnapshot();
var now = Instant.now();
service.handle(settings, snapshot, false, now);
service.handle(settings, snapshot, false, now);
service.handle(settings, snapshot, false, null, now);
service.handle(settings, snapshot, false, null, now);
// 告警后窗口重开,再次累计到阈值 → 第二次告警
service.handle(settings, snapshot, false, now);
service.handle(settings, snapshot, false, now);
service.handle(settings, snapshot, false, null, now);
service.handle(settings, snapshot, false, null, now);
verify(sender, times(2)).send(any(), any());
}
@@ -127,13 +128,13 @@ class LoginFailureAlertServiceTest {
var now = Instant.now();
// 第一次失败开启窗口,10 分钟后窗口已过期 → 计数从新窗口重新开始
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now.plus(Duration.ofMinutes(10)));
service.handle(settings(3, 5), snapshot, false, now.plus(Duration.ofMinutes(10)));
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
verify(sender, never()).send(any(), any());
service.handle(settings(3, 5), snapshot, false, now.plus(Duration.ofMinutes(10)));
service.handle(settings(3, 5), snapshot, false, null, now.plus(Duration.ofMinutes(10)));
var payload = capturedPayload();
assertThat((Map<String, Object>) payload.get("data")).containsEntry("failures", 3);
@@ -145,16 +146,16 @@ class LoginFailureAlertServiceTest {
var snapshot = loginSnapshot();
var now = Instant.now();
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
// 登录成功立即清零:其后失败需重新累计
service.handle(settings(3, 5), snapshot, true, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, true, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
service.handle(settings(3, 5), snapshot, false, null, now);
verify(sender, never()).send(any(), any());
service.handle(settings(3, 5), snapshot, false, now);
service.handle(settings(3, 5), snapshot, false, null, now);
verify(sender, times(1)).send(any(), any());
}
@@ -163,7 +164,7 @@ class LoginFailureAlertServiceTest {
enableAlerts(1, 5);
var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 302);
service.onLoginResult(snapshot, 302, null);
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
}
@@ -173,8 +174,8 @@ class LoginFailureAlertServiceTest {
enableAlerts(1, 5);
var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 200);
service.onLoginResult(snapshot, 204);
service.onLoginResult(snapshot, 200, null);
service.onLoginResult(snapshot, 204, null);
verify(sender, never()).send(any(), any());
}
@@ -184,11 +185,38 @@ class LoginFailureAlertServiceTest {
enableAlerts(1, 5);
var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 401);
service.onLoginResult(snapshot, 401, null);
verify(sender, times(1)).send(eq(WEBHOOK_URL), any());
}
@Test
void shouldIncludeAttemptedUsernameInPayload() {
// 登录尝试用户名(功能评审 P0-1):进入负载 content 与 data,接收方可区分定向撞库
enableAlerts(1, 5);
var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 401, "admin");
var payload = capturedPayload();
assertThat((String) payload.get("content")).contains("尝试的账号:admin");
assertThat((Map<String, Object>) payload.get("data"))
.containsEntry("attemptedUsername", "admin");
}
@Test
void shouldOmitAttemptedUsernameSegmentWhenAbsent() {
enableAlerts(1, 5);
var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 401, null);
var payload = capturedPayload();
assertThat((String) payload.get("content")).doesNotContain("尝试的账号");
assertThat((Map<String, Object>) payload.get("data"))
.containsEntry("attemptedUsername", null);
}
@Test
void shouldSkipWhenAlertDisabled() {
when(settingProvider.get()).thenReturn(Mono.just(
@@ -196,8 +224,8 @@ class LoginFailureAlertServiceTest {
var snapshot = loginSnapshot();
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
service.onLoginResult(snapshot, 401);
service.onLoginResult(snapshot, 401);
service.onLoginResult(snapshot, 401, null);
service.onLoginResult(snapshot, 401, null);
verify(sender, never()).send(any(), any());
assertThat(service.failureCount).isZero();
@@ -209,7 +237,7 @@ class LoginFailureAlertServiceTest {
new AlertSettings(true, " ", 1, 5)));
var snapshot = loginSnapshot();
service.onLoginResult(snapshot, 401);
service.onLoginResult(snapshot, 401, null);
verify(sender, never()).send(any(), any());
}
@@ -219,7 +247,8 @@ class LoginFailureAlertServiceTest {
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
var snapshot = loginSnapshot();
assertThatCode(() -> service.onLoginResult(snapshot, 401)).doesNotThrowAnyException();
assertThatCode(() -> service.onLoginResult(snapshot, 401, null))
.doesNotThrowAnyException();
verify(sender, never()).send(any(), any());
}
@@ -230,7 +259,7 @@ class LoginFailureAlertServiceTest {
doThrow(new IllegalStateException("webhook broken"))
.when(sender).send(any(), any());
assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401))
assertThatCode(() -> service.onLoginResult(loginSnapshot(), 401, null))
.doesNotThrowAnyException();
}
@@ -241,7 +270,7 @@ class LoginFailureAlertServiceTest {
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.build());
service.onLoginResult(snapshot, 401);
service.onLoginResult(snapshot, 401, null);
var payload = capturedPayload();
assertThat((String) payload.get("content")).doesNotContain("()");
@@ -39,7 +39,7 @@ class AuditExportEndpointTest {
"/apis/" + AuditLog.GROUP + "/v1alpha1/auditlogs/-/export";
private static final String CSV_HEADER =
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
"操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent";
private ReactiveExtensionClient client;
private WebTestClient webClient;
@@ -57,13 +57,14 @@ class AuditExportEndpointTest {
}
private static AuditLog auditLog(String name, Instant creationTimestamp, String username,
String method, String resourceType, String resourceName, String path,
Integer statusCode, String remoteIp, String userAgent) {
String attemptedUsername, 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.setAttemptedUsername(attemptedUsername);
spec.setMethod(method);
spec.setResourceType(resourceType);
spec.setResourceName(resourceName);
@@ -94,11 +95,12 @@ class AuditExportEndpointTest {
void shouldExportCsvWithBomHeaderAndRows() {
var time = Instant.parse("2026-11-01T00:00:00Z");
stubSinglePage(List.of(
auditLog("auditlog-1", time, "admin", "POST", "users", "zhangsan",
auditLog("auditlog-1", time, "admin", null, "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")));
// 登录失败记录(功能评审 P0-1):尝试用户列为登录时尝试的用户名
auditLog("auditlog-2", time.plusSeconds(60), "unknown", "admin", "POST", "auth",
null, "/login", 401, "10.0.0.8", "Mozilla/5.0")));
var body = exportAndGetBody(EXPORT_URI);
@@ -106,16 +108,16 @@ class AuditExportEndpointTest {
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"
+ ",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");
+ ",unknown,admin,POST,auth,,/login,登录,,失败,401,10.0.0.8,Mozilla/5.0");
}
@Test
void shouldExportChangesColumnWhenRecordHasChanges() {
var time = Instant.parse("2026-11-04T00:00:00Z");
var log = auditLog("auditlog-1", time, "admin", "PUT", "posts", "abc",
var log = auditLog("auditlog-1", time, "admin", null, "PUT", "posts", "abc",
"/apis/content.halo.run/v1alpha1/posts/abc", 200, "127.0.0.1", "UA");
log.getSpec().setChanges(List.of(
change(ChangeType.UPDATED, "spec.title", "旧标题", "新标题"),
@@ -126,7 +128,7 @@ class AuditExportEndpointTest {
var lines = body.split("\r\n");
assertThat(lines[1]).isEqualTo(expectedTimeColumn(time)
+ ",admin,PUT,posts,abc,/apis/content.halo.run/v1alpha1/posts/abc"
+ ",admin,,PUT,posts,abc,/apis/content.halo.run/v1alpha1/posts/abc"
+ ",修改文章,修改 spec.title:旧标题 → 新标题;新增 spec.cover:c.png"
+ ",成功,200,127.0.0.1,UA");
}
@@ -152,7 +154,7 @@ class AuditExportEndpointTest {
void shouldEscapeSpecialCharactersAndFormulaInjection() {
stubSinglePage(List.of(
// 逗号与引号需加引号且内部引号翻倍;= 开头需加单引号前缀
auditLog("auditlog-1", Instant.parse("2026-11-02T00:00:00Z"), "a\"b", "PUT",
auditLog("auditlog-1", Instant.parse("2026-11-02T00:00:00Z"), "a\"b", null, "PUT",
"posts", "=sum(A1)", "/apis/content.halo.run/v1alpha1/posts/x,y", 200,
"127.0.0.1", "@evil")));
@@ -160,20 +162,20 @@ class AuditExportEndpointTest {
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\""
+ ",\"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)));
auditLog("auditlog-1", Instant.parse("2026-11-03T00:00:00Z"), "admin", null,
"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,,,修改主题,,失败,,,");
+ ",admin,,PATCH,themes,,,修改主题,,失败,,,");
}
@Test
@@ -229,8 +231,8 @@ class AuditExportEndpointTest {
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"));
auditLog("auditlog-401", Instant.parse("2026-11-01T00:00:00Z"), "admin", null,
"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)),
@@ -266,7 +268,7 @@ class AuditExportEndpointTest {
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,
"admin", null, "POST", "users", "user-" + i, "/apis/v1alpha1/users", 200,
"127.0.0.1", "UA"));
}
return items;
@@ -55,7 +55,7 @@ class AuditRecorderTest {
.header("User-Agent", "UA-1")
.build());
recorder.record(snapshot, new ChangeCapture(), 204, "admin");
recorder.record(snapshot, new ChangeCapture(), 204, "admin", null);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
@@ -78,7 +78,7 @@ class AuditRecorderTest {
@Test
void shouldUseUnknownUsernameWhenOperatorMissing() {
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null);
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401, null, null);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
@@ -89,11 +89,25 @@ class AuditRecorderTest {
assertThat(captor.getValue().getSpec().getStatusCode()).isEqualTo(401);
}
@Test
void shouldRecordAttemptedUsernameForLoginAttempt() {
// 登录尝试用户名(功能评审 P0-1):操作者记“未知用户”,尝试用户随 spec 落库
recorder.record(snapshotOf("/login"), new ChangeCapture(), 401,
AuditLogSpec.UNKNOWN_USERNAME, "zhangsan");
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
var spec = captor.getValue().getSpec();
assertThat(spec.getUsername()).isEqualTo(AuditLogSpec.UNKNOWN_USERNAME);
assertThat(spec.getAttemptedUsername()).isEqualTo("zhangsan");
assertThat(spec.getAction()).isEqualTo("login");
}
@Test
void shouldAnnotateSubActionSemanticAction() {
recorder.record(RequestSnapshot.of(MockServerHttpRequest
.put("http://localhost/apis/api.console.halo.run/v1alpha1/posts/xyz/publish")
.build()), new ChangeCapture(), 200, "admin");
.build()), new ChangeCapture(), 200, "admin", null);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
@@ -107,7 +121,7 @@ class AuditRecorderTest {
.thenReturn(Mono.just(new AuditSettings(false, 30, null, null)));
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), new ChangeCapture(),
200, "admin");
200, "admin", null);
verify(client, never()).create(any(AuditLog.class));
}
@@ -117,7 +131,7 @@ class AuditRecorderTest {
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
new ChangeCapture(), 200, "admin")).doesNotThrowAnyException();
new ChangeCapture(), 200, "admin", null)).doesNotThrowAnyException();
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
verify(client).create(any(AuditLog.class));
@@ -129,7 +143,7 @@ class AuditRecorderTest {
new IllegalStateException("storage unavailable")));
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
new ChangeCapture(), 500, "admin")).doesNotThrowAnyException();
new ChangeCapture(), 500, "admin", null)).doesNotThrowAnyException();
}
@Test
@@ -147,7 +161,7 @@ class AuditRecorderTest {
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.build());
recorder.record(snapshot, capture, 200, "admin");
recorder.record(snapshot, capture, 200, "admin", null);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
@@ -172,7 +186,7 @@ class AuditRecorderTest {
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.build());
recorder.record(snapshot, capture, 403, "admin");
recorder.record(snapshot, capture, 403, "admin", null);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
@@ -183,7 +197,7 @@ class AuditRecorderTest {
@Test
void shouldNotRecordChangesWhenContextMissing() {
recorder.record(snapshotOf("/apis/content.halo.run/v1alpha1/posts/abc"),
new ChangeCapture(), 200, "admin");
new ChangeCapture(), 200, "admin", null);
var captor = ArgumentCaptor.forClass(AuditLog.class);
verify(client).create(captor.capture());
@@ -0,0 +1,240 @@
package run.halo.operationaudit.audit;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import reactor.core.publisher.Mono;
/**
* 登录尝试用户名提取测试(功能评审 P0-1):表单体解析(成功/无 username/异常静默)、
* JSON 体提取、字段白名单(密码绝不提取)、请求体缓存后下游可重复读、
* 分块/超限/不支持形态降级为原 exchange。
*/
class LoginAttemptCaptureTest {
private LoginAttemptCapture capture;
@BeforeEach
void setUp() {
capture = new LoginAttemptCapture();
}
private static MockServerWebExchange formExchange(String body) {
return MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost/login")
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
.body(body));
}
private static MockServerWebExchange jsonExchange(String body) {
return MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost/login")
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
.contentType(MediaType.APPLICATION_JSON)
.contentLength(body.getBytes(StandardCharsets.UTF_8).length)
.body(body));
}
private LoginAttempt prepare(MockServerWebExchange exchange) {
var attempt = new LoginAttempt();
StepVerifier.create(capture.prepare(exchange, attempt)).expectNextCount(1)
.verifyComplete();
return attempt;
}
// ===== 表单体解析 =====
@Test
void shouldExtractUsernameFromFormBody() {
var attempt = prepare(formExchange("username=admin&password=secret-pw&remember=true"));
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
}
@Test
void shouldDecodeUrlEncodedUsername() {
var attempt = prepare(formExchange("username=user%40mail.com&password=x"));
assertThat(attempt.getAttemptedUsername()).isEqualTo("user@mail.com");
}
@Test
void shouldNotExtractPasswordOrOtherFields() {
// 白名单制:仅 username 字段被提取,password 等任何其余字段绝不落库
var attempt = prepare(formExchange("password=secret&email=a@b.c"));
assertThat(attempt.getAttemptedUsername()).isNull();
}
@Test
void shouldReturnNullWhenUsernameMissingOrBlank() {
assertThat(prepare(formExchange("password=x")).getAttemptedUsername()).isNull();
assertThat(prepare(formExchange("username=&password=x")).getAttemptedUsername()).isNull();
assertThat(prepare(formExchange("username= ")).getAttemptedUsername()).isNull();
}
@Test
void shouldFallbackToRawValueOnMalformedEncoding() {
// 裸 % 等非法编码:解码失败回退原值,尽力提取且绝不抛出
var attempt = prepare(formExchange("username=bad%zz&password=x"));
assertThat(attempt.getAttemptedUsername()).isEqualTo("bad%zz");
}
@Test
void shouldExtractSilentlyFromGarbageBody() {
// 解析异常静默:任何畸形输入都不抛出、不提取
var attempt = prepare(formExchange("&&&"));
assertThat(attempt.getAttemptedUsername()).isNull();
}
// ===== JSON 体提取 =====
@Test
void shouldExtractUsernameFromJsonBody() {
var attempt = prepare(jsonExchange("{\"username\":\"admin\",\"password\":\"secret\"}"));
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
}
@Test
void shouldReturnNullWhenJsonUsernameMissing() {
var attempt = prepare(jsonExchange("{\"name\":\"admin\"}"));
assertThat(attempt.getAttemptedUsername()).isNull();
}
// ===== 请求体缓存与下游可重复读 =====
@Test
void shouldKeepBodyReadableDownstream() {
var body = "username=admin&password=secret";
var exchange = formExchange(body);
var attempt = new LoginAttempt();
var prepared = capture.prepare(exchange, attempt).block();
assertThat(attempt.getAttemptedUsername()).isEqualTo("admin");
// 装饰后的请求可重复读(每次订阅独立 buffer),登录处理可正常读取表单
assertThat(prepared).isNotSameAs(exchange);
var first = prepared.getRequest().getBody()
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
.collectList().block();
var second = prepared.getRequest().getBody()
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
.collectList().block();
assertThat(first).containsExactly(body);
assertThat(second).containsExactly(body);
}
// ===== 形态与边界降级 =====
@Test
void shouldPassthroughUnsupportedContentType() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost/login")
.contentType(MediaType.MULTIPART_FORM_DATA)
.contentLength(2)
.body("x=1"));
var attempt = new LoginAttempt();
var prepared = capture.prepare(exchange, attempt).block();
assertThat(prepared).isSameAs(exchange);
assertThat(attempt.getAttemptedUsername()).isNull();
}
@Test
void shouldPassthroughChunkedBodyWithoutContentLength() {
var request = MockServerHttpRequest.post("http://localhost/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(Flux.just(DefaultDataBufferFactory.sharedInstance
.wrap("username=admin".getBytes(StandardCharsets.UTF_8))));
var exchange = MockServerWebExchange.from(request);
var attempt = new LoginAttempt();
var prepared = capture.prepare(exchange, attempt).block();
// 分块传输(无 Content-Length):不读请求体,避免中断流式请求
assertThat(prepared).isSameAs(exchange);
assertThat(attempt.getAttemptedUsername()).isNull();
}
@Test
void shouldPassthroughOversizedBody() {
var oversized = "a".repeat(LoginAttemptCapture.MAX_BODY_BYTES + 1);
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentLength(oversized.length())
.body(oversized));
var attempt = new LoginAttempt();
var prepared = capture.prepare(exchange, attempt).block();
assertThat(prepared).isSameAs(exchange);
assertThat(attempt.getAttemptedUsername()).isNull();
}
@Test
void shouldPassthroughEmptyBody() {
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED));
var attempt = new LoginAttempt();
var prepared = capture.prepare(exchange, attempt).block();
assertThat(prepared).isSameAs(exchange);
assertThat(attempt.getAttemptedUsername()).isNull();
}
// ===== 兜底脱敏(现有敏感字段规则约束) =====
@Test
void shouldRedactWhitelistedFieldMatchingSensitiveRule() {
// 白名单当前仅 username(不命中敏感规则,值原样提取);
// 兜底约束:字段名若命中现有敏感字段规则,值一律以 ****** 代替
assertThat(LoginAttemptCapture.maskIfSensitive("username", "admin")).isEqualTo("admin");
assertThat(LoginAttemptCapture.maskIfSensitive("password", "secret"))
.isEqualTo(ChangeDiffEngine.REDACTED_VALUE);
}
@Test
void shouldNotTouchResponse() {
var exchange = formExchange("username=admin&password=x");
var attempt = new LoginAttempt();
capture.prepare(exchange, attempt).block();
// 提取过程只读请求侧,不写响应(状态码仍为未设置的 null)
assertThat(exchange.getResponse().getStatusCode()).isNull();
}
// ===== 提取函数直接断言 =====
@Test
void shouldExtractLastUsernameWhenDuplicated() {
assertThat(LoginAttemptCapture.usernameOfForm("username=first&username=second"))
.isEqualTo("second");
}
@Test
void shouldReturnNullForBlankFormBody() {
assertThat(LoginAttemptCapture.usernameOfForm(null)).isNull();
assertThat(LoginAttemptCapture.usernameOfForm(" ")).isNull();
}
}
@@ -3,15 +3,18 @@ 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.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -27,6 +30,7 @@ import run.halo.operationaudit.alert.LoginFailureAlertService;
* 字段级变更(产品设计 V2):捕获上下文随记录透传给 Recorder。
* 系统内部变更(产品设计 V2):所有写方法请求登记 HTTP 写标记(含非捕获路径)。
* 登录失败告警(产品设计 V2「告警通知」):POST /login 结束回调结果(2xx 成功/其余失败)。
* 登录尝试用户名(功能评审 P0-1):POST /login 请求期提取并透传给告警与记录。
*/
class OperationAuditWebFilterTest {
@@ -73,8 +77,9 @@ class OperationAuditWebFilterTest {
when(captureManager.prepare(any(ServerWebExchange.class), any(RequestSnapshot.class),
any(ChangeCapture.class)))
.thenAnswer(inv -> Mono.just((ServerWebExchange) inv.getArgument(0)));
// 登录尝试用户名提取为真实实现:过滤器行为测试同时覆盖提取透传
filter = new OperationAuditWebFilter(recorder, captureManager, writeMarker,
loginFailureAlertService);
new LoginAttemptCapture(), loginFailureAlertService);
}
@Test
@@ -92,7 +97,7 @@ class OperationAuditWebFilterTest {
.verifyComplete();
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
eq("admin"));
eq("admin"), isNull());
}
@Test
@@ -103,7 +108,7 @@ class OperationAuditWebFilterTest {
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any());
verify(recorder, never()).record(any(), any(), any(), any(), any());
}
@Test
@@ -116,7 +121,25 @@ class OperationAuditWebFilterTest {
// 匿名访问 /login:无 SecurityContext → 操作者为“未知用户”,登录端点仍记录
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
eq(AuditLogSpec.UNKNOWN_USERNAME));
eq(AuditLogSpec.UNKNOWN_USERNAME), isNull());
}
@Test
void shouldRecordAndAlertAttemptedUsernameOnLoginAttempt() {
// 登录尝试用户名(功能评审 P0-1):表单体中的 username 白名单提取,
// 随告警回调与审计记录透传;密码等其余字段绝不提取
var exchange = MockServerWebExchange.from(MockServerHttpRequest
.post("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentLength("username=admin&password=secret".getBytes(StandardCharsets.UTF_8).length)
.body("username=admin&password=secret"));
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(recorder).record(any(RequestSnapshot.class), any(ChangeCapture.class), eq(200),
eq(AuditLogSpec.UNKNOWN_USERNAME), eq("admin"));
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200),
eq("admin"));
}
@Test
@@ -128,7 +151,7 @@ class OperationAuditWebFilterTest {
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any());
verify(recorder, never()).record(any(), any(), any(), any(), any());
}
@Test
@@ -145,7 +168,7 @@ class OperationAuditWebFilterTest {
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(anonymous)))
.verifyComplete();
verify(recorder, never()).record(any(), any(), any(), any());
verify(recorder, never()).record(any(), any(), any(), any(), any());
}
@Test
@@ -163,7 +186,8 @@ class OperationAuditWebFilterTest {
.verifyComplete();
var captor = ArgumentCaptor.forClass(RequestSnapshot.class);
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"));
verify(recorder).record(captor.capture(), any(ChangeCapture.class), eq(200), eq("admin"),
isNull());
assertThat(ResourceResolver.resolve(captor.getValue().getPath()).resourceType())
.isEqualTo("auth");
}
@@ -195,7 +219,7 @@ class OperationAuditWebFilterTest {
// 请求期创建的同一个 capture 实例被透传给记录阶段
verify(recorder).record(any(RequestSnapshot.class), eq(captured[0]), eq(200),
eq("admin"));
eq("admin"), isNull());
}
@Test
@@ -222,7 +246,7 @@ class OperationAuditWebFilterTest {
verify(writeMarker).onRequestStart(any());
verify(writeMarker).onRequestComplete(any());
verify(recorder, never()).record(any(), any(), any(), any());
verify(recorder, never()).record(any(), any(), any(), any(), any());
}
@Test
@@ -247,7 +271,8 @@ class OperationAuditWebFilterTest {
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200));
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(200),
isNull());
}
@Test
@@ -261,7 +286,8 @@ class OperationAuditWebFilterTest {
.verifyComplete();
// 非常响应(401)同样回调,由告警服务按失败累计
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401));
verify(loginFailureAlertService).onLoginResult(any(RequestSnapshot.class), eq(401),
isNull());
}
@Test
@@ -278,7 +304,7 @@ class OperationAuditWebFilterTest {
StepVerifier.create(filter.filter(logout, CHAIN)).verifyComplete();
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), any());
.onLoginResult(any(RequestSnapshot.class), any(), any());
}
@Test
@@ -290,6 +316,6 @@ class OperationAuditWebFilterTest {
StepVerifier.create(filter.filter(exchange, CHAIN)).verifyComplete();
verify(loginFailureAlertService, never())
.onLoginResult(any(RequestSnapshot.class), any());
.onLoginResult(any(RequestSnapshot.class), any(), any());
}
}
@@ -4,6 +4,8 @@
export interface AuditLogSpec {
username: string
/** 登录尝试的用户名(功能评审 P0-1):仅 POST /login 请求提取落库,其余为 null。 */
attemptedUsername?: string | null
method: string
resourceType: string
resourceName?: string | null
@@ -78,6 +78,11 @@ const rawJson = computed(() =>
<dt>操作者</dt>
<dd>{{ displayUsername(log.spec.username) }}</dd>
</div>
<!-- 登录尝试的用户名(功能评审 P0-1):仅登录请求落库,历史记录/其他请求缺失 -->
<div v-if="log.spec.attemptedUsername" class="detail-row">
<dt>尝试用户</dt>
<dd class="break-all">{{ log.spec.attemptedUsername }}</dd>
</div>
<div class="detail-row">
<dt>描述</dt>
<dd>{{ describeOperation(log.spec) }}</dd>