支付客户端现在支持独立信任 nginx 的 TLS 证书,保留域名校验,不修改全局信任库

This commit is contained in:
lu7213 committed 2026-10-29 05:12:09 -04:00
1 parent d88ad8996a
commit 36e3b046a0
6 files changed
+191 -10

No files matched your search

@@ -1,33 +1,39 @@
package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.security.RsaKeyUtil;
import com.ruoyi.system.security.SecureClient;
import com.ruoyi.system.service.PaymentSignatureService;
import okhttp3.*;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.ruoyi.system.service.PaymentSignatureService;
/** 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。 */
import static com.ruoyi.system.rental.RentalValues.*;
/**
* 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。
*/
@Component
public class RentalPaymentClient {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RentalPaymentClient.class);
private final ObjectMapper json;
private final RentalPaymentProperties properties;
private final ResourceLoader resources;
public RentalPaymentClient(ObjectMapper json, RentalPaymentProperties properties, ResourceLoader resources) {
this.json = json.copy().enable(com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
this.properties = properties;
this.resources = resources;
}
public String publicKey(RentalPaymentProperties.Channel channel) throws Exception {
// 不打印资源路径;配置误填密钥正文或含口令URL时同样不会泄露。
String location = channel.getRsaPublicKeyLocation();
@@ -47,6 +53,7 @@ public class RentalPaymentClient {
return pem;
}
}
public Map<String, Object> call(Map<String, Object> order, String operation) throws Exception {
RentalPaymentProperties.Channel channel = properties.channel(text(order, "network"));
require(properties.isEnabled() && channel.isEnabled(), "支付充值尚未启用");
@@ -60,26 +67,35 @@ public class RentalPaymentClient {
}
Object encrypted = SecureClient.encrypt(text(order, "payment_api_key"), channel.getApiSecret(),
RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")), parameters);
OkHttpClient client = new OkHttpClient.Builder()
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(properties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS)
.readTimeout(properties.getReadTimeoutMs(), TimeUnit.MILLISECONDS)
.callTimeout(30, TimeUnit.SECONDS).followRedirects(false).followSslRedirects(false)
.retryOnConnectionFailure(false).build();
Request request = new Request.Builder().url(text(order, "payment_base_url") + "/api/v1/order/" + operation)
.retryOnConnectionFailure(false);
RentalPaymentTls.configure(builder, channel.getTlsCertificateLocation(), resources);
LOG.info("支付TLS配置 network={} additionalCertificateConfigured={} hostnameVerification=enabled",
text(order, "network"), channel.getTlsCertificateLocation() != null && !channel.getTlsCertificateLocation().trim().isEmpty());
OkHttpClient client = builder.build();
String url = text(order, "payment_base_url") + "/api/v1/order/" + operation;
Request request = new Request.Builder().url(url)
.post(RequestBody.create(MediaType.parse("application/json"), json.writeValueAsString(encrypted))).build();
long started = System.nanoTime();
LOG.info("充值支付请求开始 topupNo={} network={} operation={}", text(order, "topup_no"), text(order, "network"), operation);
LOG.info("充值支付请求开始 url {} topupNo={} network={} operation={}",url, text(order, "topup_no"), text(order, "network"), operation);
try (Response response = client.newCall(request).execute()) {
LOG.info("充值支付HTTP响应 topupNo={} operation={} httpStatus={} elapsedMs={}",
text(order, "topup_no"), operation, response.code(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
Map<String, Object> result = json.readValue(RentalHttp.body(response), new TypeReference<Map<String, Object>>() { });
Map<String, Object> result = json.readValue(RentalHttp.body(response), new TypeReference<Map<String, Object>>() {
});
LOG.info("充值支付业务响应 topupNo={} operation={} businessCode={} dataObject={}",
text(order, "topup_no"), operation, number(result, "code"), result.get("data") instanceof Map);
require(number(result, "code") == 200 && result.get("data") instanceof Map, "支付请求未成功,请稍后核对");
return (Map<String, Object>) result.get("data");
}
}
/** RSA验签使用项目既有参数规范化规则,不使用租赁HMAC或浏览器跳转结果。 */
/**
* RSA验签使用项目既有参数规范化规则,不使用租赁HMAC或浏览器跳转结果。
*/
public boolean verify(Map<String, Object> order, Map<String, Object> payload, String key, String signature) {
try {
if (!text(order, "payment_api_key").equals(key) || signature == null) return false;
@@ -87,6 +103,8 @@ public class RentalPaymentClient {
verifier.initVerify(RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")));
verifier.update(PaymentSignatureService.canonicalText(payload).getBytes(StandardCharsets.UTF_8));
return verifier.verify(Base64.getDecoder().decode(signature));
} catch (Exception exception) { return false; }
} catch (Exception exception) {
return false;
}
}
}
@@ -84,6 +84,10 @@ public class RentalPaymentProperties {
private String apiKey = "";
private String apiSecret = "";
private String rsaPublicKeyLocation = "";
/** 支付服务TLS信任证书(PEM/DER),不是支付应用RSA公钥;空值使用JVM默认信任。 */
private String tlsCertificateLocation = "";
public String getTlsCertificateLocation() { return tlsCertificateLocation; }
public void setTlsCertificateLocation(String value) { tlsCertificateLocation = value; }
private String notifyUrl = "";
private BigDecimal minAmount = new BigDecimal("1.00");
private BigDecimal maxAmount = new BigDecimal("10000.00");
@@ -0,0 +1,67 @@
package com.ruoyi.system.rental;
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;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import org.springframework.core.io.ResourceLoader;
/** 支付专用TLS上下文。只追加管理员指定的信任证书,不修改全局SSLContext或域名校验。 */
final class RentalPaymentTls {
private RentalPaymentTls() { }
static void configure(OkHttpClient.Builder builder, String location, ResourceLoader resources) throws Exception {
if (location == null || location.trim().isEmpty()) { return; }
// 只允许本地或类路径证书,避免为建立信任而先请求不可信远端。
RentalValues.require(location.startsWith("file:") || location.startsWith("classpath:"),
"支付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) {
RentalValues.require(bytes.size() + count <= 262144, "支付TLS证书文件超过256KiB");
bytes.write(buffer, 0, count);
}
certificates = CertificateFactory.getInstance("X.509")
.generateCertificates(new ByteArrayInputStream(bytes.toByteArray()));
}
RentalValues.require(!certificates.isEmpty(), "支付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) certificate).checkValidity();
combined.setCertificateEntry("payment-" + index++, certificate);
}
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(combined);
X509TrustManager trust = manager(factory);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{trust}, null);
// OkHttp仍执行默认HostnameVerifier,证书SAN必须匹配请求域名/IP。
builder.sslSocketFactory(context.getSocketFactory(), trust);
}
private static X509TrustManager manager(TrustManagerFactory factory) {
for (TrustManager manager : factory.getTrustManagers()) {
if (manager instanceof X509TrustManager) { return (X509TrustManager) manager; }
}
throw new IllegalStateException("JVM未提供X509信任管理器");
}
}
@@ -0,0 +1,75 @@
package com.ruoyi.system.rental;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Test;
import org.springframework.core.io.DefaultResourceLoader;
import static org.junit.Assert.*;
/** 本地自签TLS握手测试:不访问外网、不更改JVM全局信任配置。 */
public class RentalPaymentTlsTest {
@Test public void trustsConfiguredCertificateButStillChecksHostname() throws Exception {
Path directory = Files.createTempDirectory("rental-tls-test-");
Path keys = directory.resolve("server.p12");
Path pem = directory.resolve("server.pem");
HttpsServer server = null;
try {
String binary = System.getProperty("os.name").toLowerCase(java.util.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); }
String executable = tool.toString();
Process process = new ProcessBuilder(executable, "-genkeypair", "-alias", "test", "-keyalg", "RSA",
"-keysize", "2048", "-validity", "1", "-dname", "CN=localhost", "-ext", "SAN=dns:localhost",
"-keystore", keys.toString(), "-storetype", "PKCS12", "-storepass", "test-pass-123", "-keypass", "test-pass-123")
.redirectErrorStream(true).redirectOutput(directory.resolve("keytool.log").toFile()).start();
assertTrue(process.waitFor(30, TimeUnit.SECONDS));
assertEquals(0, process.exitValue());
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream input = Files.newInputStream(keys)) { keyStore.load(input, "test-pass-123".toCharArray()); }
X509Certificate certificate = (X509Certificate) keyStore.getCertificate("test");
Files.write(pem, certificate.getEncoded());
KeyManagerFactory managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
managers.init(keyStore, "test-pass-123".toCharArray());
SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(managers.getKeyManagers(), null, null);
server = HttpsServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
server.setHttpsConfigurator(new HttpsConfigurator(ssl));
server.createContext("/", exchange -> { exchange.sendResponseHeaders(200, -1); exchange.close(); });
server.start();
int port = server.getAddress().getPort();
OkHttpClient.Builder builder = new OkHttpClient.Builder().callTimeout(5, TimeUnit.SECONDS);
RentalPaymentTls.configure(builder, pem.toUri().toString(), new DefaultResourceLoader());
OkHttpClient trusted = builder.build();
try (Response response = trusted.newCall(new Request.Builder().url("https://localhost:" + port).build()).execute()) {
assertEquals(200, response.code());
}
assertThrows(javax.net.ssl.SSLPeerUnverifiedException.class, () -> {
try (Response response = trusted.newCall(new Request.Builder().url("https://127.0.0.1:" + port).build()).execute()) { fail("hostname verification bypassed"); }
});
OkHttpClient unchanged = new OkHttpClient.Builder().callTimeout(5, TimeUnit.SECONDS).build();
assertThrows(javax.net.ssl.SSLHandshakeException.class, () -> {
try (Response response = unchanged.newCall(new Request.Builder().url("https://localhost:" + port).build()).execute()) { fail("global trust modified"); }
});
} finally {
if (server != null) { server.stop(0); }
Files.deleteIfExists(pem); Files.deleteIfExists(keys);
Files.deleteIfExists(directory.resolve("keytool.log")); Files.deleteIfExists(directory);
}
}
@Test public void rejectsRemoteCertificateSources() {
assertThrows(IllegalArgumentException.class, () -> RentalPaymentTls.configure(
new OkHttpClient.Builder(), "https://untrusted.example/cert.pem", new DefaultResourceLoader()));
}
}