From 36e3b046a08bcf91c2eabf4098a50047b62d2da1 Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Thu, 29 Oct 2026 05:12:09 -0400 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=AE=A2=E6=88=B7=E7=AB=AF?= =?UTF-8?q?=E7=8E=B0=E5=9C=A8=E6=94=AF=E6=8C=81=E7=8B=AC=E7=AB=8B=E4=BF=A1?= =?UTF-8?q?=E4=BB=BB=20nginx=20=E7=9A=84=20TLS=20=E8=AF=81=E4=B9=A6?= =?UTF-8?q?=EF=BC=8C=E4=BF=9D=E7=95=99=E5=9F=9F=E5=90=8D=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=EF=BC=8C=E4=B8=8D=E4=BF=AE=E6=94=B9=E5=85=A8=E5=B1=80=E4=BF=A1?= =?UTF-8?q?=E4=BB=BB=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/rental/topup-payment.md | 14 ++++ .../src/main/resources/application-rental.yml | 3 + .../system/rental/RentalPaymentClient.java | 38 +++++++--- .../rental/RentalPaymentProperties.java | 4 + .../ruoyi/system/rental/RentalPaymentTls.java | 67 +++++++++++++++++ .../system/rental/RentalPaymentTlsTest.java | 75 +++++++++++++++++++ 6 files changed, 191 insertions(+), 10 deletions(-) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentTls.java create mode 100644 ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalPaymentTlsTest.java diff --git a/docs/rental/topup-payment.md b/docs/rental/topup-payment.md index 267a152..c489d7d 100644 --- a/docs/rental/topup-payment.md +++ b/docs/rental/topup-payment.md @@ -44,6 +44,20 @@ RENT_PAYMENT_MAINNET_MAX_AMOUNT=10000.00 ## 业务流程与资金安全 +### 自签HTTPS支付服务 + +支付客户端支持独立信任证书,无需修改全局JVM信任库: + +```properties +RENT_PAYMENT_NILE_TLS_CERTIFICATE=file:/etc/nginx/certs/fullchain.pem +# 主网若需要独立证书,可另外配置: +RENT_PAYMENT_MAINNET_TLS_CERTIFICATE=file:/etc/nginx/certs/fullchain.pem +``` + +对应 `rental.payment.nile.tls-certificate-location` / `mainnet.tls-certificate-location`。文件须为经过管理员核对的X.509证书或CA证书(PEM/DER),不能使用privkey.pem或支付RSA公钥。运行后端的用户须有读取权限;容器需挂载文件。证书SAN必须包含支付域名或IP,例如 `IP:192.168.3.103`。修改后重启服务,原充值单会后台重试。 + +本功能合并当前JVM默认信任锚与指定证书,仅作用于支付HTTP客户端,保留证书有效期和域名校验。请移除此前仅为自签支付服务添加的全局 `-Djavax.net.ssl.trustStore...` 参数(如其他业务仍需要自定义全局信任库,应保留包含完整CA的合并库),恢复TronGrid等调用使用的正常默认CA。不会修复证书域名不匹配、过期或错误代理地址。 + 1. 登录用户创建充值,服务端校验账户归属、ACTIVE 状态、网络、金额上下限和最多两位小数;以 `user_id + client_request_no` 幂等落库。 2. 在数据库事务外调用项目支付加密协议,明文业务参数包含 `network=NILE/MAINNET`、`amount_currency=USDT`,避免充值金额被业务币汇率转换。未传币种的原支付客户端继续使用原汇率逻辑。 3. 展示真实支付地址、准确金额、二维码、倒计时和收银台链接。每笔充值使用 `rent:<充值单号>` 支付用户标识,隔离支付金额槽位;因此需要持续补充或维护支付钱包池容量。 diff --git a/ruoyi-admin/src/main/resources/application-rental.yml b/ruoyi-admin/src/main/resources/application-rental.yml index 0cbc9cb..2d8b3b5 100644 --- a/ruoyi-admin/src/main/resources/application-rental.yml +++ b/ruoyi-admin/src/main/resources/application-rental.yml @@ -17,6 +17,8 @@ rental: api-key: ${RENT_PAYMENT_NILE_API_KEY:} api-secret: ${RENT_PAYMENT_NILE_API_SECRET:} rsa-public-key-location: ${RENT_PAYMENT_NILE_PUBLIC_KEY:} + # nginx的TLS证书或CA证书;与支付应用RSA公钥不同,仅影响支付客户端。 + tls-certificate-location: ${RENT_PAYMENT_NILE_TLS_CERTIFICATE:} notify-url: ${RENT_PAYMENT_NILE_NOTIFY_URL:} min-amount: ${RENT_PAYMENT_NILE_MIN_AMOUNT:1.00} max-amount: ${RENT_PAYMENT_NILE_MAX_AMOUNT:10000.00} @@ -26,6 +28,7 @@ rental: api-key: ${RENT_PAYMENT_MAINNET_API_KEY:} api-secret: ${RENT_PAYMENT_MAINNET_API_SECRET:} rsa-public-key-location: ${RENT_PAYMENT_MAINNET_PUBLIC_KEY:} + tls-certificate-location: ${RENT_PAYMENT_MAINNET_TLS_CERTIFICATE:} notify-url: ${RENT_PAYMENT_MAINNET_NOTIFY_URL:} min-amount: ${RENT_PAYMENT_MAINNET_MIN_AMOUNT:1.00} max-amount: ${RENT_PAYMENT_MAINNET_MAX_AMOUNT:10000.00} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java index 032f30a..808c167 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java @@ -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 call(Map 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 result = json.readValue(RentalHttp.body(response), new TypeReference>() { }); + Map result = json.readValue(RentalHttp.body(response), new TypeReference>() { + }); 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) result.get("data"); } } - /** RSA验签使用项目既有参数规范化规则,不使用租赁HMAC或浏览器跳转结果。 */ + + /** + * RSA验签使用项目既有参数规范化规则,不使用租赁HMAC或浏览器跳转结果。 + */ public boolean verify(Map order, Map 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; + } } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentProperties.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentProperties.java index ff1fa3d..469f573 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentProperties.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentProperties.java @@ -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"); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentTls.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentTls.java new file mode 100644 index 0000000..e0de79f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentTls.java @@ -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 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信任管理器"); + } +} diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalPaymentTlsTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalPaymentTlsTest.java new file mode 100644 index 0000000..dfa7e39 --- /dev/null +++ b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalPaymentTlsTest.java @@ -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())); + } +}