fix: 落实官方规范评审修复(生成 API 客户端 / SSRF 防护 / 凭据迁 Secret)

对应 docs/operation-audit-halo-compliance.md 评审的两项不符合与第 5 节修复建议:

1. API 客户端生成(清单第 2 条):build.gradle 配置 haloPlugin.openApi 管线;
   查询/导出/测试端点补 tag、参数声明与类型化 response(生成契约输入);
   bootstrap OpenAPI 规范 JSON(与 Springdoc 声明一一对手工对齐)驱动 devtools
   generateApiClient 产出 TS 客户端(ui/src/api/generated,openapi-generator 7.7.0);
   UI 经 ui/src/api 封装层复用宿主 axiosInstance,替换手写类型与裸 fetch;
   @halo-dev/api-client 由死依赖转为 axiosInstance 实际来源。

2. 出站安全与凭据(清单第 4 条):新增 OutboundUrlGuard——URI 解析 + scheme 白名单 +
   禁止用户名/密码形态 + 全量 DNS 解析并拒绝环回/私网/链路本地/组播/未指定/
   云元数据(169.254.169.254、100.100.100.200、fd00:ec2::254)/CGNAT/ULA/Teredo/
   6to4/文档与保留段;PinnedAddressResolverGroup 钉定校验地址建连(DNS rebinding
   防护,TLS SNI/Host 仍取原主机名);重定向显式关闭、三层超时 10 秒。
   Webhook 地址凭据迁移 Halo Secret(settings.yaml 改 secret 输入存引用,服务端经
   ReactiveExtensionClient 解析键 webhookUrl,fail closed);日志只记主机名,
   不再记录可能内嵌 access_token 的完整地址。

