This is an automated email from the ASF dual-hosted git repository.
lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git
The following commit(s) were added to refs/heads/master by this push:
new abbff96df fix: bound integration HTTP response bodies (#6927)
abbff96df is described below
commit abbff96dfeadf1d416eb6eecb71d71f7e4454985
Author: zmuxuny <[email protected]>
AuthorDate: Fri Nov 27 12:41:26 2026 +0800
fix: bound integration HTTP response bodies (#6927)
---
server/README.md | 8 +
.../util/BoundedResponseBodyInterceptor.java | 107 +++++++++++++
.../ops/alert/NotificationOutboxService.java | 3 +
.../rocketmq/studio/settings/SettingsService.java | 8 +-
.../util/BoundedResponseBodyInterceptorTest.java | 165 +++++++++++++++++++
.../alert/NotificationResponseBodyLimitTest.java | 178 +++++++++++++++++++++
.../studio/settings/SettingsServiceTest.java | 79 +++++++++
7 files changed, 547 insertions(+), 1 deletion(-)
diff --git a/server/README.md b/server/README.md
index d7b312728..2ee446ceb 100644
--- a/server/README.md
+++ b/server/README.md
@@ -79,6 +79,14 @@ org.apache.rocketmq.studio
### settings / audit
通用设置(`rmq_settings`)、外部数据源配置与连通性测试、写操作审计。
+### 集成 HTTP 响应大小限制
+
+数据源连接测试与钉钉 / SMS Webhook 客户端的响应体上限为 **5 MiB(5,242,880 字节)**,
+与常规 Prometheus 查询的响应预算一致。该限制在字符串转换和 HTTP 错误处理前生效,
+同时覆盖成功及错误状态;缺少或低报 `Content-Length` 也不会绕过实际读取字节数检查。
+恰好达到上限的响应仍会被正常解析,超限的数据源测试返回失败,通知投递沿用现有重试及耗尽策略。
+连接 / 读取超时、URL 校验和禁止重定向策略保持不变。
+
## 分层与命名约定
- **Controller → Service → Repository**:Controller 只做入参校验与 `Result` 包装;
diff --git
a/server/src/main/java/org/apache/rocketmq/studio/common/util/BoundedResponseBodyInterceptor.java
b/server/src/main/java/org/apache/rocketmq/studio/common/util/BoundedResponseBodyInterceptor.java
new file mode 100644
index 000000000..96065be31
--- /dev/null
+++
b/server/src/main/java/org/apache/rocketmq/studio/common/util/BoundedResponseBodyInterceptor.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.studio.common.util;
+
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpRequest;
+import org.springframework.http.HttpStatusCode;
+import org.springframework.http.client.ClientHttpRequestExecution;
+import org.springframework.http.client.ClientHttpRequestInterceptor;
+import org.springframework.http.client.ClientHttpResponse;
+import org.springframework.web.client.RestClientException;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/** Bounds response bodies before message converters or HTTP error handlers
can buffer them. */
+public final class BoundedResponseBodyInterceptor implements
ClientHttpRequestInterceptor {
+
+ private final int maxResponseBytes;
+
+ public BoundedResponseBodyInterceptor(int maxResponseBytes) {
+ if (maxResponseBytes <= 0 || maxResponseBytes == Integer.MAX_VALUE) {
+ throw new IllegalArgumentException("Response body limit must be
positive and less than Integer.MAX_VALUE");
+ }
+ this.maxResponseBytes = maxResponseBytes;
+ }
+
+ @Override
+ public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution)
+ throws IOException {
+ ClientHttpResponse response = execution.execute(request, body);
+ try {
+ byte[] boundedBody;
+ // Close the upstream stream even on rejection, before
response.close() can try to drain it.
+ try (InputStream stream = response.getBody()) {
+ if (response.getHeaders().getContentLength() >
maxResponseBytes) {
+ throw new ResponseTooLargeException(maxResponseBytes);
+ }
+ // The extra byte distinguishes an exact-boundary body from an
oversized/chunked one.
+ boundedBody = stream.readNBytes(maxResponseBytes + 1);
+ if (boundedBody.length > maxResponseBytes) {
+ throw new ResponseTooLargeException(maxResponseBytes);
+ }
+ }
+ return new BufferedResponse(response, boundedBody);
+ } catch (IOException | RuntimeException exception) {
+ response.close();
+ throw exception;
+ }
+ }
+
+ public static final class ResponseTooLargeException extends
RestClientException {
+ public ResponseTooLargeException(int maxResponseBytes) {
+ super("HTTP response body exceeds " + maxResponseBytes + " bytes");
+ }
+ }
+
+ private static final class BufferedResponse implements ClientHttpResponse {
+ private final ClientHttpResponse response;
+ private final InputStream body;
+
+ private BufferedResponse(ClientHttpResponse response, byte[] body) {
+ this.response = response;
+ this.body = new ByteArrayInputStream(body);
+ }
+
+ @Override
+ public HttpStatusCode getStatusCode() throws IOException {
+ return response.getStatusCode();
+ }
+
+ @Override
+ public String getStatusText() throws IOException {
+ return response.getStatusText();
+ }
+
+ @Override
+ public HttpHeaders getHeaders() {
+ return response.getHeaders();
+ }
+
+ @Override
+ public InputStream getBody() {
+ return body;
+ }
+
+ @Override
+ public void close() {
+ response.close();
+ }
+ }
+}
diff --git
a/server/src/main/java/org/apache/rocketmq/studio/ops/alert/NotificationOutboxService.java
b/server/src/main/java/org/apache/rocketmq/studio/ops/alert/NotificationOutboxService.java
index 57d33fb64..28f769342 100644
---
a/server/src/main/java/org/apache/rocketmq/studio/ops/alert/NotificationOutboxService.java
+++
b/server/src/main/java/org/apache/rocketmq/studio/ops/alert/NotificationOutboxService.java
@@ -27,6 +27,7 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.studio.audit.OperationAuditService;
import org.apache.rocketmq.studio.cluster.metrics.AlertingProperties;
import org.apache.rocketmq.studio.common.domain.PageResult;
+import org.apache.rocketmq.studio.common.util.BoundedResponseBodyInterceptor;
import
org.apache.rocketmq.studio.common.util.NoRedirectClientHttpRequestFactory;
import org.apache.rocketmq.studio.common.util.TextBounds;
import org.apache.rocketmq.studio.common.util.UrlHostGuard;
@@ -75,6 +76,7 @@ import jakarta.mail.internet.InternetAddress;
@Service
public class NotificationOutboxService {
private static final int MAX_ATTEMPTS = 5;
+ private static final int MAX_WEBHOOK_RESPONSE_BYTES = 5 * 1024 * 1024;
private static final int BATCH_SIZE = 20;
private static final Duration DEFAULT_CLAIM_TIMEOUT =
Duration.ofMinutes(1);
private static final Duration DEFAULT_CLAIM_RENEWAL_INTERVAL =
Duration.ofSeconds(20);
@@ -149,6 +151,7 @@ public class NotificationOutboxService {
this.alertRepository = alertRepository;
this.operationAuditService = operationAuditService;
this.restTemplate = restTemplate;
+ this.restTemplate.getInterceptors().add(new
BoundedResponseBodyInterceptor(MAX_WEBHOOK_RESPONSE_BYTES));
this.mailSender = mailSender;
this.alertingProperties = alertingProperties == null ? new
AlertingProperties() : alertingProperties;
this.claimTimeout =
positiveDuration(this.alertingProperties.getNotificationClaimTimeout(),
diff --git
a/server/src/main/java/org/apache/rocketmq/studio/settings/SettingsService.java
b/server/src/main/java/org/apache/rocketmq/studio/settings/SettingsService.java
index 88e656862..58bb873b4 100644
---
a/server/src/main/java/org/apache/rocketmq/studio/settings/SettingsService.java
+++
b/server/src/main/java/org/apache/rocketmq/studio/settings/SettingsService.java
@@ -25,6 +25,7 @@ import
org.apache.rocketmq.studio.cluster.metrics.MetricsBackendType;
import org.apache.rocketmq.studio.cluster.metrics.PrometheusQueryUri;
import org.apache.rocketmq.studio.common.exception.BusinessException;
import org.apache.rocketmq.studio.common.domain.PageResult;
+import org.apache.rocketmq.studio.common.util.BoundedResponseBodyInterceptor;
import org.apache.rocketmq.studio.common.util.UrlHostGuard;
import java.net.InetAddress;
import java.net.UnknownHostException;
@@ -70,6 +71,7 @@ public class SettingsService {
}, // AWS IMDS IPv6: fd00:ec2::254
new byte[] {100, 100, 100, (byte) 200}); // Alibaba Cloud ECS
metadata
private static final String PROMETHEUS_TEST_QUERY = "up";
+ private static final int MAX_DATA_SOURCE_RESPONSE_BYTES = 5 * 1024 * 1024;
private static final String AUTH_NONE = "none";
private static final String AUTH_BASIC = "basic auth";
private static final String AUTH_BEARER = "bearer token";
@@ -90,7 +92,9 @@ public class SettingsService {
SettingsService(SettingsRepository settingsRepository, RestClient
restClient,
ObjectMapper objectMapper, OperationAuditService
operationAuditService) {
this.settingsRepository = settingsRepository;
- this.restClient = restClient;
+ this.restClient = restClient.mutate()
+ .requestInterceptor(new
BoundedResponseBodyInterceptor(MAX_DATA_SOURCE_RESPONSE_BYTES))
+ .build();
this.objectMapper = objectMapper;
this.operationAuditService = operationAuditService;
}
@@ -348,6 +352,8 @@ public class SettingsService {
return prometheusSuccess(parseJson(body));
} catch (IllegalArgumentException | URISyntaxException exception) {
return failed(exception.getMessage());
+ } catch (BoundedResponseBodyInterceptor.ResponseTooLargeException
exception) {
+ return failed("Prometheus response body exceeds " +
MAX_DATA_SOURCE_RESPONSE_BYTES + " bytes");
} catch (RestClientResponseException exception) {
return failed(prometheusErrorMessage(exception));
} catch (ResourceAccessException exception) {
diff --git
a/server/src/test/java/org/apache/rocketmq/studio/common/util/BoundedResponseBodyInterceptorTest.java
b/server/src/test/java/org/apache/rocketmq/studio/common/util/BoundedResponseBodyInterceptorTest.java
new file mode 100644
index 000000000..7e2a2ecf5
--- /dev/null
+++
b/server/src/test/java/org/apache/rocketmq/studio/common/util/BoundedResponseBodyInterceptorTest.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.studio.common.util;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.client.ClientHttpResponse;
+import org.springframework.mock.http.client.MockClientHttpResponse;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.SocketTimeoutException;
+import java.util.Arrays;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+
+class BoundedResponseBodyInterceptorTest {
+ private static final int LIMIT = 32;
+ private final BoundedResponseBodyInterceptor interceptor = new
BoundedResponseBodyInterceptor(LIMIT);
+
+ @ParameterizedTest
+ @ValueSource(ints = {200, 400, 500})
+ void rejectsOversizedBodiesWithoutContentLengthAfterOneExtraByteTest(int
status) throws Exception {
+ TrackingStream stream = new TrackingStream(LIMIT + 100);
+ MockClientHttpResponse response = spy(new
MockClientHttpResponse(stream, HttpStatus.valueOf(status)));
+
+ assertThatThrownBy(() -> intercept(response))
+
.isInstanceOf(BoundedResponseBodyInterceptor.ResponseTooLargeException.class)
+ .hasMessage("HTTP response body exceeds 32 bytes");
+
+ assertThat(stream.bytesRead).isEqualTo(LIMIT + 1);
+ assertThat(stream.closed).isTrue();
+ verify(response, atLeastOnce()).close();
+ }
+
+ @Test
+ void rejectsAdvertisedOversizeBeforeReadingTheBodyTest() {
+ TrackingStream stream = new TrackingStream(LIMIT + 100);
+ MockClientHttpResponse response = spy(new
MockClientHttpResponse(stream, HttpStatus.BAD_GATEWAY));
+ response.getHeaders().setContentLength(LIMIT + 1);
+
+ assertThatThrownBy(() -> intercept(response))
+
.isInstanceOf(BoundedResponseBodyInterceptor.ResponseTooLargeException.class);
+
+ assertThat(stream.bytesRead).isZero();
+ assertThat(stream.closed).isTrue();
+ verify(response, atLeastOnce()).close();
+ }
+
+ @Test
+ void doesNotTrustAnUnderstatedContentLengthTest() {
+ TrackingStream stream = new TrackingStream(LIMIT + 100);
+ MockClientHttpResponse response = spy(new
MockClientHttpResponse(stream, HttpStatus.OK));
+ response.getHeaders().setContentLength(1);
+
+ assertThatThrownBy(() -> intercept(response))
+
.isInstanceOf(BoundedResponseBodyInterceptor.ResponseTooLargeException.class);
+
+ assertThat(stream.bytesRead).isEqualTo(LIMIT + 1);
+ assertThat(stream.closed).isTrue();
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {0, LIMIT - 1, LIMIT})
+ void acceptsBodiesAtOrBelowTheBoundaryAndPreservesMetadataTest(int length)
throws Exception {
+ TrackingStream stream = new TrackingStream(length);
+ MockClientHttpResponse response = spy(new
MockClientHttpResponse(stream, HttpStatus.UNPROCESSABLE_ENTITY));
+ response.getHeaders().add("X-Upstream", "preserved");
+
+ ClientHttpResponse bounded = intercept(response);
+
+ byte[] bytes = bounded.getBody().readAllBytes();
+ assertThat(bytes).hasSize(length);
+ if (length > 0) {
+ assertThat(bytes).containsOnly((byte) 'x');
+ }
+
assertThat(bounded.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
+
assertThat(bounded.getStatusText()).isEqualTo(response.getStatusText());
+
assertThat(bounded.getHeaders().getFirst("X-Upstream")).isEqualTo("preserved");
+ assertThat(stream.bytesRead).isEqualTo(length);
+ assertThat(stream.closed).isTrue();
+ bounded.close();
+ verify(response, atLeastOnce()).close();
+ }
+
+ @Test
+ void propagatesReadTimeoutAndClosesTheResponseTest() {
+ SocketTimeoutException timeout = new SocketTimeoutException("read
timed out");
+ InputStream stream = new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw timeout;
+ }
+ };
+ MockClientHttpResponse response = spy(new
MockClientHttpResponse(stream, HttpStatus.OK));
+
+ assertThatThrownBy(() -> intercept(response)).isSameAs(timeout);
+ verify(response, atLeastOnce()).close();
+ }
+
+ private ClientHttpResponse intercept(ClientHttpResponse response) throws
IOException {
+ return
interceptor.intercept(mock(org.springframework.http.HttpRequest.class), new
byte[0],
+ (request, body) -> response);
+ }
+
+ /** Emits a few bytes at a time without allocating the entire advertised
body. */
+ private static final class TrackingStream extends InputStream {
+ private final int length;
+ private int bytesRead;
+ private boolean closed;
+
+ private TrackingStream(int length) {
+ this.length = length;
+ }
+
+ @Override
+ public int read() {
+ if (bytesRead == length) {
+ return -1;
+ }
+ bytesRead++;
+ return 'x';
+ }
+
+ @Override
+ public int read(byte[] buffer, int offset, int count) {
+ if (count == 0) {
+ return 0;
+ }
+ if (bytesRead == length) {
+ return -1;
+ }
+ int read = Math.min(Math.min(count, 3), length - bytesRead);
+ Arrays.fill(buffer, offset, offset + read, (byte) 'x');
+ bytesRead += read;
+ return read;
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+ }
+}
diff --git
a/server/src/test/java/org/apache/rocketmq/studio/ops/alert/NotificationResponseBodyLimitTest.java
b/server/src/test/java/org/apache/rocketmq/studio/ops/alert/NotificationResponseBodyLimitTest.java
new file mode 100644
index 000000000..ec16841bb
--- /dev/null
+++
b/server/src/test/java/org/apache/rocketmq/studio/ops/alert/NotificationResponseBodyLimitTest.java
@@ -0,0 +1,178 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.rocketmq.studio.ops.alert;
+
+import org.apache.rocketmq.studio.audit.OperationAuditService;
+import org.apache.rocketmq.studio.common.domain.enums.AlertLevel;
+import
org.apache.rocketmq.studio.persistence.entity.RmqAlertNotificationOutbox;
+import
org.apache.rocketmq.studio.persistence.mapper.RmqAlertNotificationOutboxMapper;
+import org.apache.rocketmq.studio.settings.GeneralSettingsVO;
+import org.apache.rocketmq.studio.settings.SettingsRepository;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.mock.http.client.MockClientHttpResponse;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.client.MockRestServiceServer;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.ByteArrayInputStream;
+import java.net.HttpURLConnection;
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static
org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
+import static
org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
+import static
org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
+
+class NotificationResponseBodyLimitTest {
+ private static final int LIMIT = 5 * 1024 * 1024;
+ private static final String WEBHOOK_URL = "https://192.0.2.1/hook";
+
+ private final RmqAlertNotificationOutboxMapper mapper =
mock(RmqAlertNotificationOutboxMapper.class);
+ private final SettingsRepository settings = mock(SettingsRepository.class);
+ private final AlertRepository alerts = mock(AlertRepository.class);
+ private final OperationAuditService audit =
mock(OperationAuditService.class);
+ private NotificationOutboxService service;
+ private MockRestServiceServer server;
+
+ @BeforeEach
+ void setUpTest() {
+ RestTemplate client = new RestTemplate();
+ server = MockRestServiceServer.bindTo(client).build();
+ service = new NotificationOutboxService(mapper, settings,
mock(AlertSilenceService.class), alerts, audit, client);
+
when(settings.loadGeneralSettings()).thenReturn(GeneralSettingsVO.builder()
+ .dingtalkWebhook(WEBHOOK_URL).smsWebhook(WEBHOOK_URL).build());
+ }
+
+ @AfterEach
+ void tearDownTest() {
+ service.closeHeartbeatExecutor();
+ server.verify();
+ }
+
+ @ParameterizedTest
+ @CsvSource({"200,false", "200,true", "400,false", "400,true", "500,false"})
+ void testNotificationShouldRejectOversizedSuccessAndErrorBodiesTest(int
status, boolean declaredLength) {
+ byte[] oversizedJson = ("{\"errcode\":0}" + " ".repeat(LIMIT +
1)).getBytes(StandardCharsets.UTF_8);
+ ByteArrayInputStream body = new ByteArrayInputStream(oversizedJson);
+ MockClientHttpResponse response = spy(new MockClientHttpResponse(body,
HttpStatus.valueOf(status)));
+ response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
+ if (declaredLength) {
+ response.getHeaders().setContentLength(oversizedJson.length);
+ }
+ server.expect(requestTo(WEBHOOK_URL)).andRespond(request -> response);
+
+ assertThatThrownBy(() -> service.sendTestMessage("dingtalk"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Test notification failed: HTTP response body
exceeds " + LIMIT + " bytes");
+
+ assertThat(body.available()).isEqualTo(declaredLength ?
oversizedJson.length
+ : oversizedJson.length - LIMIT - 1);
+ verify(response, atLeastOnce()).close();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"dingtalk", "sms"})
+ void acceptsAWebhookBodyExactlyAtTheLimitTest(String channel) {
+ String json = "{\"errcode\":0}";
+ server.expect(requestTo(WEBHOOK_URL))
+ .andRespond(withSuccess(json + " ".repeat(LIMIT -
json.length()), MediaType.APPLICATION_JSON));
+
+ assertThatCode(() ->
service.sendTestMessage(channel)).doesNotThrowAnyException();
+ }
+
+ @Test
+ void preservesDingTalkErrorDetailsTest() {
+ server.expect(requestTo(WEBHOOK_URL)).andRespond(withSuccess(
+ "{\"errcode\":310000,\"errmsg\":\"keywords not in content\"}",
MediaType.APPLICATION_JSON));
+
+ assertThatThrownBy(() -> service.sendTestMessage("dingtalk"))
+ .hasMessage("Test notification failed: DingTalk rejected
webhook: keywords not in content");
+ }
+
+ @Test
+ void preservesHttpErrorHandlingForSmallWebhookBodiesTest() {
+
server.expect(requestTo(WEBHOOK_URL)).andRespond(withStatus(HttpStatus.SERVICE_UNAVAILABLE)
+ .contentType(MediaType.TEXT_PLAIN).body("temporarily
unavailable"));
+
+ assertThatThrownBy(() -> service.sendTestMessage("sms"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("503").hasMessageContaining("temporarily
unavailable");
+ }
+
+ @ParameterizedTest
+ @CsvSource({"200,0", "500,0", "200,4", "500,4"})
+ void
oversizedBodiesShouldFollowTheExistingRetryAndExhaustionPolicyTest(int status,
int attempts) {
+ RmqAlertNotificationOutbox row = new RmqAlertNotificationOutbox();
+ row.setId(8L);
+ row.setAlertId(9L);
+ row.setChannel("dingtalk");
+ row.setStatus("PENDING");
+ row.setAttemptCount(attempts);
+ when(mapper.findDispatchable(any(LocalDateTime.class),
any(LocalDateTime.class), any(Integer.class)))
+ .thenReturn(List.of(row));
+ when(mapper.claimForDispatch(any(), any(LocalDateTime.class),
any(LocalDateTime.class),
+ any(LocalDateTime.class), anyString(),
eq(attempts))).thenReturn(1);
+ when(mapper.update(any(), any())).thenReturn(1);
+
when(alerts.findAlertById(9L)).thenReturn(Optional.of(SystemAlertVO.builder().id(9L)
+
.level(AlertLevel.warning).title("Lag").description("high").instanceId("local").build()));
+ MockClientHttpResponse response = spy(new MockClientHttpResponse(
+ new ByteArrayInputStream(("{\"errcode\":0}" + " ".repeat(LIMIT
+ 1))
+ .getBytes(StandardCharsets.UTF_8)),
HttpStatus.valueOf(status)));
+ server.expect(requestTo(WEBHOOK_URL)).andRespond(request -> response);
+
+ service.dispatch();
+
+ verify(mapper).update(any(), any());
+ verify(audit).record(attempts == 4 ? "FAIL_ALERT_NOTIFICATION" :
"RETRY_ALERT_NOTIFICATION",
+ "ALERT_NOTIFICATION", "8", null, "alertId=9, channel=dingtalk",
+ "FAILED", "HTTP response body exceeds " + LIMIT + " bytes");
+ verify(response, atLeastOnce()).close();
+ }
+
+ @Test
+ void webhookClientShouldKeepTimeoutsAndRedirectPolicyTest() {
+ RestTemplate client =
ReflectionTestUtils.invokeMethod(NotificationOutboxService.class, "newClient");
+ assertThat(client).isNotNull();
+ HttpURLConnection connection = mock(HttpURLConnection.class);
+
+ ReflectionTestUtils.invokeMethod(client.getRequestFactory(),
"prepareConnection", connection, "POST");
+
+ verify(connection).setConnectTimeout(3000);
+ verify(connection).setReadTimeout(5000);
+ verify(connection, atLeastOnce()).setInstanceFollowRedirects(false);
+ }
+}
diff --git
a/server/src/test/java/org/apache/rocketmq/studio/settings/SettingsServiceTest.java
b/server/src/test/java/org/apache/rocketmq/studio/settings/SettingsServiceTest.java
index 50bc94581..423c8d688 100644
---
a/server/src/test/java/org/apache/rocketmq/studio/settings/SettingsServiceTest.java
+++
b/server/src/test/java/org/apache/rocketmq/studio/settings/SettingsServiceTest.java
@@ -35,9 +35,15 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
+import org.springframework.http.client.ClientHttpRequestFactory;
+import org.springframework.mock.http.client.MockClientHttpResponse;
+import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.RestClient;
+import java.io.ByteArrayInputStream;
+import java.net.HttpURLConnection;
import java.net.InetAddress;
+import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
@@ -51,6 +57,9 @@ import static
org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -58,6 +67,7 @@ import static
org.springframework.test.web.client.match.MockRestRequestMatchers.
import static
org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static
org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static
org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
+import static
org.springframework.test.web.client.response.MockRestResponseCreators.withException;
import static
org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
@ExtendWith(MockitoExtension.class)
@@ -645,6 +655,75 @@ class SettingsServiceTest {
assertThat(result.getMessage()).contains("Unsupported data source
type: grafana-metrics");
}
+ @ParameterizedTest
+ @CsvSource({"200,false", "200,true", "422,false", "422,true", "500,false"})
+ void connectionShouldBoundSuccessAndErrorBodiesTest(int status, boolean
declaredLength) {
+ int limit = 5 * 1024 * 1024;
+ byte[] oversizedJson = (PROMETHEUS_SUCCESS_BODY + " ".repeat(limit +
1))
+ .getBytes(StandardCharsets.UTF_8);
+ ByteArrayInputStream body = new ByteArrayInputStream(oversizedJson);
+ MockClientHttpResponse response = spy(new MockClientHttpResponse(body,
HttpStatus.valueOf(status)));
+ response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
+ if (declaredLength) {
+ response.getHeaders().setContentLength(oversizedJson.length);
+ }
+
prometheusServer.expect(requestTo(PROMETHEUS_QUERY_URL)).andRespond(request ->
response);
+
+ DataSourceTestResultVO result =
settingsService.testDataSource(DataSourceTestDTO.builder()
+ .url(PROMETHEUS_BASE_URL).type("Prometheus").build());
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getMessage()).isEqualTo("Prometheus response body
exceeds " + limit + " bytes");
+ assertThat(body.available()).isEqualTo(declaredLength ?
oversizedJson.length
+ : oversizedJson.length - limit - 1);
+ verify(response, atLeastOnce()).close();
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {200, 422})
+ void connectionShouldParseBodiesExactlyAtTheLimitTest(int status) {
+ String json = status == 200 ? PROMETHEUS_SUCCESS_BODY
+ :
"{\"status\":\"error\",\"errorType\":\"bad_data\",\"error\":\"invalid query\"}";
+ String body = json + " ".repeat(5 * 1024 * 1024 - json.length());
+ prometheusServer.expect(requestTo(PROMETHEUS_QUERY_URL))
+
.andRespond(withStatus(HttpStatus.valueOf(status)).contentType(MediaType.APPLICATION_JSON).body(body));
+
+ DataSourceTestResultVO result =
settingsService.testDataSource(DataSourceTestDTO.builder()
+ .url(PROMETHEUS_BASE_URL).type("Prometheus").build());
+
+ assertThat(result.isSuccess()).isEqualTo(status == 200);
+ assertThat(result.getMessage()).isEqualTo(status == 200 ? "Connection
successful"
+ : "Prometheus query failed (bad_data): invalid query");
+ }
+
+ @Test
+ void connectionShouldKeepTheReadTimeoutErrorTest() {
+ prometheusServer.expect(requestTo(PROMETHEUS_QUERY_URL))
+ .andRespond(withException(new SocketTimeoutException("timed
out")));
+
+ DataSourceTestResultVO result =
settingsService.testDataSource(DataSourceTestDTO.builder()
+ .url(PROMETHEUS_BASE_URL).type("Prometheus").build());
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getMessage()).isEqualTo("Prometheus connection timed
out");
+ }
+
+ @Test
+ void dataSourceClientShouldKeepTimeoutsAndRedirectPolicyTest() {
+ RestClient.Builder builder = spy(RestClient.builder());
+ new SettingsService(settingsRepository, builder, new ObjectMapper(),
operationAuditService);
+ org.mockito.ArgumentCaptor<ClientHttpRequestFactory> factory =
+
org.mockito.ArgumentCaptor.forClass(ClientHttpRequestFactory.class);
+ verify(builder).requestFactory(factory.capture());
+ HttpURLConnection connection = mock(HttpURLConnection.class);
+
+ ReflectionTestUtils.invokeMethod(factory.getValue(),
"prepareConnection", connection, "GET");
+
+ verify(connection).setConnectTimeout(3000);
+ verify(connection).setReadTimeout(5000);
+ verify(connection).setInstanceFollowRedirects(false);
+ }
+
@Test
void connectionShouldApplyBasicAuthenticationTest() {
String expectedAuthorization = "Basic "