This commit is contained in:
+115
-80
@@ -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.ContentModerationForwardService;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
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.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.secure.ModerationRuntimeConfig;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
|
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
|
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.MockMvc;
|
||||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
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.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
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));
|
new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true));
|
||||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
||||||
when(crypto.verifyPlain("callback-token", "1000", "nonce", "plain-signature")).thenReturn(true);
|
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,
|
WechatContentModerationCallbackController controller = controller(secureConfig, crypto,
|
||||||
mock(ContentModerationService.class), mock(IntegrationProbeService.class),
|
mock(ContentModerationService.class), mock(IntegrationProbeService.class),
|
||||||
mock(ContentModerationForwardService.class));
|
mock(ContentModerationForwardService.class));
|
||||||
@@ -72,15 +67,16 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void localHitDoesNotForward() throws Exception {
|
void localHitDoesNotProbeAndForward() throws Exception {
|
||||||
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
||||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
||||||
ContentModerationService moderationService = mock(ContentModerationService.class);
|
ContentModerationService moderationService = mock(ContentModerationService.class);
|
||||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||||
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
|
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
|
||||||
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
|
String decoded = "{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"}}";
|
||||||
.thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"envVersion\\\":\\\"trial\\\"}\"}");
|
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")).thenReturn(decoded);
|
||||||
when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial")).thenReturn(true);
|
when(forwardService.reserveTrace("task-json")).thenReturn(true);
|
||||||
|
when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调")).thenReturn(true);
|
||||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
||||||
mock(IntegrationProbeService.class), forwardService)).build();
|
mock(IntegrationProbeService.class), forwardService)).build();
|
||||||
|
|
||||||
@@ -94,41 +90,8 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().string("success"));
|
.andExpect(content().string("success"));
|
||||||
|
|
||||||
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature");
|
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调");
|
||||||
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial");
|
verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
|
||||||
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 = "<xml><Encrypt>encrypted-xml</Encrypt></xml>";
|
|
||||||
when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
|
|
||||||
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true);
|
|
||||||
String decodedXml = "<xml><trace_id>task-xml</trace_id><suggest>review</suggest><extra>{"env":"prod","envVersion":"release"}</extra></xml>";
|
|
||||||
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");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -139,8 +102,9 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||||
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
|
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
|
||||||
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
|
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
|
||||||
.thenReturn("{\"trace_id\":\"probe-1\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"probeId\\\":\\\"probe-1\\\"}\"}");
|
.thenReturn("{\"trace_id\":\"probe-1\",\"suggest\":\"review\"}");
|
||||||
when(probeService.handleImageCallback("probe-1", "review", "probe-1")).thenReturn(true);
|
when(forwardService.reserveTrace("probe-1")).thenReturn(true);
|
||||||
|
when(probeService.handleImageCallback("probe-1", "review", null)).thenReturn(true);
|
||||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
|
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
|
||||||
mock(ContentModerationService.class), probeService, forwardService)).build();
|
mock(ContentModerationService.class), probeService, forwardService)).build();
|
||||||
|
|
||||||
@@ -154,20 +118,21 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().string("success"));
|
.andExpect(content().string("success"));
|
||||||
|
|
||||||
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
|
verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void otherEnvironmentCallbackIsEnqueuedAndReturnsSuccessImmediately() throws Exception {
|
void localMissForwardsRawDecryptedPayload() throws Exception {
|
||||||
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
||||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
||||||
ContentModerationService moderationService = mock(ContentModerationService.class);
|
ContentModerationService moderationService = mock(ContentModerationService.class);
|
||||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||||
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
||||||
when(crypto.decrypt(anyString(), anyString(), anyString()))
|
String decoded = "{\"trace_id\":\"task-prod\",\"result\":{\"suggest\":\"review\"},\"errmsg\":\"人工复核\"}";
|
||||||
.thenReturn("{\"trace_id\":\"task-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}");
|
when(crypto.decrypt(anyString(), anyString(), anyString())).thenReturn(decoded);
|
||||||
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
|
when(forwardService.reserveTrace("task-prod")).thenReturn(true);
|
||||||
when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH)));
|
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString())).thenReturn(false);
|
||||||
|
when(forwardService.probeAndForward(anyString(), anyString(), anyString())).thenReturn(true);
|
||||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
||||||
mock(IntegrationProbeService.class), forwardService)).build();
|
mock(IntegrationProbeService.class), forwardService)).build();
|
||||||
|
|
||||||
@@ -181,20 +146,20 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().string("success"));
|
.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
|
@Test
|
||||||
void missingTargetReturnsSuccessAndRecordsTargetMissing() throws Exception {
|
void duplicateTraceReturnsSuccessWithoutProcessing() throws Exception {
|
||||||
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
||||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
||||||
ContentModerationService moderationService = mock(ContentModerationService.class);
|
ContentModerationService moderationService = mock(ContentModerationService.class);
|
||||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||||
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
||||||
when(crypto.decrypt(anyString(), anyString(), anyString()))
|
when(crypto.decrypt(anyString(), anyString(), anyString()))
|
||||||
.thenReturn("{\"trace_id\":\"task-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}");
|
.thenReturn("{\"trace_id\":\"task-dup\",\"suggest\":\"review\"}");
|
||||||
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
|
when(forwardService.reserveTrace("task-dup")).thenReturn(false);
|
||||||
when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of()));
|
|
||||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
||||||
mock(IntegrationProbeService.class), forwardService)).build();
|
mock(IntegrationProbeService.class), forwardService)).build();
|
||||||
|
|
||||||
@@ -208,20 +173,25 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().string("success"));
|
.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
|
@Test
|
||||||
void extraWithoutEnvIsRecordedAsNoEnvAndNotForwarded() throws Exception {
|
void keepsXmlEnvelopeSupportForAesEncryptedCallback() throws Exception {
|
||||||
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
||||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
||||||
ContentModerationService moderationService = mock(ContentModerationService.class);
|
ContentModerationService moderationService = mock(ContentModerationService.class);
|
||||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||||
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
String xml = "<xml><Encrypt>encrypted-xml</Encrypt></xml>";
|
||||||
when(crypto.decrypt(anyString(), anyString(), anyString()))
|
when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
|
||||||
.thenReturn("{\"trace_id\":\"task-unknown\",\"suggest\":\"review\",\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}");
|
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true);
|
||||||
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
|
String decodedXml = "<xml><trace_id>task-xml</trace_id><suggest>review</suggest></xml>";
|
||||||
when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH)));
|
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,
|
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
||||||
mock(IntegrationProbeService.class), forwardService)).build();
|
mock(IntegrationProbeService.class), forwardService)).build();
|
||||||
|
|
||||||
@@ -230,35 +200,104 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
.param("nonce", "nonce")
|
.param("nonce", "nonce")
|
||||||
.param("msg_signature", "message-signature")
|
.param("msg_signature", "message-signature")
|
||||||
.param("encrypt_type", "aes")
|
.param("encrypt_type", "aes")
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_XML)
|
||||||
.content("{\"Encrypt\":\"encrypted-json\"}"))
|
.content(xml))
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().string("success"));
|
.andExpect(content().string("success"));
|
||||||
|
|
||||||
verify(forwardService).recordUnclaimed(eq("task-unknown"), anyString(), anyString(), anyString());
|
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调");
|
||||||
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void secondHopOrSelfForwardIsDroppedAndRecorded() throws Exception {
|
void forwardedCallbackClaimsLocally() throws Exception {
|
||||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||||
|
ContentModerationService moderationService = mock(ContentModerationService.class);
|
||||||
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
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),
|
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")
|
mvc.perform(post("/integration/wechat/content-moderation/callback")
|
||||||
.header("X-Moderation-Forward-By", "sit")
|
.header("X-Moderation-Forward-By", "prod")
|
||||||
.header("X-Moderation-Forward-Hop", "2")
|
.header("X-Moderation-Forward-Hop", "1")
|
||||||
.header("X-Timestamp", "1000")
|
.header("X-Timestamp", "1000")
|
||||||
.header("X-Nonce", "forward-nonce")
|
.header("X-Nonce", "forward-nonce")
|
||||||
.header("X-Signature", "forward-signature")
|
.header("X-Signature", "forward-signature")
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.content("{\"trace_id\":\"loop-task\",\"suggest\":\"review\"}"))
|
.content("{\"trace_id\":\"task-claim\",\"suggest\":\"review\"}"))
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(content().string("success"));
|
.andExpect(content().string("CLAIMED"));
|
||||||
|
}
|
||||||
|
|
||||||
verify(forwardService).recordUnclaimed(eq("loop-task"), any(), anyString(), anyString());
|
@Test
|
||||||
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
|
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
|
@Test
|
||||||
@@ -274,10 +313,6 @@ class WechatContentModerationCallbackControllerTest {
|
|||||||
"{\"trace_id\":\"task-1\"}"));
|
"{\"trace_id\":\"task-1\"}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private ModerationForwardConfig forwardConfig(Map<String, String> targets) {
|
|
||||||
return new ModerationForwardConfig(true, targets, "forward-secret-key-01");
|
|
||||||
}
|
|
||||||
|
|
||||||
private SecureIntegrationConfigService readyWechatConfig() {
|
private SecureIntegrationConfigService readyWechatConfig() {
|
||||||
SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class);
|
SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class);
|
||||||
when(secureConfig.getModerationCallbackConfig()).thenReturn(
|
when(secureConfig.getModerationCallbackConfig()).thenReturn(
|
||||||
|
|||||||
+207
-99
@@ -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.config.SalonDeployProperties;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient;
|
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.entity.ModerationCallbackForwardDO;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper;
|
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
|
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.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InOrder;
|
||||||
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.data.redis.core.RedisTemplate;
|
||||||
import org.springframework.data.redis.core.ValueOperations;
|
import org.springframework.data.redis.core.ValueOperations;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.security.MessageDigest;
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
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.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
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.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
class ContentModerationForwardServiceImplTest {
|
class ContentModerationForwardServiceImplTest {
|
||||||
private static final String SECRET = "forward-secret-key-01";
|
private static final String SECRET = "forward-secret-1234567890";
|
||||||
private static final String TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback";
|
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 ModerationCallbackForwardMapper forwardMapper;
|
||||||
private SecureIntegrationConfigService secureConfig;
|
private SecureIntegrationConfigService secureIntegrationConfigService;
|
||||||
private ModerationForwardHttpClient httpClient;
|
|
||||||
private RedisTemplate<String, Object> redisTemplate;
|
private RedisTemplate<String, Object> redisTemplate;
|
||||||
private ValueOperations<String, Object> valueOperations;
|
private ValueOperations<String, Object> valueOperations;
|
||||||
|
private ModerationForwardHttpClient forwardHttpClient;
|
||||||
private ContentModerationForwardServiceImpl service;
|
private ContentModerationForwardServiceImpl service;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
void setUp() {
|
void setUp() {
|
||||||
forwardMapper = mock(ModerationCallbackForwardMapper.class);
|
forwardMapper = mock(ModerationCallbackForwardMapper.class);
|
||||||
secureConfig = mock(SecureIntegrationConfigService.class);
|
secureIntegrationConfigService = mock(SecureIntegrationConfigService.class);
|
||||||
httpClient = mock(ModerationForwardHttpClient.class);
|
|
||||||
redisTemplate = mock(RedisTemplate.class);
|
redisTemplate = mock(RedisTemplate.class);
|
||||||
valueOperations = mock(ValueOperations.class);
|
valueOperations = mock(ValueOperations.class);
|
||||||
|
forwardHttpClient = mock(ModerationForwardHttpClient.class);
|
||||||
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
|
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
|
||||||
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(true);
|
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();
|
SalonDeployProperties deployProperties = new SalonDeployProperties();
|
||||||
deployProperties.setEnv("sit");
|
deployProperties.setEnv("sit");
|
||||||
service = new ContentModerationForwardServiceImpl(forwardMapper, secureConfig, deployProperties,
|
service = new ContentModerationForwardServiceImpl(forwardMapper, secureIntegrationConfigService,
|
||||||
redisTemplate, httpClient);
|
deployProperties, redisTemplate, forwardHttpClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@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 timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||||
String nonce = "nonce-valid";
|
String nonce = "nonce-1";
|
||||||
String body = "{\"trace_id\":\"task-1\"}";
|
String body = "{\"trace_id\":\"trace-1\"}";
|
||||||
String signature = sign(SECRET, timestamp, nonce, body);
|
String signature = sign(SECRET, timestamp, nonce, body);
|
||||||
|
|
||||||
assertTrue(service.verifySignature(timestamp, nonce, signature, body));
|
assertTrue(service.verifySignature(timestamp, nonce, signature, body));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void rejectsInvalidHmacSignature() {
|
void verifySignatureRejectsExpiredTimestamp() {
|
||||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
|
||||||
|
|
||||||
assertFalse(service.verifySignature(timestamp, "nonce-bad", "deadbeef", "{\"trace_id\":\"task-1\"}"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void rejectsExpiredTimestamp() {
|
|
||||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600);
|
String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600);
|
||||||
|
|
||||||
assertFalse(service.verifySignature(timestamp, "nonce-expired", "deadbeef", "{}"));
|
assertFalse(service.verifySignature(timestamp, "nonce-2", "bad", "{}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void retryPendingMarksSuccessWhenTargetAccepts() {
|
void verifySignatureRejectsReplayedNonce() {
|
||||||
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
|
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
|
||||||
row.setId(11L);
|
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false);
|
||||||
row.setTraceId("task-retry");
|
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||||
row.setSourceEnv("sit");
|
String body = "{}";
|
||||||
row.setTargetEnv("prod");
|
String signature = sign(SECRET, timestamp, "nonce-3", body);
|
||||||
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);
|
|
||||||
|
|
||||||
int attempted = service.retryPending();
|
assertFalse(service.verifySignature(timestamp, "nonce-3", signature, body));
|
||||||
|
|
||||||
assertEquals(1, attempted);
|
|
||||||
assertEquals("SUCCESS", row.getStatus());
|
|
||||||
verify(forwardMapper).updateById(row);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
private ModerationForwardConfig config(List<String> order) {
|
||||||
void retryFailureIncrementsCountAndKeepsRetry() {
|
Map<String, String> targets = new LinkedHashMap<>();
|
||||||
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
|
targets.put("dev", DEV_TARGET);
|
||||||
row.setId(12L);
|
targets.put("prod", PROD_TARGET);
|
||||||
row.setTraceId("task-fail");
|
return new ModerationForwardConfig(true, targets, SECRET, order);
|
||||||
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());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
private ModerationCallbackForwardDO capturedInsert() {
|
||||||
void targetMissingIsRecordedWithoutRetryQueue() {
|
|
||||||
service.recordTargetMissing("task-missing", "sit", "prod", "{\"env\":\"prod\"}", "{}");
|
|
||||||
|
|
||||||
ArgumentCaptor<ModerationCallbackForwardDO> captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class);
|
ArgumentCaptor<ModerationCallbackForwardDO> captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class);
|
||||||
verify(forwardMapper).insert(captor.capture());
|
verify(forwardMapper).insert(captor.capture());
|
||||||
ModerationCallbackForwardDO saved = captor.getValue();
|
return captor.getValue();
|
||||||
assertEquals("TARGET_MISSING", saved.getStatus());
|
|
||||||
assertEquals("prod", saved.getTargetEnv());
|
|
||||||
assertEquals(0, saved.getRetryCount());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
private String sign(String secret, String timestamp, String nonce, String body) {
|
||||||
void missingExtraIsRecordedAsNoEnv() {
|
try {
|
||||||
service.recordUnclaimed("task-noenv", "{\"envVersion\":\"trial\"}", "{}", "回调 extra 缺少部署环境标识");
|
|
||||||
|
|
||||||
ArgumentCaptor<ModerationCallbackForwardDO> captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class);
|
|
||||||
verify(forwardMapper).insert(captor.capture());
|
|
||||||
assertEquals("NO_ENV", captor.getValue().getStatus());
|
|
||||||
assertEquals("sit", captor.getValue().getSourceEnv());
|
|
||||||
}
|
|
||||||
|
|
||||||
@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");
|
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||||
mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||||
StringBuilder result = new StringBuilder();
|
String canonical = timestamp + "\n" + nonce + "\n" + sha256Hex(body);
|
||||||
for (byte item : mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8))) result.append(String.format("%02x", item));
|
byte[] digest = mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8));
|
||||||
return result.toString();
|
StringBuilder builder = new StringBuilder();
|
||||||
|
for (byte item : digest) builder.append(String.format("%02x", item));
|
||||||
|
return builder.toString();
|
||||||
|
} catch (Exception exception) {
|
||||||
|
throw new IllegalStateException(exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user