https访问方式修改

This commit is contained in:
lu7213 committed 2026-11-06 21:47:17 -05:00
1 parent 7202f0783a
commit 21a23c9f55
5 files changed
+139 -2

No files matched your search

@@ -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", "联通测试");
@@ -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<? extends Certificate> 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信任管理器");
}
}
@@ -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;
}