Skip to content

Commit de93952

Browse files
wy471xAias00claude
authored
fix(alert): guard against null alert/dateCreated in email alert template (#6457)
* fix(alert): guard against null alert/dateCreated in email alert template * fix(alert): move validation from shared AlarmContent to controller-layer DTO Remove @notblank from AlarmContent (shared DTO used by gateway AlarmSender) and add a separate AlertReportRequest DTO at the controller layer instead. This prevents gateway-generated alerts with null content (e.g. from IllegalArgumentException with no message) from being silently dropped by Spring @Valid rejection before dispatch. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(alert): drop unreachable null-alert guard, add controller validation test Remove the dead alert==null check in EmailAlertNotifyStrategy since DispatchTask.run() already guarantees non-null alerts upstream. Add AlertReportControllerTest covering @notblank validation rejections and correct AlertReportRequest→AlarmContent mapping. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(common): remove whitespace in the pom file * fix(alert): resolve checkstyle declaration order violation in EmailAlertNotifyStrategyTest --------- Co-authored-by: aias00 <[email protected]> Co-authored-by: Claude Opus 4.7 <[email protected]>
1 parent 26645fb commit de93952

6 files changed

Lines changed: 346 additions & 8 deletions

File tree

‎shenyu-admin/src/main/java/org/apache/shenyu/admin/controller/AlertReportController.java‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
package org.apache.shenyu.admin.controller;
1919

2020
import org.apache.shenyu.admin.aspect.annotation.RestApi;
21+
import org.apache.shenyu.admin.model.dto.AlertReportRequest;
2122
import org.apache.shenyu.admin.model.result.ShenyuAdminResult;
2223
import org.apache.shenyu.admin.service.AlertDispatchService;
2324
import org.apache.shenyu.admin.utils.ShenyuResultMessage;
@@ -40,11 +41,20 @@ public class AlertReportController {
4041
/**
4142
* report new alert content.
4243
*
43-
* @param alarmContent AlertContentDTO
44+
* @param request alert report request
4445
* @return row int
4546
*/
4647
@PostMapping
47-
public ShenyuAdminResult reportAlert(@Valid @RequestBody final AlarmContent alarmContent) {
48+
public ShenyuAdminResult reportAlert(@Valid @RequestBody final AlertReportRequest request) {
49+
AlarmContent alarmContent = new AlarmContent.Builder()
50+
.title(request.getTitle())
51+
.content(request.getContent())
52+
.level(request.getLevel())
53+
.labels(request.getLabels())
54+
.namespaceId(request.getNamespaceId())
55+
.dateCreated(request.getDateCreated())
56+
.dateUpdated(request.getDateUpdated())
57+
.build();
4858
alertDispatchService.dispatchAlert(alarmContent);
4959
return ShenyuAdminResult.success(ShenyuResultMessage.CREATE_SUCCESS);
5060
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.admin.model.dto;
19+
20+
import jakarta.validation.constraints.NotBlank;
21+
import java.util.Date;
22+
import java.util.Map;
23+
24+
/**
25+
* Request DTO for /alert/report endpoint.
26+
* Validation constraints live here so internal callers using AlarmContent directly are unaffected.
27+
*/
28+
public class AlertReportRequest {
29+
30+
@NotBlank
31+
private String title;
32+
33+
private byte level;
34+
35+
private Map<String, String> labels;
36+
37+
@NotBlank
38+
private String content;
39+
40+
private String namespaceId;
41+
42+
private Date dateCreated;
43+
44+
private Date dateUpdated;
45+
46+
public String getTitle() {
47+
return title;
48+
}
49+
50+
public void setTitle(final String title) {
51+
this.title = title;
52+
}
53+
54+
public byte getLevel() {
55+
return level;
56+
}
57+
58+
public void setLevel(final byte level) {
59+
this.level = level;
60+
}
61+
62+
public Map<String, String> getLabels() {
63+
return labels;
64+
}
65+
66+
public void setLabels(final Map<String, String> labels) {
67+
this.labels = labels;
68+
}
69+
70+
public String getContent() {
71+
return content;
72+
}
73+
74+
public void setContent(final String content) {
75+
this.content = content;
76+
}
77+
78+
public String getNamespaceId() {
79+
return namespaceId;
80+
}
81+
82+
public void setNamespaceId(final String namespaceId) {
83+
this.namespaceId = namespaceId;
84+
}
85+
86+
public Date getDateCreated() {
87+
return dateCreated;
88+
}
89+
90+
public void setDateCreated(final Date dateCreated) {
91+
this.dateCreated = dateCreated;
92+
}
93+
94+
public Date getDateUpdated() {
95+
return dateUpdated;
96+
}
97+
98+
public void setDateUpdated(final Date dateUpdated) {
99+
this.dateUpdated = dateUpdated;
100+
}
101+
}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.admin.controller;
19+
20+
import org.apache.shenyu.admin.service.AlertDispatchService;
21+
import org.apache.shenyu.common.dto.AlarmContent;
22+
import org.junit.jupiter.api.BeforeEach;
23+
import org.junit.jupiter.api.Test;
24+
import org.junit.jupiter.api.extension.ExtendWith;
25+
import org.mockito.ArgumentCaptor;
26+
import org.mockito.InjectMocks;
27+
import org.mockito.Mock;
28+
import org.mockito.junit.jupiter.MockitoExtension;
29+
import org.springframework.http.MediaType;
30+
import org.springframework.test.web.servlet.MockMvc;
31+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
32+
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
33+
34+
import static org.junit.jupiter.api.Assertions.assertEquals;
35+
import static org.mockito.Mockito.verify;
36+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
37+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
38+
39+
/**
40+
* Test case for AlertReportController.
41+
*/
42+
@ExtendWith(MockitoExtension.class)
43+
public class AlertReportControllerTest {
44+
45+
private MockMvc mockMvc;
46+
47+
@InjectMocks
48+
private AlertReportController alertReportController;
49+
50+
@Mock
51+
private AlertDispatchService alertDispatchService;
52+
53+
@BeforeEach
54+
public void setUp() {
55+
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
56+
validator.afterPropertiesSet();
57+
this.mockMvc = MockMvcBuilders.standaloneSetup(alertReportController)
58+
.setValidator(validator)
59+
.build();
60+
}
61+
62+
@Test
63+
public void testBlankTitleReturns400() throws Exception {
64+
String body = "{\"title\":\"\",\"content\":\"test content\",\"level\":1}";
65+
66+
this.mockMvc.perform(post("/alert/report")
67+
.contentType(MediaType.APPLICATION_JSON)
68+
.content(body))
69+
.andExpect(status().isBadRequest());
70+
}
71+
72+
@Test
73+
public void testNullTitleReturns400() throws Exception {
74+
String body = "{\"content\":\"test content\",\"level\":1}";
75+
76+
this.mockMvc.perform(post("/alert/report")
77+
.contentType(MediaType.APPLICATION_JSON)
78+
.content(body))
79+
.andExpect(status().isBadRequest());
80+
}
81+
82+
@Test
83+
public void testBlankContentReturns400() throws Exception {
84+
String body = "{\"title\":\"test title\",\"content\":\" \",\"level\":1}";
85+
86+
this.mockMvc.perform(post("/alert/report")
87+
.contentType(MediaType.APPLICATION_JSON)
88+
.content(body))
89+
.andExpect(status().isBadRequest());
90+
}
91+
92+
@Test
93+
public void testNullContentReturns400() throws Exception {
94+
String body = "{\"title\":\"test title\",\"level\":1}";
95+
96+
this.mockMvc.perform(post("/alert/report")
97+
.contentType(MediaType.APPLICATION_JSON)
98+
.content(body))
99+
.andExpect(status().isBadRequest());
100+
}
101+
102+
@Test
103+
public void testValidRequestDispatchesCorrectly() throws Exception {
104+
String body = "{\"title\":\"test title\",\"content\":\"test content\",\"level\":1,\"namespaceId\":\"ns-1\",\"labels\":{\"key\":\"value\"}}";
105+
106+
this.mockMvc.perform(post("/alert/report")
107+
.contentType(MediaType.APPLICATION_JSON)
108+
.content(body))
109+
.andExpect(status().isOk());
110+
111+
ArgumentCaptor<AlarmContent> captor = ArgumentCaptor.forClass(AlarmContent.class);
112+
verify(alertDispatchService).dispatchAlert(captor.capture());
113+
AlarmContent dispatched = captor.getValue();
114+
assertEquals("test title", dispatched.getTitle());
115+
assertEquals("test content", dispatched.getContent());
116+
assertEquals((byte) 1, dispatched.getLevel());
117+
assertEquals("ns-1", dispatched.getNamespaceId());
118+
assertEquals("value", dispatched.getLabels().get("key"));
119+
}
120+
}

‎shenyu-alert/src/main/java/org/apache/shenyu/alert/strategy/EmailAlertNotifyStrategy.java‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,7 @@ private String buildAlertHtmlTemplate(final AlarmContent alert) {
8080
context.setVariable("nameContent", "Alarm Content");
8181
context.setVariable("content", alert.getContent());
8282
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
83-
Date alertTime = alert.getDateCreated();
84-
if (Objects.isNull(alertTime)) {
85-
alertTime = new Date();
86-
}
83+
Date alertTime = Objects.isNull(alert.getDateCreated()) ? new Date() : alert.getDateCreated();
8784
String alarmTime = simpleDateFormat.format(alertTime);
8885
context.setVariable("lastTriggerTime", alarmTime);
8986
return templateEngine.process("mailAlarm", context);

‎shenyu-alert/src/test/java/org/apache/shenyu/alert/strategy/EmailAlertNotifyStrategyTest.java‎

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,29 +20,35 @@
2020
import org.apache.shenyu.alert.model.AlertReceiverDTO;
2121
import org.apache.shenyu.common.dto.AlarmContent;
2222
import org.junit.jupiter.api.BeforeEach;
23+
import org.junit.jupiter.api.BeforeAll;
2324
import org.junit.jupiter.api.Test;
2425
import org.junit.jupiter.api.extension.ExtendWith;
2526
import org.mockito.Mock;
2627
import org.mockito.junit.jupiter.MockitoExtension;
2728
import org.mockito.junit.jupiter.MockitoSettings;
2829
import org.mockito.quality.Strictness;
2930
import org.springframework.mail.javamail.JavaMailSender;
31+
import org.mockito.Mockito;
3032
import org.thymeleaf.TemplateEngine;
3133
import org.thymeleaf.context.Context;
3234

3335
import jakarta.mail.Session;
3436
import jakarta.mail.internet.MimeMessage;
3537
import java.lang.reflect.Field;
3638
import java.text.SimpleDateFormat;
39+
import java.lang.reflect.InvocationTargetException;
40+
import java.lang.reflect.Method;
3741
import java.util.Date;
3842
import java.util.concurrent.atomic.AtomicReference;
3943

4044
import static org.junit.jupiter.api.Assertions.assertEquals;
4145
import static org.junit.jupiter.api.Assertions.assertNotNull;
4246
import static org.junit.jupiter.api.Assertions.assertTrue;
47+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
4348
import static org.mockito.ArgumentMatchers.any;
4449
import static org.mockito.ArgumentMatchers.anyString;
4550
import static org.mockito.Mockito.verify;
51+
import static org.mockito.ArgumentMatchers.eq;
4652
import static org.mockito.Mockito.when;
4753

4854
/**
@@ -60,6 +66,10 @@ public class EmailAlertNotifyStrategyTest {
6066

6167
private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
6268

69+
private static Method buildAlertHtmlTemplateMethod;
70+
71+
private static EmailAlertNotifyStrategy strategy;
72+
6373
@Mock
6474
private JavaMailSender javaMailSender;
6575

@@ -69,8 +79,6 @@ public class EmailAlertNotifyStrategyTest {
6979
@Mock
7080
private AlertReceiverDTO receiver;
7181

72-
private EmailAlertNotifyStrategy strategy;
73-
7482
private final AtomicReference<Context> capturedContext = new AtomicReference<>();
7583

7684
@BeforeEach
@@ -112,4 +120,57 @@ public void testSendWithDateCreated() throws Exception {
112120
assertNotNull(context);
113121
assertEquals("2026-08-21 10:00:00", context.getVariable("lastTriggerTime"));
114122
}
123+
124+
@BeforeAll
125+
public static void setUpAll() throws Exception {
126+
TemplateEngine mockEngine = Mockito.mock(TemplateEngine.class);
127+
when(mockEngine.process(eq("mailAlarm"), any(org.thymeleaf.context.IContext.class)))
128+
.thenReturn("<html>Rendered mailAlarm template</html>");
129+
130+
strategy = new EmailAlertNotifyStrategy(mockEngine, null);
131+
buildAlertHtmlTemplateMethod = EmailAlertNotifyStrategy.class
132+
.getDeclaredMethod("buildAlertHtmlTemplate", AlarmContent.class);
133+
buildAlertHtmlTemplateMethod.setAccessible(true);
134+
}
135+
136+
private String invokeBuildAlertHtmlTemplate(final AlarmContent alert) {
137+
try {
138+
return (String) buildAlertHtmlTemplateMethod.invoke(strategy, alert);
139+
} catch (IllegalAccessException | InvocationTargetException e) {
140+
throw new RuntimeException(e);
141+
}
142+
}
143+
144+
@Test
145+
public void testNullDateCreatedShouldNotThrowNpe() {
146+
AlarmContent alert = new AlarmContent.Builder()
147+
.title("test title")
148+
.content("test content")
149+
.dateCreated(null)
150+
.build();
151+
152+
assertDoesNotThrow(() -> invokeBuildAlertHtmlTemplate(alert));
153+
}
154+
155+
@Test
156+
public void testValidAlertShouldNotThrow() {
157+
AlarmContent alert = new AlarmContent.Builder()
158+
.title("test title")
159+
.content("test content")
160+
.dateCreated(new Date())
161+
.build();
162+
163+
assertDoesNotThrow(() -> invokeBuildAlertHtmlTemplate(alert));
164+
}
165+
166+
@Test
167+
public void testNullContentShouldNotThrow() {
168+
AlarmContent alert = new AlarmContent.Builder()
169+
.title("test title")
170+
.content(null)
171+
.dateCreated(new Date())
172+
.build();
173+
174+
assertDoesNotThrow(() -> invokeBuildAlertHtmlTemplate(alert));
175+
}
115176
}

0 commit comments

Comments
 (0)