diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java
index 7e34bb01..75063a56 100644
--- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java
+++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java
@@ -6,7 +6,6 @@ import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto;
-import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
@@ -15,8 +14,6 @@ import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import java.util.Map;
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
@@ -61,8 +58,6 @@ class WechatContentModerationCallbackControllerTest {
new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true));
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
when(crypto.verifyPlain("callback-token", "1000", "nonce", "plain-signature")).thenReturn(true);
- WechatMiniProperties wechatProperties = new WechatMiniProperties();
- wechatProperties.setAppId("mini-app-id");
WechatContentModerationCallbackController controller = controller(secureConfig, crypto,
mock(ContentModerationService.class), mock(IntegrationProbeService.class),
mock(ContentModerationForwardService.class));
@@ -72,15 +67,16 @@ class WechatContentModerationCallbackControllerTest {
}
@Test
- void localHitDoesNotForward() throws Exception {
+ void localHitDoesNotProbeAndForward() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
- when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
- .thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"envVersion\\\":\\\"trial\\\"}\"}");
- when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial")).thenReturn(true);
+ String decoded = "{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"}}";
+ when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")).thenReturn(decoded);
+ when(forwardService.reserveTrace("task-json")).thenReturn(true);
+ when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调")).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
@@ -94,41 +90,8 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(status().isOk())
.andExpect(content().string("success"));
- verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature");
- verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial");
- verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
- verify(forwardService, never()).recordUnclaimed(anyString(), any(), any(), anyString());
- }
-
- @Test
- void keepsXmlEnvelopeSupportForAesEncryptedCallback() throws Exception {
- SecureIntegrationConfigService secureConfig = readyWechatConfig();
- WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
- ContentModerationService moderationService = mock(ContentModerationService.class);
- String xml = "encrypted-xml";
- when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
- when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true);
- String decodedXml = "task-xmlreview{"env":"prod","envVersion":"release"}";
- when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml);
- when(crypto.value(decodedXml, "trace_id")).thenReturn("task-xml");
- when(crypto.value(decodedXml, "suggest")).thenReturn("review");
- when(crypto.value(decodedXml, "extra")).thenReturn("{\"env\":\"prod\",\"envVersion\":\"release\"}");
- when(moderationService.handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release")).thenReturn(true);
- MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
- mock(IntegrationProbeService.class), mock(ContentModerationForwardService.class))).build();
-
- mvc.perform(post("/integration/wechat/content-moderation/callback")
- .param("timestamp", "1000")
- .param("nonce", "nonce")
- .param("msg_signature", "message-signature")
- .param("encrypt_type", "aes")
- .contentType(MediaType.APPLICATION_XML)
- .content(xml))
- .andExpect(status().isOk())
- .andExpect(content().string("success"));
-
- verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature");
- verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release");
+ verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调");
+ verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
}
@Test
@@ -139,8 +102,9 @@ class WechatContentModerationCallbackControllerTest {
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
- .thenReturn("{\"trace_id\":\"probe-1\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"probeId\\\":\\\"probe-1\\\"}\"}");
- when(probeService.handleImageCallback("probe-1", "review", "probe-1")).thenReturn(true);
+ .thenReturn("{\"trace_id\":\"probe-1\",\"suggest\":\"review\"}");
+ when(forwardService.reserveTrace("probe-1")).thenReturn(true);
+ when(probeService.handleImageCallback("probe-1", "review", null)).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
mock(ContentModerationService.class), probeService, forwardService)).build();
@@ -154,20 +118,21 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(status().isOk())
.andExpect(content().string("success"));
- verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
+ verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
}
@Test
- void otherEnvironmentCallbackIsEnqueuedAndReturnsSuccessImmediately() throws Exception {
+ void localMissForwardsRawDecryptedPayload() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
- when(crypto.decrypt(anyString(), anyString(), anyString()))
- .thenReturn("{\"trace_id\":\"task-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}");
- when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
- when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH)));
+ String decoded = "{\"trace_id\":\"task-prod\",\"result\":{\"suggest\":\"review\"},\"errmsg\":\"人工复核\"}";
+ when(crypto.decrypt(anyString(), anyString(), anyString())).thenReturn(decoded);
+ when(forwardService.reserveTrace("task-prod")).thenReturn(true);
+ when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString())).thenReturn(false);
+ when(forwardService.probeAndForward(anyString(), anyString(), anyString())).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
@@ -181,20 +146,20 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(status().isOk())
.andExpect(content().string("success"));
- verify(forwardService).enqueue(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString());
+ verify(forwardService).probeAndForward(eq("task-prod"), eq(decoded), anyString());
+ verify(forwardService, never()).releaseTrace("task-prod");
}
@Test
- void missingTargetReturnsSuccessAndRecordsTargetMissing() throws Exception {
+ void duplicateTraceReturnsSuccessWithoutProcessing() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
when(crypto.decrypt(anyString(), anyString(), anyString()))
- .thenReturn("{\"trace_id\":\"task-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}");
- when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
- when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of()));
+ .thenReturn("{\"trace_id\":\"task-dup\",\"suggest\":\"review\"}");
+ when(forwardService.reserveTrace("task-dup")).thenReturn(false);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
@@ -208,20 +173,25 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(status().isOk())
.andExpect(content().string("success"));
- verify(forwardService).recordTargetMissing(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString());
+ verify(moderationService, never()).handleWechatImageResult(anyString(), anyString(), anyString());
+ verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
}
@Test
- void extraWithoutEnvIsRecordedAsNoEnvAndNotForwarded() throws Exception {
+ void keepsXmlEnvelopeSupportForAesEncryptedCallback() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
- when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
- when(crypto.decrypt(anyString(), anyString(), anyString()))
- .thenReturn("{\"trace_id\":\"task-unknown\",\"suggest\":\"review\",\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}");
- when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
- when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH)));
+ String xml = "encrypted-xml";
+ when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
+ when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true);
+ String decodedXml = "task-xmlreview";
+ when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml);
+ when(crypto.value(decodedXml, "trace_id")).thenReturn("task-xml");
+ when(crypto.value(decodedXml, "suggest")).thenReturn("review");
+ when(forwardService.reserveTrace("task-xml")).thenReturn(true);
+ when(moderationService.handleWechatImageResult("task-xml", "review", "微信异步图片审核回调")).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
@@ -230,35 +200,104 @@ class WechatContentModerationCallbackControllerTest {
.param("nonce", "nonce")
.param("msg_signature", "message-signature")
.param("encrypt_type", "aes")
- .contentType(MediaType.APPLICATION_JSON)
- .content("{\"Encrypt\":\"encrypted-json\"}"))
+ .contentType(MediaType.APPLICATION_XML)
+ .content(xml))
.andExpect(status().isOk())
.andExpect(content().string("success"));
- verify(forwardService).recordUnclaimed(eq("task-unknown"), anyString(), anyString(), anyString());
- verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
+ verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调");
}
@Test
- void secondHopOrSelfForwardIsDroppedAndRecorded() throws Exception {
+ void forwardedCallbackClaimsLocally() throws Exception {
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
+ ContentModerationService moderationService = mock(ContentModerationService.class);
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+ when(forwardService.reserveTrace("task-claim")).thenReturn(true);
+ when(moderationService.handleWechatImageResult("task-claim", "review", "微信异步图片审核回调")).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class),
- mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
+ moderationService, mock(IntegrationProbeService.class), forwardService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
- .header("X-Moderation-Forward-By", "sit")
- .header("X-Moderation-Forward-Hop", "2")
+ .header("X-Moderation-Forward-By", "prod")
+ .header("X-Moderation-Forward-Hop", "1")
.header("X-Timestamp", "1000")
.header("X-Nonce", "forward-nonce")
.header("X-Signature", "forward-signature")
.contentType(MediaType.APPLICATION_JSON)
- .content("{\"trace_id\":\"loop-task\",\"suggest\":\"review\"}"))
+ .content("{\"trace_id\":\"task-claim\",\"suggest\":\"review\"}"))
.andExpect(status().isOk())
- .andExpect(content().string("success"));
+ .andExpect(content().string("CLAIMED"));
+ }
- verify(forwardService).recordUnclaimed(eq("loop-task"), any(), anyString(), anyString());
- verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
+ @Test
+ void forwardedCallbackReturnsNotMineWhenLocalMiss() throws Exception {
+ ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
+ ContentModerationService moderationService = mock(ContentModerationService.class);
+ when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+ when(forwardService.reserveTrace("task-other")).thenReturn(true);
+ when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString())).thenReturn(false);
+ MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class),
+ moderationService, mock(IntegrationProbeService.class), forwardService)).build();
+
+ mvc.perform(post("/integration/wechat/content-moderation/callback")
+ .header("X-Moderation-Forward-By", "prod")
+ .header("X-Moderation-Forward-Hop", "1")
+ .header("X-Timestamp", "1000")
+ .header("X-Nonce", "forward-nonce")
+ .header("X-Signature", "forward-signature")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content("{\"trace_id\":\"task-other\",\"suggest\":\"review\"}"))
+ .andExpect(status().isOk())
+ .andExpect(content().string("NOT_MINE"));
+
+ verify(forwardService).releaseTrace("task-other");
+ }
+
+ @Test
+ void forwardedDuplicateReturnsClaimed() throws Exception {
+ ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
+ when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+ when(forwardService.reserveTrace("task-dup-forward")).thenReturn(false);
+ MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class),
+ mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
+
+ mvc.perform(post("/integration/wechat/content-moderation/callback")
+ .header("X-Moderation-Forward-By", "prod")
+ .header("X-Moderation-Forward-Hop", "1")
+ .header("X-Timestamp", "1000")
+ .header("X-Nonce", "forward-nonce")
+ .header("X-Signature", "forward-signature")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content("{\"trace_id\":\"task-dup-forward\",\"suggest\":\"review\"}"))
+ .andExpect(status().isOk())
+ .andExpect(content().string("CLAIMED"));
+ }
+
+ @Test
+ void forwardedHopGreaterThanOneIsRejected() {
+ ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
+ when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+ WechatContentModerationCallbackController controller = controller(readyWechatConfig(),
+ mock(WechatCallbackCrypto.class), mock(ContentModerationService.class),
+ mock(IntegrationProbeService.class), forwardService);
+
+ assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null,
+ "prod", "2", "1000", "forward-nonce", "forward-signature",
+ "{\"trace_id\":\"loop-task\"}"));
+ }
+
+ @Test
+ void forwardedSourceEqualToSelfIsRejected() {
+ ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
+ when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+ WechatContentModerationCallbackController controller = controller(readyWechatConfig(),
+ mock(WechatCallbackCrypto.class), mock(ContentModerationService.class),
+ mock(IntegrationProbeService.class), forwardService);
+
+ assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null,
+ "sit", "1", "1000", "forward-nonce", "forward-signature",
+ "{\"trace_id\":\"self-task\"}"));
}
@Test
@@ -274,10 +313,6 @@ class WechatContentModerationCallbackControllerTest {
"{\"trace_id\":\"task-1\"}"));
}
- private ModerationForwardConfig forwardConfig(Map targets) {
- return new ModerationForwardConfig(true, targets, "forward-secret-key-01");
- }
-
private SecureIntegrationConfigService readyWechatConfig() {
SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class);
when(secureConfig.getModerationCallbackConfig()).thenReturn(
diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java
index 4e0a40a1..b1001c0c 100644
--- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java
+++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient;
+import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationProbeResult;
import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper;
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
@@ -9,13 +10,15 @@ import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegratio
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Duration;
import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -24,149 +27,254 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
-
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ContentModerationForwardServiceImplTest {
- private static final String SECRET = "forward-secret-key-01";
- private static final String TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback";
+ private static final String SECRET = "forward-secret-1234567890";
+ private static final String DEV_TARGET = "https://dev.example.test/api/integration/wechat/content-moderation/callback";
+ private static final String PROD_TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback";
private ModerationCallbackForwardMapper forwardMapper;
- private SecureIntegrationConfigService secureConfig;
- private ModerationForwardHttpClient httpClient;
+ private SecureIntegrationConfigService secureIntegrationConfigService;
private RedisTemplate redisTemplate;
private ValueOperations valueOperations;
+ private ModerationForwardHttpClient forwardHttpClient;
private ContentModerationForwardServiceImpl service;
@BeforeEach
- @SuppressWarnings("unchecked")
void setUp() {
forwardMapper = mock(ModerationCallbackForwardMapper.class);
- secureConfig = mock(SecureIntegrationConfigService.class);
- httpClient = mock(ModerationForwardHttpClient.class);
+ secureIntegrationConfigService = mock(SecureIntegrationConfigService.class);
redisTemplate = mock(RedisTemplate.class);
valueOperations = mock(ValueOperations.class);
+ forwardHttpClient = mock(ModerationForwardHttpClient.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(true);
- when(secureConfig.getModerationForwardConfig())
- .thenReturn(new ModerationForwardConfig(true, Map.of("prod", TARGET), SECRET));
SalonDeployProperties deployProperties = new SalonDeployProperties();
deployProperties.setEnv("sit");
- service = new ContentModerationForwardServiceImpl(forwardMapper, secureConfig, deployProperties,
- redisTemplate, httpClient);
+ service = new ContentModerationForwardServiceImpl(forwardMapper, secureIntegrationConfigService,
+ deployProperties, redisTemplate, forwardHttpClient);
}
@Test
- void acceptsValidHmacSignature() throws Exception {
+ void localHitDoesNotForward() {
+ // 本地命中由控制器直接结束,这里只覆盖服务侧探测顺序的起点:第一个目标即 CLAIMED。
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
+ when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
+
+ assertTrue(service.probeAndForward("trace-1", "{\"trace_id\":\"trace-1\"}", "audit"));
+
+ verify(forwardHttpClient, never()).probe(eq(PROD_TARGET), anyString(), any());
+ ModerationCallbackForwardDO row = capturedInsert();
+ assertEquals("CLAIMED", row.getStatus());
+ assertEquals("dev", row.getTargetEnv());
+ }
+
+ @Test
+ void notMineContinuesToNextTargetAndStopsOnClaimed() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
+ when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.NOT_MINE);
+ when(forwardHttpClient.probe(eq(PROD_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
+
+ assertTrue(service.probeAndForward("trace-2", "{\"trace_id\":\"trace-2\"}", "audit"));
+
+ InOrder order = inOrder(forwardHttpClient);
+ order.verify(forwardHttpClient).probe(eq(DEV_TARGET), anyString(), any());
+ order.verify(forwardHttpClient).probe(eq(PROD_TARGET), anyString(), any());
+ ModerationCallbackForwardDO row = capturedInsert();
+ assertEquals("CLAIMED", row.getStatus());
+ assertEquals("prod", row.getTargetEnv());
+ }
+
+ @Test
+ void errorContinuesToNextTargetAndRecordsAlertNote() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
+ when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.ERROR);
+ when(forwardHttpClient.probe(eq(PROD_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
+
+ assertTrue(service.probeAndForward("trace-3", "{\"trace_id\":\"trace-3\"}", "audit"));
+
+ InOrder order = inOrder(forwardHttpClient);
+ order.verify(forwardHttpClient).probe(eq(DEV_TARGET), anyString(), any());
+ order.verify(forwardHttpClient).probe(eq(PROD_TARGET), anyString(), any());
+ ModerationCallbackForwardDO row = capturedInsert();
+ assertEquals("CLAIMED", row.getStatus());
+ assertEquals("prod", row.getTargetEnv());
+ assertTrue(row.getLastError().contains("dev"));
+ }
+
+ @Test
+ void claimedStopsRemainingTargets() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
+ when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
+
+ assertTrue(service.probeAndForward("trace-4", "{\"trace_id\":\"trace-4\"}", "audit"));
+
+ verify(forwardHttpClient, never()).probe(eq(PROD_TARGET), anyString(), any());
+ }
+
+ @Test
+ void allTargetsNotMineRecordsNoEnv() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
+ when(forwardHttpClient.probe(anyString(), anyString(), any())).thenReturn(ModerationProbeResult.NOT_MINE);
+
+ assertFalse(service.probeAndForward("trace-5", "{\"trace_id\":\"trace-5\"}", "audit"));
+
+ ModerationCallbackForwardDO row = capturedInsert();
+ assertEquals("NO_ENV", row.getStatus());
+ assertTrue(row.getLastError().contains("dev"));
+ assertTrue(row.getLastError().contains("prod"));
+ assertTrue(row.getLastError().contains("NOT_MINE"));
+ }
+
+ @Test
+ void allTargetsErrorRecordsNoEnv() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
+ when(forwardHttpClient.probe(anyString(), anyString(), any())).thenReturn(ModerationProbeResult.ERROR);
+
+ assertFalse(service.probeAndForward("trace-6", "{\"trace_id\":\"trace-6\"}", "audit"));
+
+ ModerationCallbackForwardDO row = capturedInsert();
+ assertEquals("NO_ENV", row.getStatus());
+ assertTrue(row.getLastError().contains("ERROR"));
+ }
+
+ @Test
+ void disabledConfigRecordsNoEnvWithoutProbing() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(ModerationForwardConfig.disabled());
+
+ assertFalse(service.probeAndForward("trace-7", "{\"trace_id\":\"trace-7\"}", "audit"));
+
+ verify(forwardHttpClient, never()).probe(anyString(), anyString(), any());
+ ModerationCallbackForwardDO row = capturedInsert();
+ assertEquals("NO_ENV", row.getStatus());
+ }
+
+ @Test
+ void configuredTargetsExcludeLocalEnvAndKeepConfiguredOrder() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("prod", "dev")));
+ when(forwardHttpClient.probe(eq(PROD_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.NOT_MINE);
+ when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
+
+ assertTrue(service.probeAndForward("trace-8", "{\"trace_id\":\"trace-8\"}", "audit"));
+
+ InOrder order = inOrder(forwardHttpClient);
+ order.verify(forwardHttpClient).probe(eq(PROD_TARGET), anyString(), any());
+ order.verify(forwardHttpClient).probe(eq(DEV_TARGET), anyString(), any());
+ }
+
+ @Test
+ void reserveTraceReturnsFalseForDuplicate() {
+ when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false);
+
+ assertFalse(service.reserveTrace("trace-dup"));
+ }
+
+ @Test
+ void reserveTraceFailsOpenWhenRedisUnavailable() {
+ when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class)))
+ .thenThrow(new IllegalStateException("redis down"));
+
+ assertTrue(service.reserveTrace("trace-redis-down"));
+ }
+
+ @Test
+ void releaseTraceDeletesClaimKey() {
+ service.releaseTrace("trace-release");
+
+ verify(redisTemplate).delete("salon:content-moderation:claim:trace-release");
+ }
+
+ @Test
+ void existingRecordIsUpdatedInsteadOfInserted() {
+ ModerationCallbackForwardDO existing = new ModerationCallbackForwardDO();
+ existing.setId(9L);
+ existing.setTraceId("trace-existing");
+ existing.setStatus("NO_ENV");
+ existing.setCreatedAt(LocalDateTime.now().minusMinutes(1));
+ when(forwardMapper.selectOne(any())).thenReturn(existing);
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
+ when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
+
+ assertTrue(service.probeAndForward("trace-existing", "{\"trace_id\":\"trace-existing\"}", "audit"));
+
+ assertEquals("CLAIMED", existing.getStatus());
+ assertEquals("dev", existing.getTargetEnv());
+ verify(forwardMapper).updateById(existing);
+ verify(forwardMapper, never()).insert(any(ModerationCallbackForwardDO.class));
+ }
+
+ @Test
+ void verifySignatureAcceptsValidRequest() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
- String nonce = "nonce-valid";
- String body = "{\"trace_id\":\"task-1\"}";
+ String nonce = "nonce-1";
+ String body = "{\"trace_id\":\"trace-1\"}";
String signature = sign(SECRET, timestamp, nonce, body);
assertTrue(service.verifySignature(timestamp, nonce, signature, body));
}
@Test
- void rejectsInvalidHmacSignature() {
- String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
-
- assertFalse(service.verifySignature(timestamp, "nonce-bad", "deadbeef", "{\"trace_id\":\"task-1\"}"));
- }
-
- @Test
- void rejectsExpiredTimestamp() {
+ void verifySignatureRejectsExpiredTimestamp() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600);
- assertFalse(service.verifySignature(timestamp, "nonce-expired", "deadbeef", "{}"));
+ assertFalse(service.verifySignature(timestamp, "nonce-2", "bad", "{}"));
}
@Test
- void retryPendingMarksSuccessWhenTargetAccepts() {
- ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
- row.setId(11L);
- row.setTraceId("task-retry");
- row.setSourceEnv("sit");
- row.setTargetEnv("prod");
- row.setStatus("RETRY");
- row.setRetryCount(1);
- row.setUpdatedAt(LocalDateTime.now().minusMinutes(5));
- row.setPayload("{\"trace_id\":\"task-retry\"}");
- when(forwardMapper.selectList(any())).thenReturn(List.of(row));
- when(forwardMapper.selectById(11L)).thenReturn(row);
- when(httpClient.post(anyString(), anyString(), any())).thenReturn(true);
+ void verifySignatureRejectsReplayedNonce() {
+ when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
+ when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false);
+ String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
+ String body = "{}";
+ String signature = sign(SECRET, timestamp, "nonce-3", body);
- int attempted = service.retryPending();
-
- assertEquals(1, attempted);
- assertEquals("SUCCESS", row.getStatus());
- verify(forwardMapper).updateById(row);
+ assertFalse(service.verifySignature(timestamp, "nonce-3", signature, body));
}
- @Test
- void retryFailureIncrementsCountAndKeepsRetry() {
- ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
- row.setId(12L);
- row.setTraceId("task-fail");
- row.setSourceEnv("sit");
- row.setTargetEnv("prod");
- row.setStatus("RETRY");
- row.setRetryCount(0);
- row.setUpdatedAt(null);
- row.setPayload("{\"trace_id\":\"task-fail\"}");
- when(forwardMapper.selectList(any())).thenReturn(List.of(row));
- when(forwardMapper.selectById(12L)).thenReturn(row);
- when(httpClient.post(anyString(), anyString(), any())).thenThrow(new IllegalStateException("timeout"));
-
- service.retryPending();
-
- assertEquals("RETRY", row.getStatus());
- assertEquals(1, row.getRetryCount());
- assertEquals("目标环境不可达或请求失败", row.getLastError());
+ private ModerationForwardConfig config(List order) {
+ Map targets = new LinkedHashMap<>();
+ targets.put("dev", DEV_TARGET);
+ targets.put("prod", PROD_TARGET);
+ return new ModerationForwardConfig(true, targets, SECRET, order);
}
- @Test
- void targetMissingIsRecordedWithoutRetryQueue() {
- service.recordTargetMissing("task-missing", "sit", "prod", "{\"env\":\"prod\"}", "{}");
-
+ private ModerationCallbackForwardDO capturedInsert() {
ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class);
verify(forwardMapper).insert(captor.capture());
- ModerationCallbackForwardDO saved = captor.getValue();
- assertEquals("TARGET_MISSING", saved.getStatus());
- assertEquals("prod", saved.getTargetEnv());
- assertEquals(0, saved.getRetryCount());
+ return captor.getValue();
}
- @Test
- void missingExtraIsRecordedAsNoEnv() {
- service.recordUnclaimed("task-noenv", "{\"envVersion\":\"trial\"}", "{}", "回调 extra 缺少部署环境标识");
-
- ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class);
- verify(forwardMapper).insert(captor.capture());
- assertEquals("NO_ENV", captor.getValue().getStatus());
- assertEquals("sit", captor.getValue().getSourceEnv());
+ private String sign(String secret, String timestamp, String nonce, String body) {
+ try {
+ javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
+ mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
+ String canonical = timestamp + "\n" + nonce + "\n" + sha256Hex(body);
+ byte[] digest = mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8));
+ StringBuilder builder = new StringBuilder();
+ for (byte item : digest) builder.append(String.format("%02x", item));
+ return builder.toString();
+ } catch (Exception exception) {
+ throw new IllegalStateException(exception);
+ }
}
- @Test
- void requeueMovesTargetMissingToRetryForConfiguredTargets() {
- when(forwardMapper.update(any(), any())).thenReturn(2);
-
- int requeued = service.requeueConfiguredTargets();
-
- assertEquals(2, requeued);
- verify(forwardMapper).update(org.mockito.ArgumentMatchers.isNull(), any());
- }
-
- private String sign(String secret, String timestamp, String nonce, String body) throws Exception {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- StringBuilder bodyHash = new StringBuilder();
- for (byte item : digest.digest(body.getBytes(StandardCharsets.UTF_8))) bodyHash.append(String.format("%02x", item));
- String canonical = timestamp + "\n" + nonce + "\n" + bodyHash;
- javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
- mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
- StringBuilder result = new StringBuilder();
- for (byte item : mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8))) result.append(String.format("%02x", item));
- return result.toString();
+ private String sha256Hex(String value) {
+ try {
+ java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
+ byte[] bytes = digest.digest(value.getBytes(StandardCharsets.UTF_8));
+ StringBuilder builder = new StringBuilder();
+ for (byte item : bytes) builder.append(String.format("%02x", item));
+ return builder.toString();
+ } catch (Exception exception) {
+ throw new IllegalStateException(exception);
+ }
}
}