测试:后端 244 用例(新增守卫地址段枚举/Secret 解析 fail closed/建连钉定证明等
25 例)+ UI vitest 54 用例 + vue-tsc + ./gradlew build 全部通过。
This commit is contained in:
2026-11-22 15:15:32 +08:00
parent 7257008af3
commit 9865149ab3
48 changed files with 2779 additions and 342 deletions
@@ -1,6 +1,7 @@
package run.halo.operationaudit.alert;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -8,18 +9,34 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.Secret;
import run.halo.app.plugin.ReactiveSettingFetcher;
/**
* 告警设置 TTL 缓存测试(与审计设置同款模式):命中缓存、失败/缺省回退默认(告警关闭)。
* 告警设置 TTL 缓存测试(与审计设置同款模式):命中缓存、失败/缺省回退默认(告警关闭);
* Webhook 地址 Secret 解析:未配置引用 / Secret 不存在 / 缺字段 / 空白值均 fail closed
* (错误信号,绝不发送),字段值去除首尾空白。
*/
class AlertSettingProviderTest {
private final ReactiveSettingFetcher fetcher = mock(ReactiveSettingFetcher.class);
private final AlertSettingProvider provider = new AlertSettingProvider(fetcher);
private final ReactiveExtensionClient client = mock(ReactiveExtensionClient.class);
private final AlertSettingProvider provider = new AlertSettingProvider(fetcher, client);
private static AlertSettings settings(String secretName) {
return new AlertSettings(true, secretName, 5, 5);
}
private static Secret secret(String url) {
var secret = new Secret();
secret.setStringData(Map.of(AlertSettingProvider.WEBHOOK_URL_FIELD, url));
return secret;
}
@Test
void shouldCacheWithinTtl() {
@@ -27,15 +44,15 @@ class AlertSettingProviderTest {
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
.thenAnswer(inv -> {
fetchCount.incrementAndGet();
return Mono.just(new AlertSettings(true, "https://hooks.example.com/x", 3, 2));
return Mono.just(new AlertSettings(true, "webhook-secret", 3, 2));
});
var first = provider.get().block();
var second = provider.get().block();
assertThat(first).extracting(AlertSettings::enabled, AlertSettings::webhookUrl,
assertThat(first).extracting(AlertSettings::enabled, AlertSettings::webhookSecretName,
AlertSettings::thresholdCount, AlertSettings::windowMinutes)
.containsExactly(true, "https://hooks.example.com/x", 3, 2);
.containsExactly(true, "webhook-secret", 3, 2);
assertThat(second).isSameAs(first);
assertThat(fetchCount.get()).isEqualTo(1);
}
@@ -49,7 +66,7 @@ class AlertSettingProviderTest {
assertThat(settings).isEqualTo(AlertSettings.defaults());
assertThat(settings.enabledOrDefault()).isFalse();
assertThat(settings.webhookUrlOrDefault()).isNull();
assertThat(settings.webhookSecretNameOrDefault()).isNull();
}
@Test
@@ -73,4 +90,56 @@ class AlertSettingProviderTest {
provider.get().block();
verify(fetcher, times(2)).fetch(any(), any());
}
// ===== Webhook 地址 Secret 解析(fail closed) =====
@Test
void shouldResolveWebhookUrlFromSecret() {
when(client.fetch(eq(Secret.class), eq("webhook-secret")))
.thenReturn(Mono.just(secret(" https://hooks.example.com/x ")));
assertThat(provider.webhookUrl(settings("webhook-secret")).block())
.isEqualTo("https://hooks.example.com/x");
// 便捷方法:先读设置再解析
when(fetcher.fetch(eq(AlertSettings.GROUP), eq(AlertSettings.class)))
.thenReturn(Mono.just(settings("webhook-secret")));
assertThat(provider.webhookUrl().block()).isEqualTo("https://hooks.example.com/x");
}
@Test
void shouldFailClosedWhenSecretRefMissing() {
assertThatThrownBy(() -> provider.webhookUrl(settings(" ")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("未配置");
}
@Test
void shouldFailClosedWhenSecretMissing() {
when(client.fetch(eq(Secret.class), eq("gone"))).thenReturn(Mono.empty());
assertThatThrownBy(() -> provider.webhookUrl(settings("gone")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("不存在");
}
@Test
void shouldFailClosedWhenSecretFieldMissing() {
var secret = new Secret();
secret.setStringData(Map.of("other", "value"));
when(client.fetch(eq(Secret.class), eq("webhook-secret"))).thenReturn(Mono.just(secret));
assertThatThrownBy(() -> provider.webhookUrl(settings("webhook-secret")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining(AlertSettingProvider.WEBHOOK_URL_FIELD);
}
@Test
void shouldFailClosedWhenSecretFieldBlank() {
when(client.fetch(eq(Secret.class), eq("webhook-secret")))
.thenReturn(Mono.just(secret(" ")));
assertThatThrownBy(() -> provider.webhookUrl(settings("webhook-secret")).block())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("缺少");
}
}
@@ -5,7 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* 告警设置归一测试:缺省/非法值回退默认,Webhook 地址仅接受 http(s)。
* 告警设置归一测试:缺省/非法值回退默认;凭据安全要求下本记录只持有 Secret 引用名
* (真实 Webhook 地址由 AlertSettingProvider 从 Secret 解析)。
*/
class AlertSettingsTest {
@@ -14,33 +15,25 @@ class AlertSettingsTest {
var settings = AlertSettings.defaults();
assertThat(settings.enabledOrDefault()).isFalse();
assertThat(settings.webhookUrlOrDefault()).isNull();
assertThat(settings.webhookSecretNameOrDefault()).isNull();
assertThat(settings.thresholdCountOrDefault()).isEqualTo(5);
assertThat(settings.windowMinutesOrDefault()).isEqualTo(5);
}
@Test
void shouldNormalizeWebhookUrl() {
assertThat(new AlertSettings(true, " https://hooks.example.com/x ", null, null)
.webhookUrlOrDefault()).isEqualTo("https://hooks.example.com/x");
assertThat(new AlertSettings(true, "http://127.0.0.1:9000/hook", null, null)
.webhookUrlOrDefault()).isEqualTo("http://127.0.0.1:9000/hook");
// 大写 scheme 同样接受(URL scheme 不区分大小写)
assertThat(new AlertSettings(true, "HTTPS://hooks.example.com/x", null, null)
.webhookUrlOrDefault()).isEqualTo("HTTPS://hooks.example.com/x");
void shouldNormalizeSecretName() {
assertThat(new AlertSettings(true, " operation-audit-webhook ", null, null)
.webhookSecretNameOrDefault()).isEqualTo("operation-audit-webhook");
}
@Test
void shouldRejectNonHttpWebhookUrl() {
assertThat(new AlertSettings(true, null, null, null).webhookUrlOrDefault()).isNull();
assertThat(new AlertSettings(true, "", null, null).webhookUrlOrDefault()).isNull();
assertThat(new AlertSettings(true, " ", null, null).webhookUrlOrDefault()).isNull();
assertThat(new AlertSettings(true, "ftp://hooks.example.com", null, null)
.webhookUrlOrDefault()).isNull();
assertThat(new AlertSettings(true, "hooks.example.com/x", null, null)
.webhookUrlOrDefault()).isNull();
assertThat(new AlertSettings(true, "javascript:alert(1)", null, null)
.webhookUrlOrDefault()).isNull();
void shouldRejectBlankSecretName() {
assertThat(new AlertSettings(true, null, null, null).webhookSecretNameOrDefault())
.isNull();
assertThat(new AlertSettings(true, "", null, null).webhookSecretNameOrDefault())
.isNull();
assertThat(new AlertSettings(true, " ", null, null).webhookSecretNameOrDefault())
.isNull();
}
@Test
@@ -67,8 +60,11 @@ class AlertSettingsTest {
@Test
void shouldRespectExplicitEnabledFlag() {
assertThat(new AlertSettings(null, "https://x", null, null).enabledOrDefault()).isFalse();
assertThat(new AlertSettings(false, "https://x", null, null).enabledOrDefault()).isFalse();
assertThat(new AlertSettings(true, "https://x", null, null).enabledOrDefault()).isTrue();
assertThat(new AlertSettings(null, "webhook-secret", null, null).enabledOrDefault())
.isFalse();
assertThat(new AlertSettings(false, "webhook-secret", null, null).enabledOrDefault())
.isFalse();
assertThat(new AlertSettings(true, "webhook-secret", null, null).enabledOrDefault())
.isTrue();
}
}
@@ -16,12 +16,14 @@ import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
/**
* 告警测试端点测试(功能评审 P0-2):Webhook 未配置/非法返回 400、推送结果同步返回
* (200 + success/message)、测试负载结构(type=test 与 login-failure 区分)。
* 告警测试端点测试(功能评审 P0-2):Webhook 地址不可用(未配置引用/Secret 缺失/缺键)
* 返回 400、推送结果同步返回(200 + success/message)、测试负载结构(type=test 与
* login-failure 区分)。
*/
class AlertTestEndpointTest {
private static final String TEST_URI = "/apis/" + "audit.guichumo.com" + "/v1alpha1/alerts/-/test";
private static final String WEBHOOK_URL = "https://hooks.example.com/x";
private AlertSettingProvider settingProvider;
private AlertWebhookSender sender;
@@ -39,28 +41,29 @@ class AlertTestEndpointTest {
webClient = WebTestClient.bindToRouterFunction(mounted).build();
}
private static AlertSettings settings(String webhookUrl) {
return new AlertSettings(true, webhookUrl, 5, 5);
private static AlertSettings settings(String secretName) {
return new AlertSettings(true, secretName, 5, 5);
}
@Test
void shouldRejectWhenWebhookUrlMissing() {
when(settingProvider.get()).thenReturn(Mono.just(settings(" ")));
void shouldRejectWhenWebhookUrlUnavailable() {
when(settingProvider.webhookUrl()).thenReturn(Mono.error(new IllegalStateException(
"Webhook 地址未配置(需在设置中选择或创建 Secret),请先保存设置")));
webClient.post().uri(TEST_URI)
.exchange()
.expectStatus().isBadRequest()
.expectBody()
.jsonPath("$.message").isEqualTo(
"Webhook 地址未配置或非法(需以 http(s) 开头),请先保存设置");
"Webhook 地址未配置(需在设置中选择或创建 Secret),请先保存设置");
verify(sender, org.mockito.Mockito.never()).sendForResult(any(), any());
}
@Test
void shouldReturnSuccessResult() {
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
when(sender.sendForResult(eq("https://hooks.example.com/x"), any()))
when(settingProvider.webhookUrl()).thenReturn(Mono.just(WEBHOOK_URL));
when(sender.sendForResult(eq(WEBHOOK_URL), any()))
.thenReturn(Mono.just(AlertSendResult.ok(200)));
webClient.post().uri(TEST_URI)
@@ -74,8 +77,8 @@ class AlertTestEndpointTest {
@Test
@SuppressWarnings("unchecked")
void shouldReturnFailureResultWithoutError() {
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
when(sender.sendForResult(eq("https://hooks.example.com/x"), any()))
when(settingProvider.webhookUrl()).thenReturn(Mono.just(WEBHOOK_URL));
when(sender.sendForResult(eq(WEBHOOK_URL), any()))
.thenReturn(Mono.just(new AlertSendResult(false, "connect timed out")));
webClient.post().uri(TEST_URI)
@@ -89,7 +92,7 @@ class AlertTestEndpointTest {
@Test
@SuppressWarnings("unchecked")
void shouldPostTestTypePayload() {
when(settingProvider.get()).thenReturn(Mono.just(settings("https://hooks.example.com/x")));
when(settingProvider.webhookUrl()).thenReturn(Mono.just(WEBHOOK_URL));
when(sender.sendForResult(any(), any()))
.thenReturn(Mono.just(AlertSendResult.ok(204)));
@@ -99,7 +102,7 @@ class AlertTestEndpointTest {
var urlCaptor = ArgumentCaptor.forClass(String.class);
var payloadCaptor = ArgumentCaptor.forClass(Map.class);
verify(sender).sendForResult(urlCaptor.capture(), payloadCaptor.capture());
assertThat(urlCaptor.getValue()).isEqualTo("https://hooks.example.com/x");
assertThat(urlCaptor.getValue()).isEqualTo(WEBHOOK_URL);
var payload = payloadCaptor.getValue();
assertThat(payload.get("type")).isEqualTo(AlertTestEndpoint.TEST_TYPE);
assertThat((String) payload.get("title")).contains("测试消息");
@@ -7,23 +7,32 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/**
* Webhook 推送集成测试(JDK 内置 HttpServer 走真实 HTTP):
* JSON POST 负载可达、非 2xx / 连接失败 / URL 非法均静默降级不抛出;
*
* <p>HTTP 机制经 {@code sendToTarget} 直接驱动(目标已完成校验、地址钉定)——
* JSON POST 负载可达、非 2xx / 连接失败 / 校验失败均归一为结果或静默降级不抛出;
* 结果化推送(功能评审 P0-2)返回送达与否 + 原因摘要,同样永不抛出。
*
* <p>出站安全链路经 {@code sendForResult} 驱动(真实路径):回环/内网等受限地址
* 在 SSRF 校验阶段即拒绝(不建连),建连钉定校验地址(DNS rebinding 防护——
* 主机名 localhost + 钉定 127.0.0.2 的用例证明建连走钉定地址而非 DNS 结果)。
*/
class AlertWebhookSenderTest {
private HttpServer server;
private final AlertWebhookSender sender = new AlertWebhookSender();
private final AlertWebhookSender sender = new AlertWebhookSender(new OutboundUrlGuard());
@AfterEach
void tearDown() {
@@ -32,10 +41,10 @@ class AlertWebhookSenderTest {
}
}
private HttpServer startServer(int status, AtomicReference<byte[]> body,
/** 在指定回环地址上启动测试 HTTP 服务,返回实际端口。 */
private int startServer(InetAddress bind, int status, AtomicReference<byte[]> body,
AtomicReference<String> contentType, CountDownLatch received) throws Exception {
var httpServer = HttpServer.create(
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
var httpServer = HttpServer.create(new InetSocketAddress(bind, 0), 0);
httpServer.createContext("/hook", exchange -> {
body.set(exchange.getRequestBody().readAllBytes());
contentType.set(exchange.getRequestHeaders().getFirst("Content-Type"));
@@ -44,18 +53,30 @@ class AlertWebhookSenderTest {
received.countDown();
});
httpServer.start();
return httpServer;
server = httpServer;
return httpServer.getAddress().getPort();
}
/** 构造已校验钉定目标(等价守卫对公网地址放行后的产物)。 */
private static OutboundUrlGuard.ValidatedTarget pinnedTarget(String url)
throws Exception {
var uri = new URI(url);
return new OutboundUrlGuard.ValidatedTarget(uri, uri.getPort(),
InetAddress.getByName(uri.getHost()));
}
@Test
void shouldPostJsonPayload() throws Exception {
void shouldPostJsonPayloadViaPinnedTarget() throws Exception {
var body = new AtomicReference<byte[]>();
var contentType = new AtomicReference<String>();
var received = new CountDownLatch(1);
server = startServer(200, body, contentType, received);
var port = startServer(InetAddress.getLoopbackAddress(), 200, body, contentType,
received);
var url = "http://127.0.0.1:" + port + "/hook";
sender.send("http://127.0.0.1:" + server.getAddress().getPort() + "/hook",
Map.of("title", "操作审计告警:登录失败", "failures", 3));
// fire-and-forget 语义:订阅即异步执行,不等待结果
sender.sendToTarget(pinnedTarget(url),
Map.of("title", "操作审计告警:登录失败", "failures", 3)).subscribe();
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
@@ -66,44 +87,19 @@ class AlertWebhookSenderTest {
}
@Test
void shouldNotThrowOnNon2xxResponse() throws Exception {
void shouldConnectToPinnedAddressInsteadOfDns() throws Exception {
// DNS rebinding 防护证明:主机名 localhost 的 DNS 结果是 127.0.0.1,
// 服务却监听在 127.0.0.2 —— 建连必须走钉定地址才能送达
var pinned = InetAddress.getByAddress(new byte[] {127, 0, 0, 2});
var body = new AtomicReference<byte[]>();
var contentType = new AtomicReference<String>();
var received = new CountDownLatch(1);
server = startServer(500, body, contentType, received);
var port = startServer(pinned, 200, body, contentType, received);
// 目标地址与 URL 主机名刻意不同:模拟"校验时解析结果 ≠ 重绑定后的 DNS 结果"
var target = new OutboundUrlGuard.ValidatedTarget(
new URI("http://localhost:" + port + "/hook"), port, pinned);
assertThatCode(() -> sender.send(
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of()))
.doesNotThrowAnyException();
// 500 响应同样送达(接收方先收到请求才返回 500),随后静默降级为日志
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
}
@Test
void shouldNotThrowWhenTargetUnreachable() {
// 端口 1 保留端口,连接立即被拒:异步失败仅记日志
assertThatCode(() -> sender.send("http://127.0.0.1:1/hook", Map.of()))
.doesNotThrowAnyException();
}
@Test
void shouldNotThrowWhenUrlMalformed() {
assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException();
assertThatCode(() -> sender.send(null, Map.of())).doesNotThrowAnyException();
}
// ===== 结果化推送(功能评审 P0-2:测试告警端点同步反馈到设置页) =====
@Test
void shouldReturnSuccessResultOn2xx() throws Exception {
var body = new AtomicReference<byte[]>();
var contentType = new AtomicReference<String>();
var received = new CountDownLatch(1);
server = startServer(200, body, contentType, received);
var result = sender.sendForResult(
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of("k", "v"))
var result = sender.sendToTarget(target, Map.of("pin", true))
.block(java.time.Duration.ofSeconds(10));
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
@@ -113,26 +109,37 @@ class AlertWebhookSenderTest {
}
@Test
void shouldReturnFailureResultOnNon2xx() throws Exception {
void shouldNotThrowOnNon2xxResponse() throws Exception {
var body = new AtomicReference<byte[]>();
var contentType = new AtomicReference<String>();
var received = new CountDownLatch(1);
server = startServer(503, body, contentType, received);
var port = startServer(InetAddress.getLoopbackAddress(), 500, body, contentType,
received);
var url = "http://127.0.0.1:" + port + "/hook";
var result = sender.sendForResult(
"http://127.0.0.1:" + server.getAddress().getPort() + "/hook", Map.of())
.block(java.time.Duration.ofSeconds(10));
assertThatCode(() -> sender.sendToTarget(pinnedTarget(url), Map.of()).subscribe())
.doesNotThrowAnyException();
// 500 响应同样送达(接收方先收到请求才返回 500),随后静默降级为日志
assertThat(received.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(result).isNotNull();
assertThat(result.success()).isFalse();
assertThat(result.message()).isNotBlank();
StepVerifier.create(sender.sendToTarget(pinnedTarget(url), Map.of()))
.assertNext(result -> {
assertThat(result.success()).isFalse();
assertThat(result.message()).isNotBlank();
})
.verifyComplete();
}
@Test
void shouldReturnFailureResultWhenTargetUnreachable() {
// 端口 1 保留端口,连接立即被拒:归一为失败结果而非错误信号
var result = sender.sendForResult("http://127.0.0.1:1/hook", Map.of())
void shouldReturnFailureResultWhenTargetUnreachable() throws Exception {
// 服务监听后立即停止(端口保留);或直接钉定无监听端口 → 连接失败归一为失败结果
var bound = InetAddress.getLoopbackAddress();
var socket = new java.net.ServerSocket(0, 1, bound);
var port = socket.getLocalPort();
socket.close();
var result = sender.sendToTarget(pinnedTarget("http://127.0.0.1:" + port + "/hook"),
Map.of())
.block(java.time.Duration.ofSeconds(10));
assertThat(result).isNotNull();
@@ -140,8 +147,31 @@ class AlertWebhookSenderTest {
assertThat(result.message()).isNotBlank();
}
// ===== 出站安全链路(sendForResult:真实路径,SSRF 校验前置) =====
@Test
void shouldReturnFailureResultWhenUrlMalformed() {
void shouldRejectLoopbackTargetBeforeConnecting() throws Exception {
// 回环地址在 SSRF 校验阶段即拒绝,绝不建连(端口 9 无监听,若建连会失败而非拒绝)
var result = sender.sendForResult("http://127.0.0.1:9/hook", Map.of())
.block(java.time.Duration.ofSeconds(10));
assertThat(result).isNotNull();
assertThat(result.success()).isFalse();
assertThat(result.message()).contains("受限网络地址");
}
@Test
void shouldRejectPrivateIpTarget() {
StepVerifier.create(sender.sendForResult("http://10.0.0.1/hook", Map.of()))
.assertNext(result -> {
assertThat(result.success()).isFalse();
assertThat(result.message()).contains("受限网络地址");
})
.verifyComplete();
}
@Test
void shouldNormalizeMalformedUrlToFailureResult() {
// URL 非法(含 null):装配期异常归一为失败结果,Mono 永不报错
assertThat(sender.sendForResult("not-a-url", Map.of())
.map(AlertSendResult::success).defaultIfEmpty(false).block(
@@ -149,12 +179,15 @@ class AlertWebhookSenderTest {
assertThat(sender.sendForResult(null, Map.of())
.map(AlertSendResult::success).defaultIfEmpty(false).block(
java.time.Duration.ofSeconds(10))).isFalse();
assertThat(sender.sendForResult("ftp://hooks.example.com", Map.of())
.map(AlertSendResult::success).defaultIfEmpty(false).block(
java.time.Duration.ofSeconds(10))).isFalse();
}
@Test
void shouldSendFireAndForgetWithoutThrowingForResultFailure() {
// send(fire-and-forget)复用结果化推送:失败仅记日志,调用方无感知
assertThatCode(() -> sender.send("http://127.0.0.1:1/hook", Map.of()))
// send(fire-and-forget)复用结果化推送:校验拒绝/失败仅记日志,调用方无感知
assertThatCode(() -> sender.send("http://127.0.0.1:9/hook", Map.of()))
.doesNotThrowAnyException();
assertThatCode(() -> sender.send("not-a-url", Map.of())).doesNotThrowAnyException();
}
@@ -25,10 +25,14 @@ import run.halo.operationaudit.audit.RequestSnapshot;
/**
* 登录失败告警阈值窗口测试(产品设计 V2「告警通知」):
* 达阈值告警一次、告警后重开窗口、窗口过期重开、登录成功清零、开关与地址归一降级。
* 达阈值告警一次、告警后重开窗口、窗口过期重开、登录成功清零、开关与地址降级。
* Webhook 地址凭据存于 Halo Secret:handle 先经 AlertSettingProvider 解析地址,
* 未配置/解析失败则静默跳过(不计数也不告警)。
*/
class LoginFailureAlertServiceTest {
/** 设置中持有的 Secret 引用名(测试桩,非真实凭据)。 */
private static final String WEBHOOK_REF = "operation-audit-webhook";
private static final String WEBHOOK_URL = "https://hooks.example.com/halo-alert";
private AlertSettingProvider settingProvider;
@@ -40,11 +44,14 @@ class LoginFailureAlertServiceTest {
settingProvider = mock(AlertSettingProvider.class);
sender = mock(AlertWebhookSender.class);
service = new LoginFailureAlertService(settingProvider, sender);
// 默认解析成功:真实地址由 Secret 解析给出(凭据不出 Secret)
when(settingProvider.webhookUrl(any(AlertSettings.class)))
.thenReturn(Mono.just(WEBHOOK_URL));
}
private void enableAlerts(int threshold, int windowMinutes) {
when(settingProvider.get()).thenReturn(Mono.just(
new AlertSettings(true, WEBHOOK_URL, threshold, windowMinutes)));
new AlertSettings(true, WEBHOOK_REF, threshold, windowMinutes)));
}
private static RequestSnapshot loginSnapshot() {
@@ -220,7 +227,7 @@ class LoginFailureAlertServiceTest {
@Test
void shouldSkipWhenAlertDisabled() {
when(settingProvider.get()).thenReturn(Mono.just(
new AlertSettings(false, WEBHOOK_URL, 1, 5)));
new AlertSettings(false, WEBHOOK_REF, 1, 5)));
var snapshot = loginSnapshot();
// 开关关闭:不计数也不告警(阈值 1 也应无任何副作用)
@@ -232,14 +239,19 @@ class LoginFailureAlertServiceTest {
}
@Test
void shouldSkipWhenWebhookUrlMissing() {
void shouldSkipWhenWebhookUrlUnavailable() {
when(settingProvider.get()).thenReturn(Mono.just(
new AlertSettings(true, " ", 1, 5)));
when(settingProvider.webhookUrl(any(AlertSettings.class)))
.thenReturn(Mono.error(new IllegalStateException("Webhook 地址未配置")));
var snapshot = loginSnapshot();
// 地址解析失败(未配置 Secret / Secret 缺字段):静默跳过,不计数也不告警
service.onLoginResult(snapshot, 401, null);
service.onLoginResult(snapshot, 401, null);
verify(sender, never()).send(any(), any());
assertThat(service.failureCount).isZero();
}
@Test
@@ -277,8 +289,8 @@ class LoginFailureAlertServiceTest {
assertThat((Map<String, Object>) payload.get("data")).containsEntry("userAgent", null);
}
/** 直接驱动 handle 用的告警设置(handle 不读设置缓存,参数须与断言一致)。 */
/** 直接驱动 handle 用的告警设置(handle 只读开关/阈值,地址走 provider 解析)。 */
private AlertSettings settings(int thresholdCount, int windowMinutes) {
return new AlertSettings(true, WEBHOOK_URL, thresholdCount, windowMinutes);
return new AlertSettings(true, WEBHOOK_REF, thresholdCount, windowMinutes);
}
}
@@ -0,0 +1,236 @@
package run.halo.operationaudit.alert;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
/**
* 出站地址守卫测试(官方《敏感数据与出站请求》指南逐项覆盖):
* 结构校验(scheme 白名单/主机名/用户名密码形态/端口)、危险地址段拒绝
* (环回/私网/链路本地/组播/未指定/云元数据/CGNAT/ULA/过渡机制/文档与保留段)、
* 内嵌 IPv4 映射地址、合法公网地址放行、钉定目标构造。
*/
class OutboundUrlGuardTest {
private final OutboundUrlGuard guard = new OutboundUrlGuard();
private static InetAddress addr(String literal) throws Exception {
return InetAddress.getByName(literal);
}
private static void assertForbidden(String literal) throws Exception {
assertThat(OutboundUrlGuard.isForbiddenAddress(addr(literal)))
.as("应拒绝 " + literal)
.isTrue();
}
private static void assertAllowed(String literal) throws Exception {
assertThat(OutboundUrlGuard.isForbiddenAddress(addr(literal)))
.as("应放行 " + literal)
.isFalse();
}
// ===== 结构校验(scheme / 主机名 / 用户名密码形态 / 端口) =====
@Test
void shouldRejectBlankOrNullUrl() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(null))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("为空");
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(" "))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("为空");
}
@Test
void shouldRejectUnparsableUrl() {
// "not-a-url" 被 URI 解析为相对引用(无 scheme):落入 scheme 白名单拒绝,
// 与无法解析同等不可用
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure("not-a-url"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("http(s)");
}
@Test
void shouldRejectNonHttpSchemes() {
for (var url : new String[] {"ftp://hooks.example.com/x", "javascript:alert(1)",
"file:///etc/passwd", "ws://hooks.example.com", "//hooks.example.com/x"}) {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(url))
.as(url)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("http(s)");
}
}
@Test
void shouldAcceptHttpAndHttpsInAnyCase() throws Exception {
assertThat(OutboundUrlGuard.checkStructure("http://hooks.example.com/x").getHost())
.isEqualTo("hooks.example.com");
assertThat(OutboundUrlGuard.checkStructure("HTTPS://hooks.example.com/x").getPort())
.isEqualTo(-1);
assertThat(OutboundUrlGuard.checkStructure("Http://hooks.example.com").getScheme())
.isEqualTo("Http");
}
@Test
void shouldRejectMissingHost() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure("http:///path"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("主机名");
}
@Test
void shouldRejectUserInfoForm() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure(
"https://user:pass@hooks.example.com/x"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("用户名/密码");
}
@Test
void shouldRejectIllegalPort() {
assertThatThrownBy(() -> OutboundUrlGuard.checkStructure("https://hooks.example.com:70000"))
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("端口");
}
// ===== 危险地址段判定 =====
@Test
void shouldRejectLoopbackAndUnspecified() throws Exception {
assertForbidden("127.0.0.1");
assertForbidden("127.5.5.5");
assertForbidden("0.0.0.0");
assertForbidden("0.1.2.3"); // 0/8 本网络段
assertForbidden("::1");
assertForbidden("::");
}
@Test
void shouldRejectPrivateRanges() throws Exception {
assertForbidden("10.0.0.1");
assertForbidden("172.16.0.1");
assertForbidden("192.168.1.1");
assertForbidden("fd00::1"); // IPv6 ULA(Java 未覆盖,补充判定)
assertForbidden("fd00:ec2::254"); // AWS IMDS IPv6
assertForbidden("fe80::1"); // 链路本地
}
@Test
void shouldRejectCloudMetadataAddresses() throws Exception {
assertForbidden("169.254.169.254"); // AWS/GCP/Azure 元数据(链路本地)
assertForbidden("100.100.100.200"); // 阿里云元数据(CGNAT 段,Java 未覆盖)
assertForbidden("100.64.0.1"); // 100.64/10 共享地址段
}
@Test
void shouldRejectMulticastAndReservedRanges() throws Exception {
assertForbidden("224.0.0.1");
assertForbidden("ff02::1");
assertForbidden("240.0.0.1");
assertForbidden("255.255.255.255");
assertForbidden("192.0.0.1");
assertForbidden("192.0.2.1");
assertForbidden("198.18.0.1");
assertForbidden("198.51.100.7");
assertForbidden("203.0.113.9");
}
@Test
void shouldRejectIpv6TransitionAndDocRanges() throws Exception {
assertForbidden("2001:0000:4136:e378:8000:63bf:3fff:fdd2"); // Teredo
assertForbidden("2002:a9fe:a9fe::1"); // 6to4 内嵌 169.254.169.254
assertForbidden("2001:db8::1"); // 文档段
}
@Test
void shouldRejectIpv4MappedOrCompatibleEmbeds() throws Exception {
// ::ffff:x.x.x.x 映射与 ::x.x.x.x 兼容形态按内嵌 IPv4 再判
assertForbidden("::ffff:10.0.0.1");
assertForbidden("::ffff:127.0.0.1");
assertForbidden("::10.0.0.1");
assertAllowed("::ffff:8.8.8.8"); // 映射公网地址放行
}
@Test
void shouldAllowPublicAddresses() throws Exception {
assertAllowed("8.8.8.8");
assertAllowed("1.1.1.1");
assertAllowed("2606:4700::1111");
}
@Test
void shouldClassifyAddressTypes() throws Exception {
assertThat(addr("8.8.8.8")).isInstanceOf(Inet4Address.class);
assertThat(addr("2606:4700::1111")).isInstanceOf(Inet6Address.class);
}
// ===== validate:解析 + 拒绝 + 放行(离线可验证场景) =====
@Test
void shouldValidatePublicIpLiteral() {
// IP 字面量不查 DNS(离线可测):公网地址放行并钉定
StepVerifier.create(guard.validate("https://8.8.8.8:8443/hook"))
.assertNext(target -> {
assertThat(target.address().getHostAddress()).isEqualTo("8.8.8.8");
assertThat(target.port()).isEqualTo(8443);
assertThat(target.uri().getPath()).isEqualTo("/hook");
assertThat(target.toSocketAddress().getPort()).isEqualTo(8443);
})
.verifyComplete();
}
@Test
void shouldRejectLoopbackHostname() {
// localhost 解析到环回地址:整体拒绝(validate 全链路)
StepVerifier.create(guard.validate("http://localhost:1/hook"))
.expectErrorSatisfies(e -> assertThat(e)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("受限网络地址"))
.verify();
}
@Test
void shouldRejectUnresolvableHost() {
// .invalid TLD 保证 NXDOMAIN(RFC 6761):解析失败 fail closed
StepVerifier.create(guard.validate("http://webhook.invalid/hook"))
.expectErrorSatisfies(e -> assertThat(e)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("无法解析"))
.verify();
}
@Test
void shouldRejectMalformedUrlViaValidate() {
StepVerifier.create(guard.validate("javascript:alert(1)"))
.expectErrorSatisfies(e -> assertThat(e)
.isInstanceOf(OutboundUrlGuard.InvalidUrlException.class)
.hasMessageContaining("http(s)"))
.verify();
}
@Test
void shouldExposeUriAndPortOnValidatedTarget() throws Exception {
var target = new OutboundUrlGuard.ValidatedTarget(
new URI("http://hooks.example.com:9000/x"), 9000, addr("8.8.8.8"));
assertThat(target.toSocketAddress().getAddress().getHostAddress()).isEqualTo("8.8.8.8");
assertThat(target.toSocketAddress().getPort()).isEqualTo(9000);
}
// ===== 日志卫生:主机名提取(地址可能内嵌凭据,绝不整体落日志) =====
@Test
void shouldExtractHostForLogging() {
assertThat(OutboundUrlGuard.urlHost("https://hooks.example.com/x?token=abc"))
.isEqualTo("hooks.example.com");
assertThat(OutboundUrlGuard.urlHost(null)).isEqualTo("<unset>");
assertThat(OutboundUrlGuard.urlHost(" ")).isEqualTo("<unset>");
assertThat(OutboundUrlGuard.urlHost("not-a-url")).isEqualTo("<unparsed>");
}
}