feat: 微信审核回调支持跨环境转发与补偿重试

This commit is contained in:
2026-11-04 23:24:05 +08:00
parent 99fa38f110
commit 90b07bf33e
25 changed files with 1479 additions and 49 deletions
@@ -0,0 +1,24 @@
package com.xiaowang.jayucloud.salon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
/**
* 部署环境标识。
* 用于微信内容审核回调的跨环境路由,必须由各环境 Nacos 显式配置,缺失时启动失败。
*/
@Data
@Component
@Validated
@ConfigurationProperties(prefix = "jayucloud-salon.deploy")
public class SalonDeployProperties {
@NotBlank
@Pattern(regexp = "dev|sit|prod", message = "部署环境标识必须是 dev、sit 或 prod")
private String env;
}
@@ -2,30 +2,46 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; 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.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;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.Locale;
@Slf4j
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/integration/wechat/content-moderation") @RequestMapping("/integration/wechat/content-moderation")
public class WechatContentModerationCallbackController { public class WechatContentModerationCallbackController {
private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By";
private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop";
private final SecureIntegrationConfigService secureIntegrationConfigService; private final SecureIntegrationConfigService secureIntegrationConfigService;
private final WechatMiniProperties wechatProperties; private final WechatMiniProperties wechatProperties;
private final WechatCallbackCrypto crypto; private final WechatCallbackCrypto crypto;
private final ContentModerationService contentModerationService; private final ContentModerationService contentModerationService;
private final IntegrationProbeService integrationProbeService; private final IntegrationProbeService integrationProbeService;
private final ContentModerationForwardService contentModerationForwardService;
private final SalonDeployProperties deployProperties;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
@GetMapping("/callback") @GetMapping("/callback")
@@ -54,12 +70,23 @@ public class WechatContentModerationCallbackController {
MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_XML_VALUE,
MediaType.TEXT_XML_VALUE MediaType.TEXT_XML_VALUE
}) })
public String callback(@RequestParam("timestamp") String timestamp, public String callback(@RequestParam(value = "timestamp", required = false) String timestamp,
@RequestParam("nonce") String nonce, @RequestParam(value = "nonce", required = false) String nonce,
@RequestParam(value = "msg_signature", required = false) String messageSignature, @RequestParam(value = "msg_signature", required = false) String messageSignature,
@RequestParam(value = "signature", required = false) String signature, @RequestParam(value = "signature", required = false) String signature,
@RequestParam(value = "encrypt_type", required = false) String encryptType, @RequestParam(value = "encrypt_type", required = false) String encryptType,
@org.springframework.web.bind.annotation.RequestBody String body) throws Exception { @RequestHeader(value = "X-Moderation-Forward-By", required = false) String forwardBy,
@RequestHeader(value = "X-Moderation-Forward-Hop", required = false) String forwardHop,
@RequestHeader(value = "X-Timestamp", required = false) String forwardTimestamp,
@RequestHeader(value = "X-Nonce", required = false) String forwardNonce,
@RequestHeader(value = "X-Signature", required = false) String forwardSignature,
@RequestBody String body) throws Exception {
if (StringUtils.hasText(forwardBy) || StringUtils.hasText(forwardHop)) {
return handleForwardedCallback(forwardBy, forwardHop, forwardTimestamp, forwardNonce, forwardSignature, body);
}
if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce)) {
throw new IllegalArgumentException("微信审核回调缺少时间戳或随机串");
}
ModerationRuntimeConfig config = requireWechatConfig(); ModerationRuntimeConfig config = requireWechatConfig();
String encrypted = extractEncryptedPayload(body); String encrypted = extractEncryptedPayload(body);
String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature; String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature;
@@ -90,12 +117,119 @@ public class WechatContentModerationCallbackController {
extra = firstText(root, "extra", "Extra"); extra = firstText(root, "extra", "Extra");
} }
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识"); if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识");
if (!integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) { if (claimLocally(taskId, suggest, reason, extra)) {
contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra)); return "success";
}
String taskEnv = normalizeEnv(decodeTaskEnv(extra));
String localEnv = deployProperties.getEnv();
String forwardPayload = buildForwardPayload(taskId, suggest, reason, extra);
if (!StringUtils.hasText(taskEnv)) {
contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "回调 extra 缺少部署环境标识");
log.warn("微信审核回调无法认领:extra 缺少环境标识,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
taskId, localEnv, null);
return "success";
}
if (taskEnv.equals(localEnv)) {
contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "本环境未匹配到审核任务");
log.warn("微信审核回调无法认领:本环境未匹配任务,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
taskId, localEnv, taskEnv);
return "success";
}
ModerationForwardConfig forwardConfig = contentModerationForwardService.runtimeConfig();
if (!StringUtils.hasText(forwardConfig.targetFor(taskEnv))) {
contentModerationForwardService.recordTargetMissing(taskId, localEnv, taskEnv, extra, forwardPayload);
log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
taskId, localEnv, taskEnv);
return "success";
}
contentModerationForwardService.enqueue(taskId, localEnv, taskEnv, extra, forwardPayload);
return "success";
}
/**
* 处理转发进来的回调:只允许一跳,验签通过后仅在本地处理,不再二次转发。
*/
private String handleForwardedCallback(String forwardBy, String forwardHop, String timestamp,
String nonce, String signature, String body) {
if (!contentModerationForwardService.verifySignature(timestamp, nonce, signature, body)) {
throw new IllegalArgumentException("跨环境转发签名校验失败");
}
String taskId;
String suggest;
String reason;
String extra;
try {
JsonNode root = objectMapper.readTree(body == null ? "" : body);
taskId = firstText(root, "trace_id", "traceId", "task_id");
suggest = firstText(root, "suggest", "Suggest");
if (!StringUtils.hasText(suggest)) suggest = "review";
reason = firstText(root, "reason", "errmsg");
if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调";
extra = firstText(root, "extra", "Extra");
} catch (Exception exception) {
throw new IllegalArgumentException("跨环境转发报文无法解析");
}
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("跨环境转发报文缺少任务标识");
String hopText = forwardHop == null ? "1" : forwardHop.trim();
int hop;
try {
hop = Integer.parseInt(hopText);
} catch (NumberFormatException exception) {
hop = 2;
}
String localEnv = deployProperties.getEnv();
String sourceEnv = normalizeEnv(forwardBy);
if (hop > 1 || (StringUtils.hasText(sourceEnv) && sourceEnv.equals(localEnv))) {
contentModerationForwardService.recordUnclaimed(taskId, extra, body,
"检测到转发环路或超过一跳,已丢弃");
log.warn("微信审核回调转发被丢弃:环路或超过一跳,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
taskId, sourceEnv, localEnv, hop);
return "success";
}
log.info("收到跨环境转发的微信审核回调,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
taskId, sourceEnv, localEnv, hop);
if (!claimLocally(taskId, suggest, reason, extra)) {
contentModerationForwardService.recordUnclaimed(taskId, extra, body, "转发目标环境仍未匹配到审核任务");
log.warn("跨环境转发的微信审核回调未匹配到本地任务,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
taskId, sourceEnv, localEnv, hop);
} }
return "success"; return "success";
} }
private boolean claimLocally(String taskId, String suggest, String reason, String extra) {
if (integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) {
return true;
}
return contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra));
}
private String buildForwardPayload(String taskId, String suggest, String reason, String extra) {
ObjectNode payload = objectMapper.createObjectNode();
payload.put("trace_id", taskId);
payload.put("suggest", suggest);
payload.put("reason", reason);
if (StringUtils.hasText(extra)) payload.put("extra", extra);
return payload.toString();
}
private String decodeTaskEnv(String extra) {
if (!StringUtils.hasText(extra)) return null;
try {
JsonNode payload = objectMapper.readTree(extra);
return firstText(payload, "env");
} catch (Exception ignored) {
return null;
}
}
private String normalizeEnv(String value) {
if (!StringUtils.hasText(value)) return null;
String normalized = value.trim().toLowerCase(Locale.ROOT);
return Arrays.asList("dev", "sit", "prod").contains(normalized) ? normalized : null;
}
private String decodeSourceEnvVersion(String extra) { private String decodeSourceEnvVersion(String extra) {
if (!StringUtils.hasText(extra)) return null; if (!StringUtils.hasText(extra)) return null;
try { try {
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
@@ -26,16 +27,19 @@ public class WechatContentModerationProvider implements ContentModerationProvide
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final WechatMiniClientService wechatMiniClientService; private final WechatMiniClientService wechatMiniClientService;
private final ContentModerationProperties properties; private final ContentModerationProperties properties;
private final SalonDeployProperties deployProperties;
public WechatContentModerationProvider( public WechatContentModerationProvider(
@Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate, @Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate,
ObjectMapper objectMapper, ObjectMapper objectMapper,
WechatMiniClientService wechatMiniClientService, WechatMiniClientService wechatMiniClientService,
ContentModerationProperties properties) { ContentModerationProperties properties,
SalonDeployProperties deployProperties) {
this.restTemplate = restTemplate; this.restTemplate = restTemplate;
this.objectMapper = objectMapper; this.objectMapper = objectMapper;
this.wechatMiniClientService = wechatMiniClientService; this.wechatMiniClientService = wechatMiniClientService;
this.properties = properties; this.properties = properties;
this.deployProperties = deployProperties;
} }
@Override @Override
@@ -67,6 +71,7 @@ public class WechatContentModerationProvider implements ContentModerationProvide
public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) { public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) {
Map<String, String> extra = new LinkedHashMap<>(); Map<String, String> extra = new LinkedHashMap<>();
extra.put("env", deployProperties.getEnv());
extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion)); extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion));
extra.put("probeId", probeId); extra.put("probeId", probeId);
try { try {
@@ -103,8 +108,11 @@ public class WechatContentModerationProvider implements ContentModerationProvide
if (!"develop".equals(envVersion) && !"trial".equals(envVersion) && !"release".equals(envVersion)) { if (!"develop".equals(envVersion) && !"trial".equals(envVersion) && !"release".equals(envVersion)) {
envVersion = "UNKNOWN"; envVersion = "UNKNOWN";
} }
Map<String, String> extra = new LinkedHashMap<>();
extra.put("env", deployProperties.getEnv());
extra.put("envVersion", envVersion);
try { try {
return objectMapper.writeValueAsString(Map.of("envVersion", envVersion)); return objectMapper.writeValueAsString(extra);
} catch (java.io.IOException exception) { } catch (java.io.IOException exception) {
throw new IllegalStateException("无法编码微信审核来源版本", exception); throw new IllegalStateException("无法编码微信审核来源版本", exception);
} }
@@ -0,0 +1,46 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO;
import java.util.List;
/**
* 微信异步图片审核回调的跨环境转发。
*/
public interface ContentModerationForwardService {
ModerationForwardConfig runtimeConfig();
List<ModerationForwardRecordVO> listRecent(int limit);
/**
* 记录无法认领的回调(extra 缺失或指向本环境但本地没有任务),不自动重试。
*/
void recordUnclaimed(String traceId, String extraJson, String payload, String note);
/**
* 记录目标环境未配置的回调,不自动重试,配置补齐后可由补偿任务重放。
*/
void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload);
/**
* 落库为 PENDING 并异步转发,确保微信回调在 5 秒内拿到 success。
*/
void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload);
/**
* 重放到期的 RETRY 记录,最多 5 次,指数退避。
*/
int retryPending();
/**
* 转发配置补齐后,把对应目标环境下的 TARGET_MISSING 记录重新排队。
*/
int requeueConfiguredTargets();
/**
* 校验转发请求的 HMAC 签名、时间窗与 nonce 防重放。
*/
boolean verifySignature(String timestamp, String nonce, String signature, String body);
}
@@ -0,0 +1,341 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient;
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;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@Service
@RequiredArgsConstructor
public class ContentModerationForwardServiceImpl implements ContentModerationForwardService {
private static final String STATUS_PENDING = "PENDING";
private static final String STATUS_SUCCESS = "SUCCESS";
private static final String STATUS_RETRY = "RETRY";
private static final String STATUS_FAILED = "FAILED";
private static final String STATUS_NO_ENV = "NO_ENV";
private static final String STATUS_TARGET_MISSING = "TARGET_MISSING";
private static final int MAX_RETRY = 5;
private static final long SIGNATURE_WINDOW_SECONDS = 300;
private static final long NONCE_TTL_SECONDS = 600;
private static final String NONCE_KEY_PREFIX = "salon:content-moderation:forward:nonce:";
private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By";
private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop";
private static final AtomicInteger THREAD_INDEX = new AtomicInteger(1);
private static final ExecutorService FORWARD_EXECUTOR = Executors.newFixedThreadPool(2, new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "moderation-forward-" + THREAD_INDEX.getAndIncrement());
thread.setDaemon(true);
return thread;
}
});
private final ModerationCallbackForwardMapper forwardMapper;
private final SecureIntegrationConfigService secureIntegrationConfigService;
private final SalonDeployProperties deployProperties;
private final RedisTemplate<String, Object> redisTemplate;
private final ModerationForwardHttpClient forwardHttpClient;
@Override
public ModerationForwardConfig runtimeConfig() {
return secureIntegrationConfigService.getModerationForwardConfig();
}
@Override
public List<ModerationForwardRecordVO> listRecent(int limit) {
int size = limit <= 0 ? 10 : Math.min(limit, 50);
List<ModerationCallbackForwardDO> rows = forwardMapper.selectList(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
.orderByDesc(ModerationCallbackForwardDO::getCreatedAt)
.last("LIMIT " + size));
return rows.stream().map(this::toVO).toList();
}
@Override
public void recordUnclaimed(String traceId, String extraJson, String payload, String note) {
if (!StringUtils.hasText(traceId)) {
log.warn("微信审核回调无法认领且缺少任务标识,note={}", note);
return;
}
log.warn("微信审核回调无法认领,traceId={}, sourceEnv={}, targetEnv={}, hop=0, note={}",
traceId, deployProperties.getEnv(), null, note);
ModerationCallbackForwardDO row = build(traceId, deployProperties.getEnv(), null, extraJson, payload, STATUS_NO_ENV, note);
saveQuietly(row);
}
@Override
public void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) {
log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
traceId, sourceEnv, targetEnv);
ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload,
STATUS_TARGET_MISSING, "目标环境未配置转发地址");
saveQuietly(row);
}
@Override
public void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) {
ModerationCallbackForwardDO existing = findByTrace(traceId);
if (existing != null) {
log.info("微信审核回调转发已存在记录,traceId={}, sourceEnv={}, targetEnv={}, status={}",
traceId, sourceEnv, targetEnv, existing.getStatus());
return;
}
ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload, STATUS_PENDING, null);
if (!saveQuietly(row)) return;
log.info("微信审核回调进入跨环境转发,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
traceId, sourceEnv, targetEnv);
FORWARD_EXECUTOR.execute(() -> dispatchById(row.getId()));
}
@Override
@Scheduled(fixedDelay = 60000)
public int retryPending() {
List<ModerationCallbackForwardDO> rows = forwardMapper.selectList(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
.eq(ModerationCallbackForwardDO::getStatus, STATUS_RETRY)
.lt(ModerationCallbackForwardDO::getRetryCount, MAX_RETRY)
.orderByAsc(ModerationCallbackForwardDO::getId)
.last("LIMIT 50"));
LocalDateTime now = LocalDateTime.now();
int attempted = 0;
for (ModerationCallbackForwardDO row : rows) {
if (!backoffElapsed(row, now)) continue;
attempted++;
dispatchById(row.getId());
}
return attempted;
}
@Override
public int requeueConfiguredTargets() {
ModerationForwardConfig config = runtimeConfig();
if (!config.ready() || config.getTargets() == null || config.getTargets().isEmpty()) return 0;
List<String> configuredEnvs = config.getTargets().entrySet().stream()
.filter(entry -> StringUtils.hasText(entry.getValue()))
.map(Map.Entry::getKey)
.toList();
if (configuredEnvs.isEmpty()) return 0;
return forwardMapper.update(null, new UpdateWrapper<ModerationCallbackForwardDO>()
.eq("status", STATUS_TARGET_MISSING)
.in("target_env", configuredEnvs)
.set("status", STATUS_RETRY)
.set("retry_count", 0)
.set("last_error", null)
.set("updated_at", LocalDateTime.now()));
}
@Override
public boolean verifySignature(String timestamp, String nonce, String signature, String body) {
if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false;
ModerationForwardConfig config = runtimeConfig();
if (!config.ready()) return false;
long epochSeconds;
try {
epochSeconds = Long.parseLong(timestamp.trim());
} catch (NumberFormatException exception) {
return false;
}
if (Math.abs(System.currentTimeMillis() / 1000 - epochSeconds) > SIGNATURE_WINDOW_SECONDS) return false;
if (!reserveNonce(nonce.trim())) return false;
String expected = sign(config.getSecret(), timestamp.trim(), nonce.trim(), body == null ? "" : body);
return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
signature.trim().toLowerCase(java.util.Locale.ROOT).getBytes(StandardCharsets.UTF_8));
}
private void dispatchById(Long id) {
ModerationCallbackForwardDO row = forwardMapper.selectById(id);
if (row == null || STATUS_SUCCESS.equals(row.getStatus())) return;
ModerationForwardConfig config = runtimeConfig();
if (!config.ready()) {
markFailed(row, "跨环境转发未启用或共享密钥缺失", false);
return;
}
String target = config.targetFor(row.getTargetEnv());
if (!StringUtils.hasText(target)) {
row.setStatus(STATUS_TARGET_MISSING);
row.setLastError("目标环境未配置转发地址");
row.setUpdatedAt(LocalDateTime.now());
forwardMapper.updateById(row);
log.warn("微信审核回调转发目标缺失,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
return;
}
try {
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonce = UUID.randomUUID().toString().replace("-", "");
String signature = sign(config.getSecret(), timestamp, nonce, row.getPayload() == null ? "" : row.getPayload());
Map<String, String> headers = new java.util.HashMap<>();
headers.put(FORWARD_BY_HEADER, deployProperties.getEnv());
headers.put(FORWARD_HOP_HEADER, "1");
headers.put("X-Timestamp", timestamp);
headers.put("X-Nonce", nonce);
headers.put("X-Signature", signature);
boolean accepted = forwardHttpClient.post(target, row.getPayload(), headers);
if (accepted) {
row.setStatus(STATUS_SUCCESS);
row.setLastError(null);
row.setUpdatedAt(LocalDateTime.now());
forwardMapper.updateById(row);
log.info("微信审核回调跨环境转发成功,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
} else {
markRetry(row, "目标环境返回异常状态");
}
} catch (RuntimeException exception) {
markRetry(row, "目标环境不可达或请求失败");
}
}
private void markRetry(ModerationCallbackForwardDO row, String error) {
int retries = (row.getRetryCount() == null ? 0 : row.getRetryCount()) + 1;
row.setRetryCount(retries);
row.setLastError(clip(error, 500));
row.setStatus(retries >= MAX_RETRY ? STATUS_FAILED : STATUS_RETRY);
row.setUpdatedAt(LocalDateTime.now());
forwardMapper.updateById(row);
log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, retryCount={}, status={}",
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv(), retries, row.getStatus());
}
private void markFailed(ModerationCallbackForwardDO row, String error, boolean retry) {
if (retry) {
markRetry(row, error);
return;
}
row.setStatus(STATUS_FAILED);
row.setLastError(clip(error, 500));
row.setUpdatedAt(LocalDateTime.now());
forwardMapper.updateById(row);
log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, status=FAILED",
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
}
private boolean backoffElapsed(ModerationCallbackForwardDO row, LocalDateTime now) {
if (row.getUpdatedAt() == null) return true;
long minutes = 1L << Math.min(Math.max(row.getRetryCount() == null ? 0 : row.getRetryCount(), 0), 5);
return !row.getUpdatedAt().plusMinutes(minutes).isAfter(now);
}
private boolean reserveNonce(String nonce) {
try {
Boolean fresh = redisTemplate.opsForValue().setIfAbsent(NONCE_KEY_PREFIX + nonce, "1",
Duration.ofSeconds(NONCE_TTL_SECONDS));
return Boolean.TRUE.equals(fresh);
} catch (RuntimeException exception) {
log.warn("转发 nonce 防重放写入失败,按拒绝处理");
return false;
}
}
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);
return hex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));
} catch (java.security.GeneralSecurityException exception) {
throw new IllegalStateException("转发签名计算失败", exception);
}
}
private String sha256Hex(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return hex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (java.security.NoSuchAlgorithmException exception) {
throw new IllegalStateException("无法计算报文摘要", exception);
}
}
private String hex(byte[] bytes) {
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte item : bytes) builder.append(String.format("%02x", item));
return builder.toString();
}
private ModerationCallbackForwardDO build(String traceId, String sourceEnv, String targetEnv,
String extraJson, String payload, String status, String error) {
LocalDateTime now = LocalDateTime.now();
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
row.setTraceId(clip(traceId, 128));
row.setSourceEnv(clip(sourceEnv, 16));
row.setTargetEnv(StringUtils.hasText(targetEnv) ? clip(targetEnv, 16) : null);
row.setExtraJson(clip(extraJson, 256));
row.setPayload(payload);
row.setStatus(status);
row.setRetryCount(0);
row.setLastError(clip(error, 500));
row.setCreatedAt(now);
row.setUpdatedAt(now);
return row;
}
private boolean saveQuietly(ModerationCallbackForwardDO row) {
try {
forwardMapper.insert(row);
return true;
} catch (DuplicateKeyException exception) {
log.info("微信审核回调转发记录已存在,traceId={}", row.getTraceId());
return false;
}
}
private ModerationCallbackForwardDO findByTrace(String traceId) {
if (!StringUtils.hasText(traceId)) return null;
return forwardMapper.selectOne(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
.eq(ModerationCallbackForwardDO::getTraceId, traceId)
.last("LIMIT 1"));
}
private ModerationForwardRecordVO toVO(ModerationCallbackForwardDO row) {
ModerationForwardRecordVO vo = new ModerationForwardRecordVO();
vo.setId(row.getId());
vo.setTraceId(row.getTraceId());
vo.setSourceEnv(row.getSourceEnv());
vo.setTargetEnv(row.getTargetEnv());
vo.setStatus(row.getStatus());
vo.setRetryCount(row.getRetryCount());
vo.setLastError(row.getLastError());
vo.setCreatedAt(row.getCreatedAt());
vo.setUpdatedAt(row.getUpdatedAt());
return vo;
}
private String clip(String value, int max) {
if (!StringUtils.hasText(value)) return null;
String trimmed = value.trim();
return trimmed.length() <= max ? trimmed : trimmed.substring(0, max);
}
@PreDestroy
public void shutdown() {
FORWARD_EXECUTOR.shutdownNow();
}
}
@@ -0,0 +1,35 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.support;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
* 跨环境审核回调转发客户端,固定 3 秒超时,失败以异常抛出由上层登记重试。
*/
@Component
public class ModerationForwardHttpClient {
private final RestTemplate restTemplate;
public ModerationForwardHttpClient() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(3000);
factory.setReadTimeout(3000);
this.restTemplate = new RestTemplate(factory);
}
public boolean post(String url, String body, Map<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
headers.forEach(httpHeaders::set);
ResponseEntity<String> response = restTemplate.postForEntity(url, new HttpEntity<>(body, httpHeaders), String.class);
return response.getStatusCode().is2xxSuccessful();
}
}
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
@@ -31,6 +32,7 @@ import java.util.List;
public class AdminSecureIntegrationConfigController { public class AdminSecureIntegrationConfigController {
private final SecureIntegrationConfigService secureIntegrationConfigService; private final SecureIntegrationConfigService secureIntegrationConfigService;
private final IntegrationProbeService integrationProbeService; private final IntegrationProbeService integrationProbeService;
private final ContentModerationForwardService contentModerationForwardService;
private final AdminScopeHelper adminScopeHelper; private final AdminScopeHelper adminScopeHelper;
private final SecurityAuditSupport securityAuditSupport; private final SecurityAuditSupport securityAuditSupport;
@@ -40,6 +42,7 @@ public class AdminSecureIntegrationConfigController {
UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserDO currentUser = adminScopeHelper.getCurrentUser(request);
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
config.setProbeResults(integrationProbeService.listLatest(currentUser)); config.setProbeResults(integrationProbeService.listLatest(currentUser));
config.setModerationForwardRecent(contentModerationForwardService.listRecent(10));
return Result.success(config); return Result.success(config);
} }
@@ -82,6 +85,31 @@ public class AdminSecureIntegrationConfigController {
} }
} }
@PostMapping("/content-moderation-forward")
@RequirePermission("messagehub:config:manage")
@OperationGuard(action = "secure-moderation-forward-config-save", ttlSeconds = 5, message = "跨环境转发设置正在保存,请勿重复提交")
public Result<SecureIntegrationConfigVO> saveModerationForwardConfig(HttpServletRequest request,
@Valid @RequestBody SecureIntegrationConfigDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
try {
secureIntegrationConfigService.saveModerationForwardConfig(currentUser, dto);
int requeued = contentModerationForwardService.requeueConfiguredTargets();
if (requeued > 0) {
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
"section=CONTENT_MODERATION_FORWARD,requeued=" + requeued);
} else {
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
"section=CONTENT_MODERATION_FORWARD");
}
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
config.setModerationForwardRecent(contentModerationForwardService.listRecent(10));
return Result.success(config);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION_FORWARD");
throw exception;
}
}
@GetMapping("/probe-results") @GetMapping("/probe-results")
@RequirePermission("messagehub:config:manage") @RequirePermission("messagehub:config:manage")
public Result<List<IntegrationProbeResultVO>> listProbeResults(HttpServletRequest request) { public Result<List<IntegrationProbeResultVO>> listProbeResults(HttpServletRequest request) {
@@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.system.dto;
import lombok.Data; import lombok.Data;
import java.util.Map;
@Data @Data
public class SecureIntegrationConfigDTO { public class SecureIntegrationConfigDTO {
private String mapProvider; private String mapProvider;
@@ -19,4 +21,9 @@ public class SecureIntegrationConfigDTO {
private String moderationEncodingAesKey; private String moderationEncodingAesKey;
private Boolean clearModerationCallbackToken; private Boolean clearModerationCallbackToken;
private Boolean clearModerationEncodingAesKey; private Boolean clearModerationEncodingAesKey;
private Boolean moderationForwardEnabled;
private Map<String, String> moderationForwardTargets;
private String moderationForwardSecret;
private Boolean clearModerationForwardSecret;
} }
@@ -0,0 +1,46 @@
package com.xiaowang.jayucloud.salon.core.modules.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("t_moderation_callback_forward")
public class ModerationCallbackForwardDO {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@TableField("trace_id")
private String traceId;
@TableField("source_env")
private String sourceEnv;
@TableField("target_env")
private String targetEnv;
@TableField("extra_json")
private String extraJson;
@TableField("payload")
private String payload;
@TableField("status")
private String status;
@TableField("retry_count")
private Integer retryCount;
@TableField("last_error")
private String lastError;
@TableField("created_at")
private LocalDateTime createdAt;
@TableField("updated_at")
private LocalDateTime updatedAt;
}
@@ -0,0 +1,9 @@
package com.xiaowang.jayucloud.salon.core.modules.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ModerationCallbackForwardMapper extends BaseMapper<ModerationCallbackForwardDO> {
}
@@ -0,0 +1,30 @@
package com.xiaowang.jayucloud.salon.core.modules.system.secure;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.util.StringUtils;
import java.util.Collections;
import java.util.Map;
@Data
@AllArgsConstructor
public class ModerationForwardConfig {
private boolean enabled;
private Map<String, String> targets;
private String secret;
public static ModerationForwardConfig disabled() {
return new ModerationForwardConfig(false, Collections.emptyMap(), "");
}
public String targetFor(String env) {
if (!enabled || env == null || targets == null) return null;
String target = targets.get(env);
return StringUtils.hasText(target) ? target.trim() : null;
}
public boolean ready() {
return enabled && StringUtils.hasText(secret);
}
}
@@ -1,6 +1,7 @@
package com.xiaowang.jayucloud.salon.core.modules.system.service; package com.xiaowang.jayucloud.salon.core.modules.system.service;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO;
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.vo.SecureIntegrationConfigVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
@@ -14,6 +15,10 @@ public interface SecureIntegrationConfigService {
void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto);
void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto);
ModerationForwardConfig getModerationForwardConfig();
Map<String, String> getMapRuntimeConfig(UserDO currentUser); Map<String, String> getMapRuntimeConfig(UserDO currentUser);
ModerationRuntimeConfig getModerationRuntimeConfig(); ModerationRuntimeConfig getModerationRuntimeConfig();
@@ -1,6 +1,9 @@
package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; package com.xiaowang.jayucloud.salon.core.modules.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO;
@@ -8,12 +11,14 @@ import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegration
import com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO; import com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper; import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper; import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper;
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.secure.SecureConfigEncryptionService; import com.xiaowang.jayucloud.salon.core.modules.system.secure.SecureConfigEncryptionService;
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.vo.SecureIntegrationConfigVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -22,10 +27,12 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConfigService { public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConfigService {
@@ -40,6 +47,7 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
private final SecureConfigEncryptionService encryptionService; private final SecureConfigEncryptionService encryptionService;
private final ContentModerationProperties moderationProperties; private final ContentModerationProperties moderationProperties;
private final WechatMiniProperties wechatMiniProperties; private final WechatMiniProperties wechatMiniProperties;
private final ObjectMapper objectMapper;
@Override @Override
@Transactional @Transactional
@@ -80,6 +88,12 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId()) result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId())
? wechatMiniProperties.getAppId() : ""); ? wechatMiniProperties.getAppId() : "");
result.setMockProviderAllowed(isMockAllowed()); result.setMockProviderAllowed(isMockAllowed());
ModerationForwardConfig forwardConfig = getModerationForwardConfig();
result.setModerationForwardEnabled(forwardConfig.isEnabled());
result.setModerationForwardTargets(forwardConfig.getTargets());
result.setModerationForwardSecretConfigured(StringUtils.hasText(forwardConfig.getSecret()));
result.setUpdatedAt(latestUpdateTime()); result.setUpdatedAt(latestUpdateTime());
return result; return result;
} }
@@ -163,6 +177,77 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
writeValue(MODERATION, "PROVIDER", provider, false, currentUser.getId()); writeValue(MODERATION, "PROVIDER", provider, false, currentUser.getId());
} }
@Override
@Transactional(rollbackFor = Exception.class)
public void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) {
requirePlatformAdmin(currentUser);
requireEncryptionKey();
boolean enabled = Boolean.TRUE.equals(dto.getModerationForwardEnabled());
Map<String, String> targets = normalizeForwardTargets(dto.getModerationForwardTargets());
for (Map.Entry<String, String> entry : targets.entrySet()) {
if (!isValidForwardTarget(entry.getValue())) {
throw new IllegalArgumentException("跨环境转发地址不合法(" + entry.getKey()
+ "),必须精确指向 /api/integration/wechat/content-moderation/callback,且 HTTP 仅允许内网主机");
}
}
ModerationForwardConfig current = getModerationForwardConfig();
String secret;
if (Boolean.TRUE.equals(dto.getClearModerationForwardSecret())) {
secret = "";
} else if (StringUtils.hasText(dto.getModerationForwardSecret())) {
secret = dto.getModerationForwardSecret().trim();
} else {
secret = current.getSecret();
}
if (StringUtils.hasText(secret) && !secret.matches("[A-Za-z0-9+/=_\\-]{16,128}")) {
throw new IllegalArgumentException("跨环境转发共享密钥需要为 16-128 位字母、数字或常用符号");
}
if (enabled) {
if (!StringUtils.hasText(secret)) {
throw new IllegalArgumentException("启用跨环境回调转发时必须配置共享密钥");
}
if (targets.isEmpty()) {
throw new IllegalArgumentException("启用跨环境回调转发时至少需要配置一个目标环境地址");
}
}
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("enabled", enabled);
payload.put("targets", targets);
payload.put("secret", secret);
try {
writeValue(MODERATION, "FORWARD_JSON", objectMapper.writeValueAsString(payload), true, currentUser.getId());
} catch (JsonProcessingException exception) {
throw new IllegalStateException("无法保存跨环境转发配置", exception);
}
}
@Override
public ModerationForwardConfig getModerationForwardConfig() {
if (!encryptionService.isConfigured()) return ModerationForwardConfig.disabled();
String json = readValue(MODERATION, "FORWARD_JSON", "");
if (!StringUtils.hasText(json)) return ModerationForwardConfig.disabled();
try {
JsonNode node = objectMapper.readTree(json);
boolean enabled = node.path("enabled").asBoolean(false);
Map<String, String> targets = new LinkedHashMap<>();
JsonNode targetsNode = node.path("targets");
if (targetsNode.isObject()) {
targetsNode.fields().forEachRemaining(entry -> {
if (StringUtils.hasText(entry.getValue().asText(""))) {
targets.put(entry.getKey(), entry.getValue().asText(""));
}
});
}
return new ModerationForwardConfig(enabled, targets, node.path("secret").asText(""));
} catch (JsonProcessingException exception) {
log.warn("跨环境转发配置解析失败,按未启用处理");
return ModerationForwardConfig.disabled();
}
}
@Override @Override
@Transactional @Transactional
public Map<String, String> getMapRuntimeConfig(UserDO currentUser) { public Map<String, String> getMapRuntimeConfig(UserDO currentUser) {
@@ -362,6 +447,62 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
} }
} }
private Map<String, String> normalizeForwardTargets(Map<String, String> raw) {
Map<String, String> result = new LinkedHashMap<>();
if (raw == null) return result;
for (String env : Arrays.asList("dev", "sit", "prod")) {
String value = raw.get(env);
if (StringUtils.hasText(value)) result.put(env, value.trim());
}
return result;
}
/**
* 只允许指向内容审核回调路径:HTTPS 放行(各环境对外地址通常为 HTTPS 域名),
* HTTP 仅允许私网/本机主机,避免被配置为任意公网地址造成 SSRF。
*/
private boolean isValidForwardTarget(String value) {
if (!StringUtils.hasText(value)) return false;
try {
URI uri = new URI(value.trim());
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
String host = uri.getHost();
if (!"https".equals(scheme) && !"http".equals(scheme)) return false;
if (!StringUtils.hasText(host)) return false;
if (uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null) return false;
if (!WECHAT_CALLBACK_PATH.equals(uri.getRawPath())) return false;
return !"http".equals(scheme) || isPrivateHost(host);
} catch (URISyntaxException exception) {
return false;
}
}
private boolean isPrivateHost(String host) {
String normalized = host.toLowerCase(Locale.ROOT);
if (normalized.startsWith("[") && normalized.endsWith("]")) {
normalized = normalized.substring(1, normalized.length() - 1);
}
if ("localhost".equals(normalized) || normalized.endsWith(".localhost")
|| normalized.endsWith(".local") || normalized.endsWith(".internal")) {
return true;
}
if (normalized.contains(":")) {
return normalized.startsWith("::1") || normalized.startsWith("fc") || normalized.startsWith("fd");
}
String[] parts = normalized.split("\\.");
if (parts.length != 4) return false;
try {
int first = Integer.parseInt(parts[0]);
int second = Integer.parseInt(parts[1]);
if (first == 10 || first == 127) return true;
if (first == 192 && second == 168) return true;
if (first == 172 && second >= 16 && second <= 31) return true;
return first == 169 && second == 254;
} catch (NumberFormatException exception) {
return false;
}
}
private String normalizedProvider(String value) { private String normalizedProvider(String value) {
return upper(value, "DISABLED"); return upper(value, "DISABLED");
} }
@@ -0,0 +1,18 @@
package com.xiaowang.jayucloud.salon.core.modules.system.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class ModerationForwardRecordVO {
private Long id;
private String traceId;
private String sourceEnv;
private String targetEnv;
private String status;
private Integer retryCount;
private String lastError;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -4,6 +4,7 @@ import lombok.Data;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Map;
@Data @Data
public class SecureIntegrationConfigVO { public class SecureIntegrationConfigVO {
@@ -24,6 +25,11 @@ public class SecureIntegrationConfigVO {
private String wechatMiniAppId; private String wechatMiniAppId;
private Boolean mockProviderAllowed; private Boolean mockProviderAllowed;
private Boolean moderationForwardEnabled;
private Map<String, String> moderationForwardTargets;
private Boolean moderationForwardSecretConfigured;
private List<ModerationForwardRecordVO> moderationForwardRecent;
private Boolean encryptionKeyConfigured; private Boolean encryptionKeyConfigured;
private LocalDateTime updatedAt; private LocalDateTime updatedAt;
/** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */ /** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */
@@ -0,0 +1,16 @@
CREATE TABLE IF NOT EXISTS t_moderation_callback_forward (
id BIGINT NOT NULL COMMENT '主键ID',
trace_id VARCHAR(128) NOT NULL COMMENT '微信异步图片审核任务标识 trace_id',
source_env VARCHAR(16) NOT NULL COMMENT '实际收到微信回调的部署环境',
target_env VARCHAR(16) NULL COMMENT '应处理该回调的部署环境',
extra_json VARCHAR(256) NULL COMMENT '微信回调透传的 extra 原始内容',
payload LONGTEXT NULL COMMENT '回调解密后的完整报文,仅用于补偿重放',
status VARCHAR(16) NOT NULL COMMENT 'PENDING/SUCCESS/RETRY/FAILED/NO_ENV/TARGET_MISSING',
retry_count INT NOT NULL DEFAULT 0 COMMENT '已重试次数',
last_error VARCHAR(500) NULL COMMENT '最近一次失败原因(脱敏)',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
UNIQUE KEY uk_moderation_callback_forward_trace (trace_id),
KEY idx_moderation_callback_forward_status (status, updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='微信审核回调跨环境转发记录';
@@ -1,45 +1,51 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; 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.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;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType; 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 org.junit.jupiter.api.Test;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class WechatContentModerationCallbackControllerTest { class WechatContentModerationCallbackControllerTest {
private static final String CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback";
@Test @Test
void aesHandshakeVerifiesEncryptedEchoAndReturnsDecryptedValue() { void aesHandshakeVerifiesEncryptedEchoAndReturnsDecryptedValue() {
SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class);
when(secureConfig.getModerationCallbackConfig()).thenReturn( when(secureConfig.getModerationCallbackConfig()).thenReturn(
new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true));
WechatMiniProperties wechatProperties = new WechatMiniProperties();
wechatProperties.setAppId("mini-app-id");
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-echo", "message-signature")) when(crypto.verify("callback-token", "1000", "nonce", "encrypted-echo", "message-signature"))
.thenReturn(true); .thenReturn(true);
when(crypto.decrypt("encrypted-echo", "encoding-aes-key", "mini-app-id")) when(crypto.decrypt("encrypted-echo", "encoding-aes-key", "mini-app-id"))
.thenReturn("verified-echo"); .thenReturn("verified-echo");
WechatContentModerationCallbackController controller = new WechatContentModerationCallbackController( WechatContentModerationCallbackController controller = controller(secureConfig, crypto,
secureConfig, mock(ContentModerationService.class), mock(IntegrationProbeService.class),
wechatProperties, mock(ContentModerationForwardService.class));
crypto,
mock(ContentModerationService.class),
mock(IntegrationProbeService.class),
new ObjectMapper());
String result = controller.verifyEndpoint("1000", "nonce", "message-signature", null, "aes", "encrypted-echo"); String result = controller.verifyEndpoint("1000", "nonce", "message-signature", null, "aes", "encrypted-echo");
@@ -52,31 +58,31 @@ class WechatContentModerationCallbackControllerTest {
void plaintextHandshakeStillUsesPlainSignature() { void plaintextHandshakeStillUsesPlainSignature() {
SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class);
when(secureConfig.getModerationCallbackConfig()).thenReturn( when(secureConfig.getModerationCallbackConfig()).thenReturn(
new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "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);
WechatContentModerationCallbackController controller = new WechatContentModerationCallbackController( WechatMiniProperties wechatProperties = new WechatMiniProperties();
secureConfig, wechatProperties.setAppId("mini-app-id");
new WechatMiniProperties(), WechatContentModerationCallbackController controller = controller(secureConfig, crypto,
crypto, mock(ContentModerationService.class), mock(IntegrationProbeService.class),
mock(ContentModerationService.class), mock(ContentModerationForwardService.class));
mock(IntegrationProbeService.class),
new ObjectMapper());
assertEquals("echo", controller.verifyEndpoint("1000", "nonce", null, "plain-signature", null, "echo")); assertEquals("echo", controller.verifyEndpoint("1000", "nonce", null, "plain-signature", null, "echo"));
verify(crypto).verifyPlain("callback-token", "1000", "nonce", "plain-signature"); verify(crypto).verifyPlain("callback-token", "1000", "nonce", "plain-signature");
} }
@Test @Test
void acceptsJsonEnvelopeForAesEncryptedCallback() throws Exception { void localHitDoesNotForward() 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);
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")) ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
.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\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}"); .thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"envVersion\\\":\\\"trial\\\"}\"}");
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build(); when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial")).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback") mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000") .param("timestamp", "1000")
@@ -90,6 +96,8 @@ class WechatContentModerationCallbackControllerTest {
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature"); verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature");
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial"); 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 @Test
@@ -99,14 +107,15 @@ class WechatContentModerationCallbackControllerTest {
ContentModerationService moderationService = mock(ContentModerationService.class); ContentModerationService moderationService = mock(ContentModerationService.class);
String xml = "<xml><Encrypt>encrypted-xml</Encrypt></xml>"; String xml = "<xml><Encrypt>encrypted-xml</Encrypt></xml>";
when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml"); when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")) when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true);
.thenReturn(true); String decodedXml = "<xml><trace_id>task-xml</trace_id><suggest>review</suggest><extra>{&quot;env&quot;:&quot;prod&quot;,&quot;envVersion&quot;:&quot;release&quot;}</extra></xml>";
String decodedXml = "<xml><trace_id>task-xml</trace_id><suggest>review</suggest><extra>{&quot;envVersion&quot;:&quot;release&quot;}</extra></xml>";
when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml); 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, "trace_id")).thenReturn("task-xml");
when(crypto.value(decodedXml, "suggest")).thenReturn("review"); when(crypto.value(decodedXml, "suggest")).thenReturn("review");
when(crypto.value(decodedXml, "extra")).thenReturn("{\"envVersion\":\"release\"}"); when(crypto.value(decodedXml, "extra")).thenReturn("{\"env\":\"prod\",\"envVersion\":\"release\"}");
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build(); 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") mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000") .param("timestamp", "1000")
@@ -122,19 +131,170 @@ class WechatContentModerationCallbackControllerTest {
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release"); verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release");
} }
@Test
void probeHitSkipsModerationAndForwarding() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
IntegrationProbeService probeService = mock(IntegrationProbeService.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\":\"probe-1\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"probeId\\\":\\\"probe-1\\\"}\"}");
when(probeService.handleImageCallback("probe-1", "review", "probe-1")).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
mock(ContentModerationService.class), probeService, forwardService)).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_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
}
@Test
void otherEnvironmentCallbackIsEnqueuedAndReturnsSuccessImmediately() 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)));
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).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_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
verify(forwardService).enqueue(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString());
}
@Test
void missingTargetReturnsSuccessAndRecordsTargetMissing() 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()));
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).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_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
verify(forwardService).recordTargetMissing(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString());
}
@Test
void extraWithoutEnvIsRecordedAsNoEnvAndNotForwarded() 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)));
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).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_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.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());
}
@Test
void secondHopOrSelfForwardIsDroppedAndRecorded() throws Exception {
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
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", "sit")
.header("X-Moderation-Forward-Hop", "2")
.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\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
verify(forwardService).recordUnclaimed(eq("loop-task"), any(), anyString(), anyString());
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
}
@Test
void forwardedSignatureFailureIsRejected() {
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(false);
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", "1", "1000", "forward-nonce", "bad-signature",
"{\"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(
new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true));
return secureConfig; return secureConfig;
} }
private WechatContentModerationCallbackController controller(SecureIntegrationConfigService secureConfig, private WechatContentModerationCallbackController controller(SecureIntegrationConfigService secureConfig,
WechatCallbackCrypto crypto, WechatCallbackCrypto crypto,
ContentModerationService moderationService) { ContentModerationService moderationService,
IntegrationProbeService probeService,
ContentModerationForwardService forwardService) {
WechatMiniProperties wechatProperties = new WechatMiniProperties(); WechatMiniProperties wechatProperties = new WechatMiniProperties();
wechatProperties.setAppId("mini-app-id"); wechatProperties.setAppId("mini-app-id");
return new WechatContentModerationCallbackController( SalonDeployProperties deployProperties = new SalonDeployProperties();
secureConfig, wechatProperties, crypto, moderationService, mock(IntegrationProbeService.class), new ObjectMapper()); deployProperties.setEnv("sit");
return new WechatContentModerationCallbackController(secureConfig, wechatProperties, crypto,
moderationService, probeService, forwardService, deployProperties, new ObjectMapper());
} }
} }
@@ -0,0 +1,172 @@
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.system.entity.ModerationCallbackForwardDO;
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.service.SecureIntegrationConfigService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
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.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.Mockito.mock;
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 ModerationCallbackForwardMapper forwardMapper;
private SecureIntegrationConfigService secureConfig;
private ModerationForwardHttpClient httpClient;
private RedisTemplate<String, Object> redisTemplate;
private ValueOperations<String, Object> valueOperations;
private ContentModerationForwardServiceImpl service;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
forwardMapper = mock(ModerationCallbackForwardMapper.class);
secureConfig = mock(SecureIntegrationConfigService.class);
httpClient = mock(ModerationForwardHttpClient.class);
redisTemplate = mock(RedisTemplate.class);
valueOperations = mock(ValueOperations.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);
}
@Test
void acceptsValidHmacSignature() throws Exception {
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonce = "nonce-valid";
String body = "{\"trace_id\":\"task-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() {
String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600);
assertFalse(service.verifySignature(timestamp, "nonce-expired", "deadbeef", "{}"));
}
@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);
int attempted = service.retryPending();
assertEquals(1, attempted);
assertEquals("SUCCESS", row.getStatus());
verify(forwardMapper).updateById(row);
}
@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());
}
@Test
void targetMissingIsRecordedWithoutRetryQueue() {
service.recordTargetMissing("task-missing", "sit", "prod", "{\"env\":\"prod\"}", "{}");
ArgumentCaptor<ModerationCallbackForwardDO> 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());
}
@Test
void missingExtraIsRecordedAsNoEnv() {
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");
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();
}
}
@@ -116,7 +116,7 @@ class SecureIntegrationConfigServiceImplTest {
currentUser.setType(2); currentUser.setType(2);
SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl(
mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY),
new ContentModerationProperties(), configuredWechat()); new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper());
assertThrows(RuntimeException.class, () -> service.getMapRuntimeConfig(currentUser)); assertThrows(RuntimeException.class, () -> service.getMapRuntimeConfig(currentUser));
verify(mapper, never()).selectOne(any()); verify(mapper, never()).selectOne(any());
@@ -131,7 +131,7 @@ class SecureIntegrationConfigServiceImplTest {
UserDO currentUser = adminUser(); UserDO currentUser = adminUser();
SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl(
mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY),
new ContentModerationProperties(), configuredWechat()); new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper());
assertEquals("false", service.getMapRuntimeConfig(currentUser).get("enabled")); assertEquals("false", service.getMapRuntimeConfig(currentUser).get("enabled"));
verify(mapper, org.mockito.Mockito.atLeastOnce()).selectOne(any()); verify(mapper, org.mockito.Mockito.atLeastOnce()).selectOne(any());
@@ -142,7 +142,7 @@ class SecureIntegrationConfigServiceImplTest {
ContentModerationProperties moderationProperties, ContentModerationProperties moderationProperties,
WechatMiniProperties wechatProperties) { WechatMiniProperties wechatProperties) {
return new SecureIntegrationConfigServiceImpl(mapper, mock(SystemParameterConfigMapper.class), encryption, return new SecureIntegrationConfigServiceImpl(mapper, mock(SystemParameterConfigMapper.class), encryption,
moderationProperties, wechatProperties); moderationProperties, wechatProperties, new com.fasterxml.jackson.databind.ObjectMapper());
} }
private UserDO adminUser() { private UserDO adminUser() {
@@ -132,7 +132,8 @@ class IntegrationProbeServiceImplTest {
.thenReturn("{\"errcode\":0,\"trace_id\":\"probe-task\"}"); .thenReturn("{\"errcode\":0,\"trace_id\":\"probe-task\"}");
WechatContentModerationProvider provider = new WechatContentModerationProvider( WechatContentModerationProvider provider = new WechatContentModerationProvider(
restTemplate, new ObjectMapper(), wechatClient, restTemplate, new ObjectMapper(), wechatClient,
new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties()); new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(),
deployProperties());
provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial"); provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial");
@@ -149,7 +150,8 @@ class IntegrationProbeServiceImplTest {
.thenReturn("{\"errcode\":47001}"); .thenReturn("{\"errcode\":47001}");
WechatContentModerationProvider provider = new WechatContentModerationProvider( WechatContentModerationProvider provider = new WechatContentModerationProvider(
restTemplate, new ObjectMapper(), wechatClient, restTemplate, new ObjectMapper(), wechatClient,
new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties()); new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(),
deployProperties());
var result = provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial"); var result = provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial");
@@ -157,6 +159,13 @@ class IntegrationProbeServiceImplTest {
assertEquals("微信审核请求参数格式无效,请核对接口字段", result.reason()); assertEquals("微信审核请求参数格式无效,请核对接口字段", result.reason());
} }
private com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties deployProperties() {
com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties properties =
new com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties();
properties.setEnv("sit");
return properties;
}
private UserDO admin() { private UserDO admin() {
UserDO user = new UserDO(); UserDO user = new UserDO();
user.setId(1L); user.setId(1L);
+22 -1
View File
@@ -1594,11 +1594,27 @@ export interface SecureIntegrationConfigVO {
wechatMiniAppConfigured: boolean wechatMiniAppConfigured: boolean
wechatMiniAppId: string wechatMiniAppId: string
mockProviderAllowed: boolean mockProviderAllowed: boolean
moderationForwardEnabled?: boolean
moderationForwardTargets?: Record<string, string>
moderationForwardSecretConfigured?: boolean
moderationForwardRecent?: ModerationForwardRecordVO[]
encryptionKeyConfigured: boolean encryptionKeyConfigured: boolean
updatedAt?: string updatedAt?: string
probeResults?: IntegrationProbeResultVO[] probeResults?: IntegrationProbeResultVO[]
} }
export interface ModerationForwardRecordVO {
id: IdType
traceId: string
sourceEnv?: string
targetEnv?: string
status: 'PENDING' | 'SUCCESS' | 'RETRY' | 'FAILED' | 'NO_ENV' | 'TARGET_MISSING' | string
retryCount?: number
lastError?: string
createdAt?: string
updatedAt?: string
}
export interface IntegrationProbeCheckVO { export interface IntegrationProbeCheckVO {
name: string name: string
status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING' status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING'
@@ -1640,6 +1656,10 @@ export interface SecureIntegrationConfigUpdate {
moderationEncodingAesKey?: string moderationEncodingAesKey?: string
clearModerationCallbackToken?: boolean clearModerationCallbackToken?: boolean
clearModerationEncodingAesKey?: boolean clearModerationEncodingAesKey?: boolean
moderationForwardEnabled?: boolean
moderationForwardTargets?: Record<string, string>
moderationForwardSecret?: string
clearModerationForwardSecret?: boolean
} }
/** /**
@@ -1664,7 +1684,8 @@ export const adminSecureIntegrationConfigApi = {
probe: (data: IntegrationProbeRequest) => adminApi.post<IntegrationProbeResultVO>('/system-settings/secure-integration/probe', data) as unknown as Promise<IntegrationProbeResultVO>, probe: (data: IntegrationProbeRequest) => adminApi.post<IntegrationProbeResultVO>('/system-settings/secure-integration/probe', data) as unknown as Promise<IntegrationProbeResultVO>,
getMapRuntimeConfig: () => adminApi.get<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>('/system-settings/secure-integration/map-runtime') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>, getMapRuntimeConfig: () => adminApi.get<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>('/system-settings/secure-integration/map-runtime') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>,
saveMapConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post<SecureIntegrationConfigVO>('/system-settings/secure-integration/map', data) as unknown as Promise<SecureIntegrationConfigVO>, saveMapConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post<SecureIntegrationConfigVO>('/system-settings/secure-integration/map', data) as unknown as Promise<SecureIntegrationConfigVO>,
saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post<SecureIntegrationConfigVO>('/system-settings/secure-integration/content-moderation', data) as unknown as Promise<SecureIntegrationConfigVO> saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post<SecureIntegrationConfigVO>('/system-settings/secure-integration/content-moderation', data) as unknown as Promise<SecureIntegrationConfigVO>,
saveModerationForwardConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post<SecureIntegrationConfigVO>('/system-settings/secure-integration/content-moderation-forward', data) as unknown as Promise<SecureIntegrationConfigVO>
} }
export interface WorkbenchRegistrationApplication { export interface WorkbenchRegistrationApplication {
@@ -306,6 +306,61 @@
<span v-else-if="secureStatus && !secureStatus.moderationCallbackReady" class="control-note">回调资料仍不完整,暂时不能进行微信 URL 验证。</span> <span v-else-if="secureStatus && !secureStatus.moderationCallbackReady" class="control-note">回调资料仍不完整,暂时不能进行微信 URL 验证。</span>
<span v-if="secureStatus && !secureStatus.encryptionKeyConfigured" class="secure-note__warning">安全接入加密主密钥尚未配置,Token 与 AESKey 不会保存。</span> <span v-if="secureStatus && !secureStatus.encryptionKeyConfigured" class="secure-note__warning">安全接入加密主密钥尚未配置,Token 与 AESKey 不会保存。</span>
</div> </div>
<div class="settings-subsection">
<div class="settings-subsection__head">
<div>
<strong>跨环境回调转发</strong>
<span class="tag">CROSS ENV</span>
<p class="control-note">微信只向一个环境推送异步图片审核结果;命中不到本地任务时,按回调 extra 中的部署环境标识转发到真正创建任务的环境。默认关闭。</p>
</div>
<a-button size="small" :loading="savingModerationForward" @click="saveModerationForwardConfig">保存转发设置</a-button>
</div>
<div class="field-grid cols-2">
<article class="field">
<div class="field__head"><span class="field__label">启用跨环境转发</span></div>
<p class="field__desc">关闭时未命中本地任务的回调只记录不转发。</p>
<div class="field__control"><a-switch v-model:checked="moderationForwardEnabled" /></div>
<div class="field__foot">
<span class="status-pill" :class="{ 'is-muted': !moderationForwardEnabled }">{{ moderationForwardEnabled ? '已启用' : '未启用' }}</span>
</div>
</article>
<article class="field">
<div class="field__head"><span class="field__label">共享密钥</span></div>
<p class="field__desc">16-128 位,仅用于服务端 HMAC-SHA256 转发验签,不写日志;各环境需配置相同密钥。</p>
<div class="field__control field__control--password">
<a-input-password v-model:value="moderationForwardSecret" autocomplete="new-password" :placeholder="secureStatus?.moderationForwardSecretConfigured && !clearModerationForwardSecret ? '••••••••' : '填写共享密钥,留空保持原值'" @update:value="clearModerationForwardSecret = false" />
<a-button v-if="secureStatus?.moderationForwardSecretConfigured" size="small" type="text" danger @click="clearModerationForwardSecret = !clearModerationForwardSecret">{{ clearModerationForwardSecret ? '撤销清除' : '清除' }}</a-button>
</div>
<div class="field__foot">
<span class="status-pill" :class="{ 'is-muted': !secureStatus?.moderationForwardSecretConfigured || clearModerationForwardSecret }">{{ clearModerationForwardSecret ? '保存后清除' : secureStatus?.moderationForwardSecretConfigured ? '已配置' : '待配置' }}</span>
</div>
</article>
<article v-for="env in forwardEnvTargets" :key="env.key" class="field field--wide">
<div class="field__head"><span class="field__label">{{ env.label }}回调地址</span></div>
<p class="field__desc">必须精确指向 /api/integration/wechat/content-moderation/callback;HTTP 仅允许内网主机。</p>
<div class="field__control">
<a-input v-model:value="moderationForwardTargets[env.key]" :placeholder="`例如 https://${env.key}.example.com/api/integration/wechat/content-moderation/callback`" />
</div>
</article>
</div>
<div class="forward-recent">
<div class="forward-recent__head">
<strong>最近转发结果</strong>
<span class="control-note">NO_ENV / TARGET_MISSING 不自动重试,补齐配置或人工处理后可重放。</span>
</div>
<div v-if="!(secureStatus?.moderationForwardRecent || []).length" class="control-note">暂无转发记录</div>
<ul v-else class="forward-recent__list">
<li v-for="item in secureStatus?.moderationForwardRecent" :key="String(item.id)">
<span class="status-pill" :class="{ 'is-muted': item.status !== 'SUCCESS' }">{{ forwardStatusLabel(item.status) }}</span>
<span class="forward-recent__env">{{ item.sourceEnv || '-' }} → {{ item.targetEnv || '-' }}</span>
<span class="forward-recent__trace" :title="item.traceId">{{ item.traceId }}</span>
<span class="forward-recent__time">{{ formatProbeTime(item.createdAt) }}</span>
<span v-if="item.lastError" class="forward-recent__error">{{ item.lastError }}</span>
</li>
</ul>
</div>
</div>
</div> </div>
</section> </section>
@@ -473,6 +528,16 @@ const moderationProvider = ref<'DISABLED' | 'MOCK' | 'WECHAT'>('DISABLED')
const moderationCallbackUrl = ref('') const moderationCallbackUrl = ref('')
const moderationSecrets = reactive({ callbackToken: '', encodingAesKey: '' }) const moderationSecrets = reactive({ callbackToken: '', encodingAesKey: '' })
const clearModerationSecrets = reactive({ callbackToken: false, encodingAesKey: false }) const clearModerationSecrets = reactive({ callbackToken: false, encodingAesKey: false })
const moderationForwardEnabled = ref(false)
const moderationForwardTargets = reactive<Record<'dev' | 'sit' | 'prod', string>>({ dev: '', sit: '', prod: '' })
const moderationForwardSecret = ref('')
const clearModerationForwardSecret = ref(false)
const savingModerationForward = ref(false)
const forwardEnvTargets = [
{ key: 'dev' as const, label: 'DEV' },
{ key: 'sit' as const, label: 'SIT' },
{ key: 'prod' as const, label: 'PROD' }
]
const smsProviderOptions = [ const smsProviderOptions = [
{ label: 'Spug 短信', value: 'SPUG' }, { label: 'Spug 短信', value: 'SPUG' },
{ label: '阿里云短信认证服务', value: 'ALIYUN_SMS_VERIFY' } { label: '阿里云短信认证服务', value: 'ALIYUN_SMS_VERIFY' }
@@ -630,6 +695,12 @@ const load = async () => {
mapEnabled.value = Boolean(secureConfig.mapEnabled) mapEnabled.value = Boolean(secureConfig.mapEnabled)
moderationProvider.value = secureConfig.moderationProvider || 'DISABLED' moderationProvider.value = secureConfig.moderationProvider || 'DISABLED'
moderationCallbackUrl.value = secureConfig.moderationCallbackUrl || defaultCallbackUrl() moderationCallbackUrl.value = secureConfig.moderationCallbackUrl || defaultCallbackUrl()
moderationForwardEnabled.value = Boolean(secureConfig.moderationForwardEnabled)
moderationForwardTargets.dev = secureConfig.moderationForwardTargets?.dev || ''
moderationForwardTargets.sit = secureConfig.moderationForwardTargets?.sit || ''
moderationForwardTargets.prod = secureConfig.moderationForwardTargets?.prod || ''
moderationForwardSecret.value = ''
clearModerationForwardSecret.value = false
mapSecrets.tencentWeb = '' mapSecrets.tencentWeb = ''
mapSecrets.amapWeb = '' mapSecrets.amapWeb = ''
mapSecrets.amapMini = '' mapSecrets.amapMini = ''
@@ -955,6 +1026,46 @@ const saveModerationConfig = async () => {
} }
} }
const forwardStatusLabel = (status?: string) => ({
PENDING: '待转发', SUCCESS: '已转发', RETRY: '待重试', FAILED: '失败',
NO_ENV: '无法认领', TARGET_MISSING: '目标未配置'
} as Record<string, string>)[status || ''] || '未知'
const saveModerationForwardConfig = async () => {
if (moderationForwardSecret.value && !/^[A-Za-z0-9+/=_\-]{16,128}$/.test(moderationForwardSecret.value)) {
message.warning('共享密钥需要为 16-128 位字母、数字或常用符号')
return
}
if (moderationForwardEnabled.value) {
const hasSecret = moderationForwardSecret.value.trim()
|| (secureStatus.value?.moderationForwardSecretConfigured && !clearModerationForwardSecret.value)
if (!hasSecret) {
message.warning('启用跨环境转发前,请填写共享密钥')
return
}
if (!Object.values(moderationForwardTargets).some(value => value.trim())) {
message.warning('启用跨环境转发前,至少填写一个目标环境地址')
return
}
}
savingModerationForward.value = true
try {
secureStatus.value = await adminSecureIntegrationConfigApi.saveModerationForwardConfig({
moderationForwardEnabled: moderationForwardEnabled.value,
moderationForwardTargets: { ...moderationForwardTargets },
moderationForwardSecret: moderationForwardSecret.value,
clearModerationForwardSecret: clearModerationForwardSecret.value
})
moderationForwardSecret.value = ''
clearModerationForwardSecret.value = false
message.success('跨环境转发设置已保存')
} catch (error) {
message.error(error instanceof Error ? error.message : '跨环境转发设置保存失败')
} finally {
savingModerationForward.value = false
}
}
const toggleMapSecretClear = (key: MapKey) => { clearMapSecrets[key] = !clearMapSecrets[key] } const toggleMapSecretClear = (key: MapKey) => { clearMapSecrets[key] = !clearMapSecrets[key] }
const toggleModerationSecretClear = (key: 'callbackToken' | 'encodingAesKey') => { clearModerationSecrets[key] = !clearModerationSecrets[key] } const toggleModerationSecretClear = (key: 'callbackToken' | 'encodingAesKey') => { clearModerationSecrets[key] = !clearModerationSecrets[key] }
@@ -1174,5 +1285,59 @@ onMounted(() => {
.svc__desc { white-space: normal; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; } .svc__desc { white-space: normal; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; }
.field__save { margin-left: 0; } .field__save { margin-left: 0; }
} }
.settings-subsection {
margin-top: 18px;
padding-top: 16px;
border-top: 1px dashed var(--border-color, #e5e7eb);
}
.settings-subsection__head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 12px;
}
.settings-subsection__head strong { font-size: 14px; }
.settings-subsection__head .tag { margin-left: 8px; }
.settings-subsection__head p { margin: 4px 0 0; }
.forward-recent { margin-top: 14px; }
.forward-recent__head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 10px;
margin-bottom: 8px;
}
.forward-recent__list {
display: flex;
flex-direction: column;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.forward-recent__list li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 7px 10px;
border: 1px solid var(--border-color, #e5e7eb);
border-radius: 8px;
font-size: 12px;
}
.forward-recent__trace {
flex: 1 1 180px;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.forward-recent__time { color: var(--text-color-secondary, #6b7280); }
.forward-recent__error { color: var(--danger-color, #c0392b); }
@media (max-width: 760px) {
.settings-subsection__head { flex-direction: column; align-items: stretch; }
}
</style> </style>
@@ -38,6 +38,9 @@ mybatis:
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
jayucloud-salon: jayucloud-salon:
deploy:
# 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败
env: dev
wechat: wechat:
mini: mini:
app-id: wxb6d77f7c07020d51 app-id: wxb6d77f7c07020d51
@@ -37,6 +37,9 @@ mybatis:
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
jayucloud-salon: jayucloud-salon:
deploy:
# 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败
env: prod
wechat: wechat:
mini: mini:
app-id: wxb6d77f7c07020d51 app-id: wxb6d77f7c07020d51
@@ -37,6 +37,9 @@ mybatis:
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
jayucloud-salon: jayucloud-salon:
deploy:
# 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败
env: sit
wechat: wechat:
mini: mini:
app-id: wxb6d77f7c07020d51 app-id: wxb6d77f7c07020d51