完善系统接入诊断与审核状态展示
自动发布开发环境 Nacos 配置 / publish (push) Successful in 20s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 6s

This commit is contained in:
2026-11-04 12:39:47 +08:00
parent 029b7cc578
commit d4fc48bc2a
12 changed files with 607 additions and 84 deletions
@@ -65,9 +65,9 @@ public class WechatContentModerationProvider implements ContentModerationProvide
return submitImageWithExtra(contentType, imageUrl, openId, encodeSourceEnvVersion(sourceEnvVersion));
}
public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId) {
public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) {
Map<String, String> extra = new LinkedHashMap<>();
extra.put("envVersion", "trial");
extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion));
extra.put("probeId", probeId);
try {
return submitImageWithExtra("INTEGRATION_PROBE", imageUrl, openId, objectMapper.writeValueAsString(extra));
@@ -76,6 +76,13 @@ public class WechatContentModerationProvider implements ContentModerationProvide
}
}
private String normalizeEnvVersion(String value) {
if ("developer".equalsIgnoreCase(value) || "develop".equalsIgnoreCase(value)) return "develop";
if ("trial".equalsIgnoreCase(value)) return "trial";
if ("formal".equalsIgnoreCase(value) || "release".equalsIgnoreCase(value)) return "release";
return "UNKNOWN";
}
private ModerationOutcome submitImageWithExtra(String contentType, String imageUrl, String openId, String extra) {
if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核");
if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) {
@@ -38,7 +38,9 @@ public class AdminSecureIntegrationConfigController {
@RequirePermission("messagehub:config:manage")
public Result<SecureIntegrationConfigVO> getConfig(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser));
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
config.setProbeResults(integrationProbeService.listLatest(currentUser));
return Result.success(config);
}
@GetMapping("/map-runtime")
@@ -95,8 +97,12 @@ public class AdminSecureIntegrationConfigController {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
try {
IntegrationProbeResultVO result = integrationProbeService.probe(currentUser, dto);
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
"probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus());
String auditDetail = "probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus();
if ("FAIL".equals(result.getStatus())) {
securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail);
} else {
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail);
}
return Result.success(result);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
@@ -23,13 +23,14 @@ import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeCheck
import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO;
import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.core.env.Environment;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
@@ -43,7 +44,6 @@ import java.util.UUID;
@Slf4j
@Service
@RequiredArgsConstructor
public class IntegrationProbeServiceImpl implements IntegrationProbeService {
private static final String[] SERVICES = {"CONTENT_MODERATION", "MAP", "OBJECT_STORAGE", "SMS", "SUBSCRIBE_MESSAGE"};
private static final String TEXT = "CONTENT_MODERATION";
@@ -63,6 +63,33 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
private final MessageHubPushConfigService messageHubPushConfigService;
private final MessageHubClientService messageHubClientService;
private final RestTemplate restTemplate;
private final Environment environment;
public IntegrationProbeServiceImpl(IntegrationProbeResultMapper resultMapper,
ObjectMapper objectMapper,
SecureIntegrationConfigService secureIntegrationConfigService,
WechatMiniProperties wechatMiniProperties,
WechatMiniClientService wechatMiniClientService,
WechatMiniBindingMapper bindingMapper,
WechatContentModerationProvider wechatContentModerationProvider,
List<ObjectStorageProvider> storageProviders,
MessageHubPushConfigService messageHubPushConfigService,
MessageHubClientService messageHubClientService,
@Qualifier("restTemplate") RestTemplate restTemplate,
Environment environment) {
this.resultMapper = resultMapper;
this.objectMapper = objectMapper;
this.secureIntegrationConfigService = secureIntegrationConfigService;
this.wechatMiniProperties = wechatMiniProperties;
this.wechatMiniClientService = wechatMiniClientService;
this.bindingMapper = bindingMapper;
this.wechatContentModerationProvider = wechatContentModerationProvider;
this.storageProviders = storageProviders;
this.messageHubPushConfigService = messageHubPushConfigService;
this.messageHubClientService = messageHubClientService;
this.restTemplate = restTemplate;
this.environment = environment;
}
@Override
public IntegrationProbeResultVO probe(UserDO currentUser, IntegrationProbeRequestDTO request) {
@@ -115,8 +142,21 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
.eq(IntegrationProbeResultDO::getCorrelationKey, probeId).last("LIMIT 1"));
}
if (row == null) return false;
row.setStatus("pass".equalsIgnoreCase(suggest) ? "PASS" : "review".equalsIgnoreCase(suggest) ? "WARN" : "FAIL");
row.setSummary("微信图片审核回调:" + (StringUtils.hasText(suggest) ? suggest : "review"));
if (!TEXT.equals(row.getServiceCode()) || !"IMAGE_CALLBACK".equals(row.getOperationCode())) return false;
if (!"PENDING".equals(row.getStatus())) return true;
if (row.getExpiresAt() != null && row.getExpiresAt().isBefore(LocalDateTime.now())) {
row.setStatus("FAIL");
row.setSummary("图片审核回调已超过等待期限");
row.setErrorCode("CALLBACK_TIMEOUT");
row.setCheckedAt(LocalDateTime.now());
deleteTemporaryObject(row);
resultMapper.updateById(row);
return true;
}
String candidateSuggest = StringUtils.hasText(suggest) ? suggest.trim().toLowerCase(Locale.ROOT) : "review";
String normalizedSuggest = List.of("pass", "review", "risky").contains(candidateSuggest) ? candidateSuggest : "unknown";
row.setStatus("pass".equals(normalizedSuggest) ? "PASS" : "review".equals(normalizedSuggest) ? "WARN" : "FAIL");
row.setSummary("微信图片审核回调:" + normalizedSuggest);
row.setCheckedAt(LocalDateTime.now());
try { row.setChecksJson(objectMapper.writeValueAsString(List.of(new IntegrationProbeCheckVO("微信图片审核回调", row.getStatus(), row.getSummary())))); }
catch (Exception ignored) { }
@@ -140,23 +180,50 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
deleteTemporaryObject(row);
resultMapper.updateById(row);
}
List<IntegrationProbeResultDO> cleanup = resultMapper.selectList(new LambdaQueryWrapper<IntegrationProbeResultDO>()
.isNotNull(IntegrationProbeResultDO::getTemporaryObjectName)
.lt(IntegrationProbeResultDO::getExpiresAt, LocalDateTime.now()));
for (IntegrationProbeResultDO row : cleanup) {
deleteTemporaryObject(row);
resultMapper.updateById(row);
}
}
private IntegrationProbeResultVO probeModeration(UserDO currentUser, String operation, String mode) {
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
List<IntegrationProbeCheckVO> checks = new ArrayList<>();
checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取"));
checks.add(check("审核 Provider", "WECHAT".equals(config.getModerationProvider()) || "MOCK".equals(config.getModerationProvider()), config.getModerationProvider(), "未启用"));
checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置"));
if ("WECHAT".equals(config.getModerationProvider())) {
checks.add(check("回调配置", Boolean.TRUE.equals(config.getModerationCallbackReady()), "公网 HTTPS 回调资料完整", "回调 URL、Token、AESKey 或加密主密钥不完整"));
String provider = config.getModerationProvider();
if ("WECHAT".equals(provider)) {
checks.add(check("审核 Provider", true, "微信内容安全审核", "未启用"));
checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取"));
checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置"));
String callbackUrl = config.getModerationCallbackUrl();
boolean callbackUrlValid = false;
try {
java.net.URI callback = java.net.URI.create(callbackUrl == null ? "" : callbackUrl);
callbackUrlValid = "https".equalsIgnoreCase(callback.getScheme())
&& StringUtils.hasText(callback.getHost())
&& (callback.getPort() == -1 || callback.getPort() == 443)
&& callback.getUserInfo() == null && callback.getQuery() == null && callback.getFragment() == null
&& "/api/integration/wechat/content-moderation/callback".equals(callback.getPath());
} catch (IllegalArgumentException ignored) { }
checks.add(check("回调 HTTPS 地址", callbackUrlValid, "公网 HTTPS 回调地址有效", "回调地址缺失或格式不正确"));
checks.add(check("回调 Token", Boolean.TRUE.equals(config.getModerationCallbackTokenConfigured()), "已配置", "未配置"));
checks.add(check("EncodingAESKey", Boolean.TRUE.equals(config.getModerationEncodingAesKeyConfigured()), "已配置", "未配置"));
checks.add(check("回调配置汇总", Boolean.TRUE.equals(config.getModerationCallbackReady()), "回调资料完整", "回调 URL、Token、AESKey、加密主密钥或 App 凭据不完整"));
} else if ("MOCK".equals(provider)) {
boolean mockAllowed = Boolean.TRUE.equals(config.getMockProviderAllowed());
checks.add(new IntegrationProbeCheckVO("审核 Provider", mockAllowed ? "PASS" : "FAIL", mockAllowed ? "本地模拟审核已启用" : "当前环境不允许模拟审核"));
checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "模拟渠道不会调用微信接口"));
} else {
checks.add(new IntegrationProbeCheckVO("审核 Provider", "WARN", "内容审核未启用,内容保持隔离"));
}
if (!"WECHAT".equals(config.getModerationProvider())) checks.add(new IntegrationProbeCheckVO("加密主密钥", "WARN", "当前 Provider 不是真实微信审核,无需校验加密回调密钥"));
if ("CONFIG".equals(operation)) return result(TEXT, operation, mode, config.getModerationProvider(), statusForChecks(checks), "内容审核配置诊断完成", null, checks);
if ("MOCK".equals(config.getModerationProvider())) {
if ("MOCK".equals(config.getModerationProvider()) && Boolean.TRUE.equals(config.getMockProviderAllowed())) {
checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "当前使用本地模拟审核,不会调用微信接口"));
return result(TEXT, operation, mode, "MOCK", "WARN", "当前为本地模拟流程", null, checks);
}
if ("MOCK".equals(config.getModerationProvider())) return result(TEXT, operation, mode, "MOCK", "FAIL", "当前环境不允许使用模拟审核", "MOCK_NOT_ALLOWED", checks);
if (!"WECHAT".equals(config.getModerationProvider())) return result(TEXT, operation, mode, config.getModerationProvider(), "FAIL", "微信内容审核未启用", "PROVIDER_DISABLED", checks);
if (!Boolean.TRUE.equals(config.getModerationReady())) return result(TEXT, operation, mode, "WECHAT", "FAIL", "微信审核配置未就绪,未发起接口请求", "MODERATION_NOT_READY", checks);
String openId = findProbeOpenId();
@@ -172,24 +239,43 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
}
private IntegrationProbeResultVO probeImageCallback(String mode, String openId, List<IntegrationProbeCheckVO> checks) {
IntegrationProbeResultDO current = findResult(TEXT, "IMAGE_CALLBACK");
if (current != null && "PENDING".equals(current.getStatus()) && current.getExpiresAt() != null && current.getExpiresAt().isAfter(LocalDateTime.now())) {
return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "PENDING", "已有图片测试正在等待微信回调", null,
List.of(new IntegrationProbeCheckVO("微信图片异步接口", "PENDING", "等待上一条测试的微信回调或超时清理")));
}
if (current != null && StringUtils.hasText(current.getTemporaryObjectName())) {
deleteTemporaryObject(current);
resultMapper.updateById(current);
if (StringUtils.hasText(current.getTemporaryObjectName())) {
return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "上一张临时测试图片仍未清理,请稍后重试", "TEMP_CLEANUP_FAILED",
List.of(new IntegrationProbeCheckVO("临时图片清理", "FAIL", "无法确认旧测试文件已删除")));
}
}
String objectName = "integration-probe/" + UUID.randomUUID() + ".png";
String probeId = UUID.randomUUID().toString();
ObjectStorageProvider uploaded = null;
boolean awaitingCallback = false;
boolean pendingSaved = false;
try {
byte[] image = createProbePng();
for (ObjectStorageProvider provider : storageProviders) {
if (provider.isEnabled()) {
provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName);
uploaded = provider;
provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName);
break;
}
}
if (uploaded == null) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "没有可用对象存储,无法生成图片审核地址", "STORAGE_UNAVAILABLE", checks);
String url = uploaded.getPresignedUrl(objectName, 5);
if (!StringUtils.hasText(url) || !url.startsWith("https://")) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks);
if (!StringUtils.hasText(url) || !url.startsWith("https://")) {
checks.add(new IntegrationProbeCheckVO("临时图片地址", "FAIL", "对象存储未提供公网 HTTPS 签名地址"));
return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks);
}
savePendingImageProbe(mode, probeId, uploaded.providerCode(), objectName);
ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId);
pendingSaved = true;
ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId,
wechatMiniProperties.getSubscribeMessageMiniprogramState());
String status = outcome.status() == ModerationOutcome.Status.PENDING ? "PENDING" : outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : "FAIL";
checks.add(new IntegrationProbeCheckVO("微信图片异步接口", status, outcome.reason()));
awaitingCallback = "PENDING".equals(status);
@@ -199,7 +285,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
checks.add(new IntegrationProbeCheckVO("微信图片异步接口", "FAIL", "临时图片上传或审核请求失败"));
return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "微信图片审核探测失败", "IMAGE_PROBE_FAILED", checks);
} finally {
if (uploaded != null && !awaitingCallback) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); }
if (uploaded != null && !awaitingCallback && !pendingSaved) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); }
}
}
@@ -238,20 +324,30 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
private void deleteTemporaryObject(IntegrationProbeResultDO row) {
if (!StringUtils.hasText(row.getTemporaryObjectProvider()) || !StringUtils.hasText(row.getTemporaryObjectName())) return;
storageProviders.stream().filter(provider -> provider.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().ifPresent(provider -> {
try { provider.deleteFile(row.getTemporaryObjectName()); }
catch (Exception ignored) { log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode()); }
});
row.setTemporaryObjectProvider(null);
row.setTemporaryObjectName(null);
ObjectStorageProvider provider = storageProviders.stream()
.filter(item -> item.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().orElse(null);
if (provider == null) return;
try {
provider.deleteFile(row.getTemporaryObjectName());
row.setTemporaryObjectProvider(null);
row.setTemporaryObjectName(null);
} catch (Exception ignored) {
log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode());
}
}
private IntegrationProbeResultVO probeMap(UserDO currentUser, String operation) {
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
List<IntegrationProbeCheckVO> checks = new ArrayList<>();
boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? Boolean.TRUE.equals(config.getAmapWebKeyConfigured()) : Boolean.TRUE.equals(config.getTencentWebKeyConfigured());
checks.add(check("当前 Web Key", selectedKey, "已配置", "未配置"));
checks.add(new IntegrationProbeCheckVO("高德小程序 Key", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "PASS" : "WARN", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "已配置" : "未配置,仅影响小程序选点"));
boolean amapKey = Boolean.TRUE.equals(config.getAmapWebKeyConfigured());
boolean tencentKey = Boolean.TRUE.equals(config.getTencentWebKeyConfigured());
boolean miniKey = Boolean.TRUE.equals(config.getAmapMiniKeyConfigured());
boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? amapKey : tencentKey;
checks.add(check("当前渠道 Web Key", selectedKey, "已配置", "未配置"));
checks.add(new IntegrationProbeCheckVO("高德 Web Key", amapKey ? "PASS" : "WARN", amapKey ? "已配置" : "未配置"));
checks.add(new IntegrationProbeCheckVO("腾讯 Web Key", tencentKey ? "PASS" : "WARN", tencentKey ? "已配置" : "未配置"));
checks.add(new IntegrationProbeCheckVO("高德小程序 Key", miniKey ? "PASS" : "WARN", miniKey ? "已配置" : "未配置,仅影响小程序选点"));
if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), statusForChecks(checks), "地图接入配置诊断完成", null, checks);
if (!selectedKey) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "FAIL", "当前地图渠道缺少 Web Key", "MAP_KEY_MISSING", checks);
if (!Boolean.TRUE.equals(config.getMapEnabled())) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "WARN", "地图服务当前已停用,保存并启用后才能测试真实请求", "MAP_DISABLED", checks);
if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "PASS", "地图 Key 配置诊断完成", null, checks);
@@ -277,7 +373,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
for (ObjectStorageProvider provider : storageProviders) {
checks.add(new IntegrationProbeCheckVO(provider.providerCode(), provider.isEnabled() ? "PASS" : "WARN", provider.isEnabled() ? "已启用并具备基本配置" : "未启用或配置不完整"));
}
String status = checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS";
String status = checks.isEmpty() ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS";
return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储配置完整" : "存在未启用的对象存储渠道", null, checks);
}
byte[] bytes = "salon-integration-probe".getBytes(StandardCharsets.UTF_8);
@@ -290,6 +386,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
continue;
}
enabled++;
boolean cleanupFailed = false;
try {
provider.uploadStream(new java.io.ByteArrayInputStream(bytes), bytes.length, "text/plain", objectName);
try (InputStream input = provider.downloadFile(objectName)) {
@@ -302,8 +399,10 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
} catch (Exception exception) {
checks.add(new IntegrationProbeCheckVO(provider.providerCode(), "FAIL", "上传或读取失败"));
} finally {
try { provider.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); }
try { provider.deleteFile(objectName); }
catch (Exception ignored) { cleanupFailed = true; log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); }
}
if (cleanupFailed) checks.add(new IntegrationProbeCheckVO(provider.providerCode() + " 清理", "FAIL", "临时测试对象未能删除,请检查存储状态"));
}
String status = enabled == 0 ? "FAIL" : checks.stream().anyMatch(item -> "FAIL".equals(item.getStatus())) ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS";
return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储三副本往返测试成功" : "对象存储存在未就绪渠道", null, checks);
@@ -316,9 +415,27 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
List<IntegrationProbeCheckVO> checks = new ArrayList<>();
List<com.xiaowang.jayucloud.salon.core.modules.integration.vo.MessageHubPushConfigVO> configs = messageHubPushConfigService.listConfigs(currentUser);
List<String> expectedScenes = List.of("USER_REGISTER_SMS_CODE", "USER_LOGIN_SMS_CODE", "USER_RESET_PASSWORD_SMS_CODE", "USER_BIND_PHONE_SMS_CODE", "USER_CHANGE_PHONE_SMS_CODE", "USER_CHANGE_PASSWORD_SMS_CODE");
long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode()) && Integer.valueOf(1).equals(item.getEnabled()))).count();
checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景已启用"));
boolean complete = enabled == expectedScenes.size();
long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode())
&& "SMS".equalsIgnoreCase(item.getPlatform()) && Integer.valueOf(1).equals(item.getEnabled())
&& StringUtils.hasText(item.getSendMethod()) && StringUtils.hasText(item.getQueueName())
&& StringUtils.hasText(item.getTemplateCode()))).count();
checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景配置完整并启用"));
String baseUrl = environment.getProperty("messagehub.client.base-url", "http://192.168.10.107:8080");
String accessToken = environment.getProperty("messagehub.client.access-token");
String exchange = environment.getProperty("messagehub.client.ingress-exchange", "messagehub.ingress.exchange");
String routingKey = environment.getProperty("messagehub.client.ingress-routing-key", "message.send");
String smsQueue = environment.getProperty("messagehub.client.sms-queue", "smsQueue");
String sourceSystem = environment.getProperty("messagehub.client.source-system", "jayucloud-salon");
String templateCode = environment.getProperty("messagehub.client.verify-template-code", "SPUG_SMS_VERIFY_1");
String sendMethod = environment.getProperty("messagehub.client.send-method", "SPUG");
boolean endpointConfigured = safeHttpUrl(baseUrl);
checks.add(check("MessageHub 地址", endpointConfigured, "已配置 HTTP(S) 地址", "地址未配置或格式无效"));
checks.add(check("MessageHub 访问凭据", StringUtils.hasText(accessToken), "已配置", "未配置"));
boolean deliveryConfigured = StringUtils.hasText(exchange) && StringUtils.hasText(routingKey)
&& StringUtils.hasText(smsQueue) && StringUtils.hasText(sourceSystem)
&& StringUtils.hasText(templateCode) && StringUtils.hasText(sendMethod);
checks.add(check("短信投递参数", deliveryConfigured, "交换机、路由、队列、来源和模板已配置", "部分投递参数缺失"));
boolean complete = enabled == expectedScenes.size() && endpointConfigured && StringUtils.hasText(accessToken) && deliveryConfigured;
if ("CONFIG".equals(operation) || !"REAL".equals(mode)) return result(SMS, operation, mode, "MESSAGEHUB", complete ? "PASS" : "FAIL", complete ? "短信场景配置完整;未发送真实短信" : "部分短信场景未启用", null, checks);
if (!complete) return result(SMS, operation, mode, "MESSAGEHUB", "FAIL", "短信场景配置不完整,未发送测试短信", "SMS_CONFIG_INCOMPLETE", checks);
if (!StringUtils.hasText(phone) || !phone.matches("^1[3-9]\\d{9}$")) throw new IllegalArgumentException("真实短信测试需要填写有效手机号");
@@ -332,11 +449,21 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
List<IntegrationProbeCheckVO> checks = new ArrayList<>();
String provider = StringUtils.hasText(wechatMiniProperties.getSubscribeMessageProvider()) ? wechatMiniProperties.getSubscribeMessageProvider().trim().toLowerCase(Locale.ROOT) : "mock";
boolean enabled = Boolean.TRUE.equals(wechatMiniProperties.getSubscribeMessageEnabled());
checks.add(new IntegrationProbeCheckVO("发送渠道", "wechat".equals(provider) && enabled ? "PASS" : "WARN", "wechat".equals(provider) && enabled ? "微信真实发送已启用" : "当前为 Mock 或已停用"));
boolean liveProvider = "wechat".equals(provider) && enabled;
checks.add(new IntegrationProbeCheckVO("发送渠道", liveProvider ? "PASS" : "WARN", liveProvider ? "微信真实发送已启用" : "当前为 Mock 或已停用"));
if (!liveProvider) {
checks.add(new IntegrationProbeCheckVO("小程序凭据", "WARN", "当前未调用微信接口,因此不校验真实凭据"));
checks.add(new IntegrationProbeCheckVO("固定模板", "PASS", "3 个固定模板 ID 已加载"));
return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN",
"当前为 Mock 或已停用,未调用微信接口", null, checks);
}
boolean credentials = StringUtils.hasText(wechatMiniProperties.getAppId()) && StringUtils.hasText(wechatMiniProperties.getAppSecret());
checks.add(check("小程序凭据", credentials, "已配置", "AppID 或 AppSecret 未配置"));
if (!credentials) return result(SUBSCRIBE, operation, mode, "WECHAT", "FAIL", "订阅消息凭据不完整", "WECHAT_CREDENTIALS_MISSING", checks);
if (!"wechat".equals(provider) || !enabled) return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN", "当前订阅消息未启用微信真实发送", "PROVIDER_NOT_LIVE", checks);
checks.add(check("固定模板", WechatSubscribeMessageService.TEMPLATE_APPOINTMENT.length() > 10
&& WechatSubscribeMessageService.TEMPLATE_CANCELLED.length() > 10
&& WechatSubscribeMessageService.TEMPLATE_SERVICE_START.length() > 10,
"3 个固定模板 ID 已加载", "固定模板 ID 不完整"));
try {
wechatMiniClientService.getAccessTokenForContentModeration();
checks.add(new IntegrationProbeCheckVO("access_token", "PASS", "获取成功"));
@@ -360,7 +487,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
private IntegrationProbeResultVO checkSubscribeTemplates(String operation, String mode, List<IntegrationProbeCheckVO> checks) throws Exception {
String accessToken = wechatMiniClientService.getAccessTokenForContentModeration();
String url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8);
String url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8);
JsonNode response = objectMapper.readTree(restTemplate.getForObject(url, String.class));
int errorCode = response.path("errcode").asInt(0);
if (errorCode != 0) {
@@ -390,9 +517,9 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
private void validateOperation(String service, String operation, String mode) {
boolean valid = switch (service) {
case TEXT -> List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation);
case MAP -> List.of("CONFIG", "REQUEST").contains(operation);
case STORAGE -> List.of("CONFIG", "ROUND_TRIP").contains(operation);
case TEXT -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation);
case MAP -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "REQUEST").contains(operation);
case STORAGE -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "ROUND_TRIP").contains(operation);
case SMS -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode));
case SUBSCRIBE -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode));
default -> false;
@@ -434,6 +561,13 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
}
private String normalize(String value) { return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; }
private boolean safeHttpUrl(String value) {
if (!StringUtils.hasText(value)) return false;
try {
java.net.URI uri = java.net.URI.create(value.trim());
return ("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme())) && StringUtils.hasText(uri.getHost());
} catch (IllegalArgumentException ignored) { return false; }
}
private String safeMessage(RuntimeException exception) { return "探测请求未完成,请查看脱敏检查项"; }
private String subscribeSendError(int code) {
if (code == 43101) return "当前绑定账号尚未授权此订阅模板";
@@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class SecureIntegrationConfigVO {
@@ -25,4 +26,6 @@ public class SecureIntegrationConfigVO {
private Boolean encryptionKeyConfigured;
private LocalDateTime updatedAt;
/** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */
private List<IntegrationProbeResultVO> probeResults;
}
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerati
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto;
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@@ -37,6 +38,7 @@ class WechatContentModerationCallbackControllerTest {
wechatProperties,
crypto,
mock(ContentModerationService.class),
mock(IntegrationProbeService.class),
new ObjectMapper());
String result = controller.verifyEndpoint("1000", "nonce", "message-signature", null, "aes", "encrypted-echo");
@@ -58,6 +60,7 @@ class WechatContentModerationCallbackControllerTest {
new WechatMiniProperties(),
crypto,
mock(ContentModerationService.class),
mock(IntegrationProbeService.class),
new ObjectMapper());
assertEquals("echo", controller.verifyEndpoint("1000", "nonce", null, "plain-signature", null, "echo"));
@@ -132,6 +135,6 @@ class WechatContentModerationCallbackControllerTest {
WechatMiniProperties wechatProperties = new WechatMiniProperties();
wechatProperties.setAppId("mini-app-id");
return new WechatContentModerationCallbackController(
secureConfig, wechatProperties, crypto, moderationService, new ObjectMapper());
secureConfig, wechatProperties, crypto, moderationService, mock(IntegrationProbeService.class), new ObjectMapper());
}
}
@@ -0,0 +1,139 @@
package com.xiaowang.jayucloud.salon.core.modules.system.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider;
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.WechatContentModerationProvider;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.IntegrationProbeResultMapper;
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.user.entity.UserDO;
import org.junit.jupiter.api.Test;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.util.List;
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.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class IntegrationProbeServiceImplTest {
private final IntegrationProbeResultMapper results = mock(IntegrationProbeResultMapper.class);
private final SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class);
private final WechatMiniProperties wechatProperties = new WechatMiniProperties();
private final WechatMiniClientService wechatClient = mock(WechatMiniClientService.class);
private final WechatMiniBindingMapper bindings = mock(WechatMiniBindingMapper.class);
private final WechatContentModerationProvider moderationProvider = mock(WechatContentModerationProvider.class);
private final ObjectStorageProvider storageProvider = mock(ObjectStorageProvider.class);
private final MessageHubPushConfigService smsConfigs = mock(MessageHubPushConfigService.class);
private final MessageHubClientService smsClient = mock(MessageHubClientService.class);
private final RestTemplate restTemplate = mock(RestTemplate.class);
private final Environment environment = mock(Environment.class);
private final IntegrationProbeServiceImpl service = new IntegrationProbeServiceImpl(
results, new ObjectMapper(), secureConfig, wechatProperties, wechatClient, bindings,
moderationProvider, List.of(storageProvider), smsConfigs, smsClient, restTemplate, environment);
@Test
void rejectsNonAdminBeforeAnyProbeSideEffect() {
UserDO manager = new UserDO();
manager.setType(2);
assertThrows(RuntimeException.class, () -> service.probe(manager, request("SMS", "CONFIG", "DIAGNOSTIC", false)));
verify(smsConfigs, never()).listConfigs(any());
}
@Test
void realSmsCannotBeSentWithoutExplicitConfirmation() {
assertThrows(IllegalArgumentException.class,
() -> service.probe(admin(), request("SMS", "SEND", "REAL", false)));
verify(smsClient, never()).sendSmsVerificationCode(any(), any(), any());
}
@Test
void devMockIsNotReportedAsAnAllowedMockWhenEnvironmentDisallowsIt() {
SecureIntegrationConfigVO config = new SecureIntegrationConfigVO();
config.setModerationProvider("MOCK");
config.setMockProviderAllowed(false);
when(secureConfig.getAdminConfig(any())).thenReturn(config);
when(results.selectOne(any())).thenReturn(null);
var result = service.probe(admin(), request("CONTENT_MODERATION", "CONFIG", "DIAGNOSTIC", false));
assertEquals("FAIL", result.getStatus());
verify(moderationProvider, never()).reviewText(any(), any(), any());
}
@Test
void subscribeDiagnosticInMockModeDoesNotFetchTokenOrSendAnything() {
wechatProperties.setAppId("test-app");
wechatProperties.setAppSecret("test-secret");
wechatProperties.setSubscribeMessageEnabled(true);
wechatProperties.setSubscribeMessageProvider("mock");
when(results.selectOne(any())).thenReturn(null);
var result = service.probe(admin(), request("SUBSCRIBE_MESSAGE", "CONFIG", "DIAGNOSTIC", false));
assertEquals("WARN", result.getStatus());
verify(wechatClient, never()).getAccessTokenForContentModeration();
verify(wechatClient, never()).sendSubscribeMessage(any(), any(), any(), any(), any());
}
@Test
void anOutstandingImageProbePreventsAnotherTemporaryUpload() throws Exception {
wechatProperties.setAppId("test-app");
SecureIntegrationConfigVO config = new SecureIntegrationConfigVO();
config.setModerationProvider("WECHAT");
config.setModerationReady(true);
config.setModerationCallbackReady(true);
config.setEncryptionKeyConfigured(true);
config.setWechatMiniAppConfigured(true);
when(secureConfig.getAdminConfig(any())).thenReturn(config);
WechatMiniBindingDO binding = new WechatMiniBindingDO();
binding.setOpenId("private-open-id");
when(bindings.selectOne(any())).thenReturn(binding);
IntegrationProbeResultDO pending = new IntegrationProbeResultDO();
pending.setId(10L);
pending.setServiceCode("CONTENT_MODERATION");
pending.setOperationCode("IMAGE_CALLBACK");
pending.setStatus("PENDING");
pending.setExpiresAt(LocalDateTime.now().plusMinutes(2));
when(results.selectOne(any())).thenReturn(pending);
var result = service.probe(admin(), request("CONTENT_MODERATION", "IMAGE_CALLBACK", "DIAGNOSTIC", false));
assertEquals("PENDING", result.getStatus());
verify(storageProvider, never()).uploadStream(any(), anyLong(), any(), any());
verify(moderationProvider, never()).submitTestImage(any(), any(), any(), any());
}
private UserDO admin() {
UserDO user = new UserDO();
user.setId(1L);
user.setType(4);
return user;
}
private IntegrationProbeRequestDTO request(String service, String operation, String mode, boolean confirmed) {
IntegrationProbeRequestDTO request = new IntegrationProbeRequestDTO();
request.setService(service);
request.setOperation(operation);
request.setMode(mode);
request.setConfirmed(confirmed);
request.setTargetPhone("13800138000");
return request;
}
}