diff --git a/docs/chain-executor.md b/docs/chain-executor.md index aa7e5db..73d8a89 100644 --- a/docs/chain-executor.md +++ b/docs/chain-executor.md @@ -51,9 +51,12 @@ | `CHAIN_EXECUTOR_ENABLED` | 启用双通道时设 `true` | | `CHAIN_EXECUTOR_BASE_URL` | 无尾斜杠/路径的 HTTP 或 HTTPS 根地址,例如 `http://192.168.10.20:9088` 或 `https://192.168.10.20:9088` | | `CHAIN_EXECUTOR_TOKEN` | 独立服务凭据,与执行器一致 | +| `CHAIN_EXECUTOR_TLS_CERTIFICATE` | HTTPS时可配置 `file:/.../rent-cert.pem` 或 `classpath:` 证书/CA;HTTP忽略 | 执行器自身只提供 HTTP。支付后端可使用 HTTP 直连,或使用 HTTPS 调用同机 Nginx,由 Nginx 转发到回环 HTTP。 生产跨机器调用推荐 HTTPS;证书 SAN 必须包含配置的内网 IP,支付后端 JVM 需信任签发 CA,禁止关闭证书校验。 +HTTPS使用自签或内部CA时,建议设置 `CHAIN_EXECUTOR_TLS_CERTIFICATE=file:/etc/nginx/certs/rent-cert.pem`。 +支付系统通过独立Java TLS上下文追加该证书,并保留JVM默认证书和主机名校验,不需要配置全局 trustStore。 只支持 IPv4 字面地址,不接受域名,避免 DNS 重绑定和意外公网解析。Nginx 示例见 `usdt-chain-executor/nginx/usdt-chain-executor.conf`。 diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index b322c92..bf3dd5b 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -4,6 +4,8 @@ chain: enabled: ${CHAIN_EXECUTOR_ENABLED:true} url: ${CHAIN_EXECUTOR_BASE_URL:https://192.168.3.103:9088} token: ${CHAIN_EXECUTOR_TOKEN:6hsYMjzuXPXYFd8SYRa45YnA7LyctJYD} + # HTTPS模式下追加信任的执行器证书或CA证书,仅允许file:/或classpath:资源。 + tls-certificate-location: ${CHAIN_EXECUTOR_TLS_CERTIFICATE:file:/etc/nginx/certs/rent-cert.pem}} # 项目相关配置 ruoyi: diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java index 56feb33..4a679f4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java @@ -8,10 +8,12 @@ import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestClientResponseException; +import org.springframework.core.io.DefaultResourceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; +import javax.net.ssl.HttpsURLConnection; import java.net.URI; /** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */ @@ -24,20 +26,29 @@ public class ChainExecutorClient { private String url; @Value("${chain.executor.token:}") private String token; - private final RestTemplate http; + @Value("${chain.executor.tls-certificate-location:}") + private String tlsCertificateLocation; + private RestTemplate http; public ChainExecutorClient() { + http = createHttp(null); + } + + private RestTemplate createHttp(final javax.net.ssl.SSLSocketFactory sslSocketFactory) { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory() { @Override protected void prepareConnection(java.net.HttpURLConnection connection, String method) throws java.io.IOException { super.prepareConnection(connection, method); connection.setInstanceFollowRedirects(false); + if (sslSocketFactory != null && connection instanceof HttpsURLConnection) { + ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory); + } } }; factory.setConnectTimeout(1500); factory.setReadTimeout(2500); - http = new RestTemplate(factory); + return new RestTemplate(factory); } @PostConstruct @@ -54,6 +65,14 @@ public class ChainExecutorClient { || token == null || token.length() < 32) { throw new IllegalArgumentException("内网执行服务需配置内网 HTTP/HTTPS 根地址和至少32位服务凭据"); } + if ("https".equals(target.getScheme())) { + try { + http = createHttp(ChainExecutorTls.socketFactory(tlsCertificateLocation, new DefaultResourceLoader())); + log.info("已加载内网链上执行器HTTPS信任证书"); + } catch (Exception invalidCertificate) { + throw new IllegalArgumentException("内网链上执行器TLS证书加载失败,请检查本地证书路径、格式和有效期"); + } + } log.info("内网链上执行通道已启用,开始验证执行器服务,传输协议={}", target.getScheme().toUpperCase()); try { requireResponse("/internal/v1/connectivity", "CONNECTED", "联通测试"); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorTls.java b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorTls.java new file mode 100644 index 0000000..d6bfe92 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorTls.java @@ -0,0 +1,71 @@ +package com.ruoyi.system.chain; + +import org.springframework.core.io.ResourceLoader; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collection; + +/** 执行器专用TLS信任上下文;追加本地证书,不修改JVM全局信任和主机名校验。 */ +final class ChainExecutorTls { + private ChainExecutorTls() { } + + static SSLSocketFactory socketFactory(String location, ResourceLoader resources) throws Exception { + if (location == null || location.trim().isEmpty()) { + return (SSLSocketFactory) SSLSocketFactory.getDefault(); + } + if (!location.startsWith("file:") && !location.startsWith("classpath:")) { + throw new IllegalArgumentException("执行器TLS证书必须使用file:或classpath:资源路径"); + } + Collection certificates; + try (InputStream input = resources.getResource(location).getInputStream()) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int count; + while ((count = input.read(buffer)) != -1) { + if (bytes.size() + count > 262144) throw new IllegalArgumentException("执行器TLS证书超过256KiB"); + bytes.write(buffer, 0, count); + } + certificates = CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(bytes.toByteArray())); + } + if (certificates.isEmpty()) throw new IllegalArgumentException("执行器TLS证书文件不包含X.509证书"); + + TrustManagerFactory defaults = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + defaults.init((KeyStore) null); + KeyStore combined = KeyStore.getInstance(KeyStore.getDefaultType()); + combined.load(null, null); + int index = 0; + for (X509Certificate certificate : manager(defaults).getAcceptedIssuers()) { + combined.setCertificateEntry("default-" + index++, certificate); + } + for (Certificate certificate : certificates) { + X509Certificate x509 = (X509Certificate) certificate; + x509.checkValidity(); + combined.setCertificateEntry("executor-" + index++, x509); + } + TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustFactory.init(combined); + X509TrustManager trust = manager(trustFactory); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new TrustManager[]{trust}, null); + return context.getSocketFactory(); + } + + private static X509TrustManager manager(TrustManagerFactory factory) { + for (TrustManager manager : factory.getTrustManagers()) { + if (manager instanceof X509TrustManager) return (X509TrustManager) manager; + } + throw new IllegalStateException("JVM未提供X509信任管理器"); + } +} diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorClientTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorClientTest.java index 8c133ac..cdae7f5 100644 --- a/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorClientTest.java +++ b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutorClientTest.java @@ -3,6 +3,14 @@ package com.ruoyi.system.chain; import org.junit.Test; import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Locale; +import java.util.concurrent.TimeUnit; +import org.springframework.core.io.DefaultResourceLoader; + +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; @@ -25,11 +33,45 @@ public class ChainExecutorClientTest { } } + @Test + public void loadsLocalExecutorCertificateWithoutChangingGlobalTrust() throws Exception { + Path directory = Files.createTempDirectory("executor-tls-"); + Path keys = directory.resolve("server.p12"); + Path certificate = directory.resolve("server.pem"); + try { + String binary = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win") + ? "keytool.exe" : "keytool"; + Path tool = Paths.get(System.getProperty("java.home"), "bin", binary); + if (!Files.exists(tool)) tool = Paths.get(System.getProperty("java.home"), "..", "bin", binary); + Process generate = new ProcessBuilder(tool.toString(), "-genkeypair", "-alias", "executor", "-keyalg", "RSA", + "-keysize", "2048", "-validity", "1", "-dname", "CN=127.0.0.1", "-ext", "SAN=ip:127.0.0.1", + "-keystore", keys.toString(), "-storetype", "PKCS12", "-storepass", "test-pass-123") + .redirectErrorStream(true).redirectOutput(directory.resolve("generate.log").toFile()).start(); + if (!generate.waitFor(30, TimeUnit.SECONDS) || generate.exitValue() != 0) fail("测试证书生成失败"); + Process export = new ProcessBuilder(tool.toString(), "-exportcert", "-rfc", "-alias", "executor", + "-keystore", keys.toString(), "-storetype", "PKCS12", "-storepass", "test-pass-123", + "-file", certificate.toString()).redirectErrorStream(true) + .redirectOutput(directory.resolve("export.log").toFile()).start(); + if (!export.waitFor(30, TimeUnit.SECONDS) || export.exitValue() != 0) fail("测试证书导出失败"); + assertNotNull(ChainExecutorTls.socketFactory(certificate.toUri().toString(), new DefaultResourceLoader())); + } finally { + Files.deleteIfExists(certificate); Files.deleteIfExists(keys); + Files.deleteIfExists(directory.resolve("generate.log")); Files.deleteIfExists(directory.resolve("export.log")); + Files.deleteIfExists(directory); + } + } + + @Test(expected = IllegalArgumentException.class) + public void rejectsRemoteCertificateLocation() throws Exception { + ChainExecutorTls.socketFactory("https://untrusted.example/cert.pem", new DefaultResourceLoader()); + } + private ChainExecutorClient client(String url) throws Exception { ChainExecutorClient client = new ChainExecutorClient(); set(client, "enabled", true); set(client, "url", url); set(client, "token", "test-only-token-012345678901234567890"); + set(client, "tlsCertificateLocation", ""); return client; }