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(); } }