安全接入配置改造回溯点

This commit is contained in:
2026-10-30 22:04:38 +08:00
parent 9a2c158fdd
commit 8b205f3220
12 changed files with 295 additions and 100 deletions
@@ -16,9 +16,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
@RestController
@RequiredArgsConstructor
@RequestMapping("/integration/wechat/content-moderation")
@@ -36,7 +33,7 @@ public class WechatContentModerationCallbackController {
@RequestParam(value = "signature", required = false) String signature,
@RequestParam(value = "encrypt_type", required = false) String encryptType,
@RequestParam("echostr") String echoString) {
ModerationRuntimeConfig config = requireWechatConfig();
ModerationRuntimeConfig config = requireCallbackConfig();
if ("aes".equalsIgnoreCase(encryptType)) {
if (!crypto.verify(config.getCallbackToken(), timestamp, nonce, echoString, messageSignature)) {
throw new IllegalArgumentException("微信审核回调 AES 握手校验失败");
@@ -50,7 +47,7 @@ public class WechatContentModerationCallbackController {
}
@PostMapping(value = "/callback", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
public String callback(HttpServletRequest request, @RequestParam("timestamp") String timestamp,
public String callback(@RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce,
@RequestParam(value = "msg_signature", required = false) String messageSignature,
@RequestParam(value = "signature", required = false) String signature,
@@ -98,10 +95,20 @@ public class WechatContentModerationCallbackController {
}
private ModerationRuntimeConfig requireWechatConfig() {
ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationRuntimeConfig();
if (config == null || !config.isReady() || !"WECHAT".equals(config.getProvider())) {
ModerationRuntimeConfig config = requireCallbackConfig();
if (!"WECHAT".equals(config.getProvider())) {
throw new IllegalStateException("微信内容审核回调尚未启用或配置不完整");
}
return config;
}
private ModerationRuntimeConfig requireCallbackConfig() {
ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationCallbackConfig();
if (config == null || !config.isReady()
|| !StringUtils.hasText(config.getCallbackToken())
|| !StringUtils.hasText(config.getEncodingAesKey())) {
throw new IllegalStateException("微信内容审核回调凭据尚未配置完整");
}
return config;
}
}
@@ -5,8 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -39,8 +39,8 @@ public class AdminSecureIntegrationConfigController {
@GetMapping("/map-runtime")
@RequirePermission("messagehub:config:manage")
public Result<Map<String, String>> getMapRuntimeConfig(HttpServletRequest request) {
adminScopeHelper.getCurrentUser(request);
return Result.success(secureIntegrationConfigService.getMapRuntimeConfig());
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(secureIntegrationConfigService.getMapRuntimeConfig(currentUser));
}
@PostMapping("/map")
@@ -1,6 +1,6 @@
package com.xiaowang.jayucloud.salon.core.modules.system.secure;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -21,8 +21,12 @@ public class SecureConfigEncryptionService {
private final String encodedMasterKey;
public SecureConfigEncryptionService(
@Value("${SALON_SECURE_CONFIG_MASTER_KEY:}") String encodedMasterKey) {
@Autowired
public SecureConfigEncryptionService() {
this(System.getenv("SALON_SECURE_CONFIG_MASTER_KEY"));
}
SecureConfigEncryptionService(String encodedMasterKey) {
this.encodedMasterKey = encodedMasterKey;
}
@@ -14,9 +14,11 @@ public interface SecureIntegrationConfigService {
void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto);
Map<String, String> getMapRuntimeConfig();
Map<String, String> getMapRuntimeConfig(UserDO currentUser);
ModerationRuntimeConfig getModerationRuntimeConfig();
ModerationRuntimeConfig getModerationCallbackConfig();
void migrateLegacyMapConfig();
}
@@ -1,7 +1,7 @@
package com.xiaowang.jayucloud.salon.core.modules.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
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.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO;
@@ -19,8 +19,9 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@@ -33,15 +34,14 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
private static final String MODERATION = "CONTENT_MODERATION";
private static final String SYSTEM = "SYSTEM";
private static final String LEGACY_MAP_MIGRATED = "LEGACY_MAP_MIGRATED";
private static final List<String> MAP_SECRET_KEYS = Arrays.asList(
"TENCENT_WEB_KEY", "AMAP_WEB_KEY", "AMAP_MINI_KEY");
private static final String WECHAT_CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback";
private final SecureIntegrationConfigMapper secureConfigMapper;
private final SystemParameterConfigMapper systemParameterConfigMapper;
private final SecureConfigEncryptionService encryptionService;
private final AdminScopeHelper adminScopeHelper;
private final ContentModerationProperties moderationProperties;
private final WechatMiniClientService wechatMiniClientService;
private final WechatMiniProperties wechatMiniProperties;
@Override
@Transactional
@@ -57,21 +57,30 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
result.setAmapWebKeyConfigured(hasStoredValue(MAP, "AMAP_WEB_KEY"));
result.setAmapMiniKeyConfigured(hasStoredValue(MAP, "AMAP_MINI_KEY"));
String moderationProvider = normalizedProvider(readValue(MODERATION, "PROVIDER", defaultModerationProvider()));
boolean moderationProviderReadable = encryptionService.isConfigured()
|| !hasStoredValue(MODERATION, "PROVIDER");
String moderationProvider = moderationProviderReadable
? normalizedProvider(readValue(MODERATION, "PROVIDER", defaultModerationProvider()))
: "DISABLED";
boolean tokenConfigured = hasStoredValue(MODERATION, "CALLBACK_TOKEN");
boolean aesConfigured = hasStoredValue(MODERATION, "ENCODING_AES_KEY");
boolean callbackConfigured = hasText(readValue(MODERATION, "CALLBACK_URL", ""));
boolean appConfigured = StringUtils.hasText(wechatMiniClientService.getConfiguredAppId());
boolean callbackConfigured = isValidCallbackUrl(readValue(MODERATION, "CALLBACK_URL", ""));
boolean appConfigured = isWechatMiniConfigured();
boolean callbackReady = encryptionService.isConfigured()
&& tokenConfigured && aesConfigured && callbackConfigured && appConfigured;
boolean moderationReady = "MOCK".equals(moderationProvider)
? isMockAllowed()
: "WECHAT".equals(moderationProvider) && tokenConfigured && aesConfigured && callbackConfigured && appConfigured;
: "WECHAT".equals(moderationProvider) && callbackReady;
result.setModerationProvider(moderationProvider);
result.setModerationCallbackUrl(readValue(MODERATION, "CALLBACK_URL", ""));
result.setModerationCallbackTokenConfigured(tokenConfigured);
result.setModerationEncodingAesKeyConfigured(aesConfigured);
result.setModerationCallbackReady(callbackReady);
result.setModerationReady(moderationReady);
result.setWechatMiniAppConfigured(appConfigured);
result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId())
? wechatMiniProperties.getAppId() : "");
result.setMockProviderAllowed(isMockAllowed());
result.setUpdatedAt(latestUpdateTime());
return result;
@@ -120,6 +129,32 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
}
String callbackUrl = StringUtils.trimWhitespace(dto.getModerationCallbackUrl());
String token = resolveUpdatedSecret(MODERATION, "CALLBACK_TOKEN", dto.getModerationCallbackToken(),
dto.getClearModerationCallbackToken());
String aesKey = resolveUpdatedSecret(MODERATION, "ENCODING_AES_KEY", dto.getModerationEncodingAesKey(),
dto.getClearModerationEncodingAesKey());
if (StringUtils.hasText(token) && !token.matches("[A-Za-z0-9]{3,32}")) {
throw new IllegalArgumentException("微信回调 Token 需要为 3-32 位英文字母或数字");
}
if (StringUtils.hasText(aesKey) && !aesKey.matches("[A-Za-z0-9+/]{43}")) {
throw new IllegalArgumentException("微信 EncodingAESKey 需要填写 43 位密钥");
}
String effectiveCallbackUrl = StringUtils.hasText(callbackUrl)
? callbackUrl : readValue(MODERATION, "CALLBACK_URL", "");
if ("WECHAT".equals(provider)) {
if (!StringUtils.hasText(token) || token.length() < 3 || token.length() > 32) {
throw new IllegalArgumentException("微信回调 Token 需要为 3-32 位英文字母或数字");
}
if (!StringUtils.hasText(aesKey) || !aesKey.matches("[A-Za-z0-9+/]{43}")) {
throw new IllegalArgumentException("微信 EncodingAESKey 需要填写 43 位密钥");
}
if (!isValidCallbackUrl(effectiveCallbackUrl)) {
throw new IllegalArgumentException("微信回调地址必须使用公网域名 HTTPS,并精确指向 /api/integration/wechat/content-moderation/callback");
}
if (!isWechatMiniConfigured()) {
throw new IllegalArgumentException("当前环境未同时配置微信小程序 AppID 和 AppSecret,请先完成环境配置");
}
}
if (StringUtils.hasText(callbackUrl)) {
writeValue(MODERATION, "CALLBACK_URL", callbackUrl, false, currentUser.getId());
}
@@ -127,33 +162,13 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
dto.getClearModerationCallbackToken(), currentUser.getId());
updateSecret(MODERATION, "ENCODING_AES_KEY", dto.getModerationEncodingAesKey(),
dto.getClearModerationEncodingAesKey(), currentUser.getId());
String token = resolveUpdatedSecret(MODERATION, "CALLBACK_TOKEN", dto.getModerationCallbackToken(),
dto.getClearModerationCallbackToken());
String aesKey = resolveUpdatedSecret(MODERATION, "ENCODING_AES_KEY", dto.getModerationEncodingAesKey(),
dto.getClearModerationEncodingAesKey());
String effectiveCallbackUrl = StringUtils.hasText(callbackUrl)
? callbackUrl : readValue(MODERATION, "CALLBACK_URL", "");
if ("WECHAT".equals(provider)) {
if (!StringUtils.hasText(token) || token.length() < 3 || token.length() > 32) {
throw new IllegalArgumentException("微信回调 Token 需要填写 3-32 个字符");
}
if (!StringUtils.hasText(aesKey) || !aesKey.matches("[A-Za-z0-9+/]{43}")) {
throw new IllegalArgumentException("微信 EncodingAESKey 需要填写 43 位密钥");
}
if (!StringUtils.hasText(effectiveCallbackUrl) || !effectiveCallbackUrl.startsWith("https://")) {
throw new IllegalArgumentException("微信回调地址必须是公网可访问的 HTTPS 地址");
}
if (!StringUtils.hasText(wechatMiniClientService.getConfiguredAppId())) {
throw new IllegalArgumentException("当前环境未配置微信小程序 AppID,请先完成环境配置");
}
}
writeValue(MODERATION, "PROVIDER", provider, false, currentUser.getId());
}
@Override
@Transactional
public Map<String, String> getMapRuntimeConfig() {
public Map<String, String> getMapRuntimeConfig(UserDO currentUser) {
adminScopeHelper.requirePlatformAdmin(currentUser, "仅平台管理员可以读取地图运行密钥");
migrateLegacyMapConfig();
String provider = upper(readValue(MAP, "PROVIDER", "TENCENT"), "TENCENT");
boolean enabled = Boolean.parseBoolean(readValue(MAP, "ENABLED", "false"));
@@ -168,7 +183,20 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
@Override
public ModerationRuntimeConfig getModerationRuntimeConfig() {
ModerationRuntimeConfig callbackConfig = getModerationCallbackConfig();
if ("WECHAT".equals(callbackConfig.getProvider()) && callbackConfig.isReady()) return callbackConfig;
if ("MOCK".equals(callbackConfig.getProvider()) && isMockAllowed()) {
return new ModerationRuntimeConfig("MOCK", "", "", "", true);
}
return new ModerationRuntimeConfig("DISABLED", "", "", "", false);
}
@Override
public ModerationRuntimeConfig getModerationCallbackConfig() {
if (!encryptionService.isConfigured()) {
if (!hasStoredValue(MODERATION, "PROVIDER") && isMockAllowed()) {
return new ModerationRuntimeConfig("MOCK", "", "", "", true);
}
return new ModerationRuntimeConfig("DISABLED", "", "", "", false);
}
String provider = normalizedProvider(readValue(MODERATION, "PROVIDER", defaultModerationProvider()));
@@ -176,10 +204,8 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
String token = readValue(MODERATION, "CALLBACK_TOKEN", "");
String aesKey = readValue(MODERATION, "ENCODING_AES_KEY", "");
boolean allowedMock = !"MOCK".equals(provider) || isMockAllowed();
boolean configured = "MOCK".equals(provider)
? isMockAllowed()
: "WECHAT".equals(provider) && StringUtils.hasText(token) && StringUtils.hasText(aesKey)
&& StringUtils.hasText(callbackUrl) && StringUtils.hasText(wechatMiniClientService.getConfiguredAppId());
boolean configured = StringUtils.hasText(token) && StringUtils.hasText(aesKey)
&& isValidCallbackUrl(callbackUrl) && isWechatMiniConfigured();
if (!allowedMock) provider = "DISABLED";
return new ModerationRuntimeConfig(provider, callbackUrl, token, aesKey, configured);
}
@@ -202,8 +228,14 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
moveLegacyValue(legacyByKey, "AMAP_MINI_KEY", MAP, "AMAP_MINI_KEY", true);
SystemParameterConfigDO oldProvider = legacyByKey.get("MAP_PROVIDER");
if (oldProvider != null) {
String enabled = Integer.valueOf(1).equals(oldProvider.getEnabled()) ? "true" : "false";
writeValue(MAP, "ENABLED", enabled, false, null);
String provider = upper(oldProvider.getConfigValue(), "TENCENT");
String activeKeyName = "AMAP".equals(provider) ? "AMAP_WEB_KEY" : "TENCENT_MAP_KEY";
SystemParameterConfigDO activeKey = legacyByKey.get(activeKeyName);
boolean enabled = Integer.valueOf(1).equals(oldProvider.getEnabled())
&& activeKey != null
&& Integer.valueOf(1).equals(activeKey.getEnabled())
&& StringUtils.hasText(activeKey.getConfigValue());
writeValue(MAP, "ENABLED", String.valueOf(enabled), false, null);
}
for (SystemParameterConfigDO legacy : legacyConfigs) {
legacy.setConfigValue("");
@@ -298,6 +330,34 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
return isMockAllowed() ? "MOCK" : "DISABLED";
}
private boolean isWechatMiniConfigured() {
return StringUtils.hasText(wechatMiniProperties.getAppId())
&& StringUtils.hasText(wechatMiniProperties.getAppSecret());
}
private boolean isValidCallbackUrl(String value) {
if (!StringUtils.hasText(value)) return false;
try {
URI uri = new URI(value.trim());
String host = uri.getHost();
if (!"https".equalsIgnoreCase(uri.getScheme()) || !StringUtils.hasText(host)
|| uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null
|| !WECHAT_CALLBACK_PATH.equals(uri.getRawPath())) {
return false;
}
String normalizedHost = host.toLowerCase(Locale.ROOT);
if (normalizedHost.endsWith(".")) normalizedHost = normalizedHost.substring(0, normalizedHost.length() - 1);
if ("localhost".equals(normalizedHost) || normalizedHost.endsWith(".localhost")
|| normalizedHost.endsWith(".local") || normalizedHost.endsWith(".internal")
|| normalizedHost.contains(":") || normalizedHost.matches("\\d{1,3}(\\.\\d{1,3}){3}")) {
return false;
}
return uri.getPort() == -1 || uri.getPort() == 443;
} catch (URISyntaxException exception) {
return false;
}
}
private String normalizedProvider(String value) {
return upper(value, "DISABLED");
}
@@ -17,8 +17,10 @@ public class SecureIntegrationConfigVO {
private String moderationCallbackUrl;
private Boolean moderationCallbackTokenConfigured;
private Boolean moderationEncodingAesKeyConfigured;
private Boolean moderationCallbackReady;
private Boolean moderationReady;
private Boolean wechatMiniAppConfigured;
private String wechatMiniAppId;
private Boolean mockProviderAllowed;
private Boolean encryptionKeyConfigured;