package com.ruoyi.system.notification; import com.alibaba.fastjson2.JSON; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.notification.NotificationGateway.*; import com.ruoyi.common.notification.NotificationPolicy; import java.net.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import org.junit.jupiter.api.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.PlatformTransactionManager; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class NotificationContractTest { private Command command(String path) { return new Command("SYSTEM_MESSAGE","fixture","test:1","通知","正文",Set.of(2L),Set.of(),Set.of(Channel.INBOX,Channel.EMAIL),path); } @Test void immutableCanonicalPayloadRoundTripsAndIgnoresSetOrdering() { var one=new Command("SYSTEM_MESSAGE","fixture","test:1","通知","正文",new LinkedHashSet<>(List.of(2L,3L)),Set.of(5L,6L),Set.of(Channel.INBOX,Channel.EMAIL),"/index"); var two=new Command("SYSTEM_MESSAGE","fixture","test:1","通知","正文",new LinkedHashSet<>(List.of(3L,2L)),Set.of(6L,5L),Set.of(Channel.EMAIL,Channel.INBOX),"/index"); assertEquals(NotificationService.canonical(one),NotificationService.canonical(two)); assertEquals(one,JSON.parseObject(NotificationService.canonical(one),Command.class)); assertThrows(UnsupportedOperationException.class,()->one.userIds().add(4L)); } @Test void sourcePathsAndPayloadDoNotAcceptExternalLinksHeaderInjectionOrHugeRecipients() { for(String path:List.of("https://example.com","//example.com","/index?token=secret","/index#x","/a\\b"))assertThrows(ServiceException.class,()->NotificationService.validate(command(path))); for(String path:List.of("","/index","/project/tasks/123"))assertDoesNotThrow(()->NotificationService.validate(command(path))); var c=command("/index"); assertThrows(ServiceException.class,()->NotificationService.validate(new Command(c.businessType(),c.businessId(),c.eventKey(),"x\r\nBcc:attack@example.com",c.content(),c.userIds(),c.roleIds(),c.channels(),c.sourcePath()))); assertThrows(ServiceException.class,()->NotificationService.validate(new Command(c.businessType(),c.businessId(),"随机 中文",c.title(),c.content(),c.userIds(),c.roleIds(),c.channels(),c.sourcePath()))); } @Test void missingOrDenyingBusinessPolicyCannotCreateRowsOrUseMailTransport() { var db=mock(JdbcTemplate.class);var mail=mock(NotificationMailSender.class);var manager=mock(PlatformTransactionManager.class); var service=new NotificationService(db,mail,manager,List.of()); assertEquals(403,assertThrows(ServiceException.class,()->service.publish(command("/index"))).getCode()); NotificationPolicy deny=new NotificationPolicy(){public String businessType(){return "SYSTEM_MESSAGE";}public void checkPublisher(Command c){throw new ServiceException("denied",403);}public boolean canReceive(long id,Command c){return true;}}; var guarded=new NotificationService(db,mail,manager,List.of(deny)); assertEquals(403,assertThrows(ServiceException.class,()->guarded.publish(command("/index"))).getCode()); assertThrows(IllegalStateException.class,()->new NotificationService(db,mail,manager,List.of(deny,deny))); verifyNoInteractions(db,mail,manager); } @Test void feedbackUsesTheSharedTransportWithoutChangingItsConfirmationWorkflow() throws Exception { var shared=mock(NotificationMailSender.class);var feedback=new FeedbackMailSender(shared); when(shared.ready()).thenReturn(true);assertTrue(feedback.ready()); feedback.send(List.of("owner@example.com"),"标题","正文","feedback-test"); verify(shared).send(List.of("owner@example.com"),"标题","正文","feedback-test"); } @Test void jakartaMailReallyPerformsSmtpAgainstALocalSinkOnly() throws Exception { // Bind loopback only. No real addresses or external SMTP servers are contacted. try(var sink=new ServerSocket(0,1,InetAddress.getLoopbackAddress())) { sink.setSoTimeout(10000);var commands=new CopyOnWriteArrayList(); var capture=CompletableFuture.supplyAsync(()->{ try(var socket=sink.accept();var reader=new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));var writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),StandardCharsets.UTF_8))) { socket.setSoTimeout(10000);writer.write("220 localhost test\r\n");writer.flush();boolean data=false; for(String line;(line=reader.readLine())!=null;) { commands.add(line); if(data){if(line.equals(".")){data=false;writer.write("250 accepted\r\n");writer.flush();}continue;} if(line.startsWith("EHLO")||line.startsWith("HELO"))writer.write("250 localhost\r\n"); else if(line.equals("DATA")){writer.write("354 continue\r\n");data=true;} else if(line.equals("QUIT")){writer.write("221 bye\r\n");writer.flush();break;} else writer.write("250 ok\r\n");writer.flush(); } return true; }catch(Exception e){throw new CompletionException(e);} }); var smtp=new JavaMailSenderImpl();smtp.setHost(sink.getInetAddress().getHostAddress());smtp.setPort(sink.getLocalPort()); smtp.getJavaMailProperties().setProperty("mail.smtp.connectiontimeout","5000");smtp.getJavaMailProperties().setProperty("mail.smtp.timeout","5000"); var sender=new NotificationMailSender(smtp);ReflectionTestUtils.setField(sender,"enabled",true);ReflectionTestUtils.setField(sender,"username","sender@example.com");ReflectionTestUtils.setField(sender,"password","local-test-only");ReflectionTestUtils.setField(sender,"senderName","业务通知"); sender.send(List.of("recipient@example.com"),"本地通知验证","中文正文,仅进入本机测试接收器","notification-local-test"); assertTrue(capture.get(10,TimeUnit.SECONDS)); assertEquals(1,commands.stream().filter(line->line.startsWith("RCPT TO:")).count()); assertTrue(commands.contains("RCPT TO:")); assertFalse(commands.contains("RCPT TO:")); assertTrue(commands.stream().anyMatch(line->line.equals("X-WMS-Notification-Id: notification-local-test"))); } } }