支付客户端现在支持独立信任 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

+14
View File
@@ -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` 幂等落库。 1. 登录用户创建充值,服务端校验账户归属、ACTIVE 状态、网络、金额上下限和最多两位小数;以 `user_id + client_request_no` 幂等落库。
2. 在数据库事务外调用项目支付加密协议,明文业务参数包含 `network=NILE/MAINNET`、`amount_currency=USDT`,避免充值金额被业务币汇率转换。未传币种的原支付客户端继续使用原汇率逻辑。 2. 在数据库事务外调用项目支付加密协议,明文业务参数包含 `network=NILE/MAINNET`、`amount_currency=USDT`,避免充值金额被业务币汇率转换。未传币种的原支付客户端继续使用原汇率逻辑。
3. 展示真实支付地址、准确金额、二维码、倒计时和收银台链接。每笔充值使用 `rent:<充值单号>` 支付用户标识,隔离支付金额槽位;因此需要持续补充或维护支付钱包池容量。 3. 展示真实支付地址、准确金额、二维码、倒计时和收银台链接。每笔充值使用 `rent:<充值单号>` 支付用户标识,隔离支付金额槽位;因此需要持续补充或维护支付钱包池容量。
@@ -17,6 +17,8 @@ rental:
api-key: ${RENT_PAYMENT_NILE_API_KEY:} api-key: ${RENT_PAYMENT_NILE_API_KEY:}
api-secret: ${RENT_PAYMENT_NILE_API_SECRET:} api-secret: ${RENT_PAYMENT_NILE_API_SECRET:}
rsa-public-key-location: ${RENT_PAYMENT_NILE_PUBLIC_KEY:} 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:} notify-url: ${RENT_PAYMENT_NILE_NOTIFY_URL:}
min-amount: ${RENT_PAYMENT_NILE_MIN_AMOUNT:1.00} min-amount: ${RENT_PAYMENT_NILE_MIN_AMOUNT:1.00}
max-amount: ${RENT_PAYMENT_NILE_MAX_AMOUNT:10000.00} max-amount: ${RENT_PAYMENT_NILE_MAX_AMOUNT:10000.00}
@@ -26,6 +28,7 @@ rental:
api-key: ${RENT_PAYMENT_MAINNET_API_KEY:} api-key: ${RENT_PAYMENT_MAINNET_API_KEY:}
api-secret: ${RENT_PAYMENT_MAINNET_API_SECRET:} api-secret: ${RENT_PAYMENT_MAINNET_API_SECRET:}
rsa-public-key-location: ${RENT_PAYMENT_MAINNET_PUBLIC_KEY:} rsa-public-key-location: ${RENT_PAYMENT_MAINNET_PUBLIC_KEY:}
tls-certificate-location: ${RENT_PAYMENT_MAINNET_TLS_CERTIFICATE:}
notify-url: ${RENT_PAYMENT_MAINNET_NOTIFY_URL:} notify-url: ${RENT_PAYMENT_MAINNET_NOTIFY_URL:}
min-amount: ${RENT_PAYMENT_MAINNET_MIN_AMOUNT:1.00} min-amount: ${RENT_PAYMENT_MAINNET_MIN_AMOUNT:1.00}
max-amount: ${RENT_PAYMENT_MAINNET_MAX_AMOUNT:10000.00} max-amount: ${RENT_PAYMENT_MAINNET_MAX_AMOUNT:10000.00}
@@ -1,33 +1,39 @@
package com.ruoyi.system.rental; package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.security.RsaKeyUtil; import com.ruoyi.system.security.RsaKeyUtil;
import com.ruoyi.system.security.SecureClient; import com.ruoyi.system.security.SecureClient;
import com.ruoyi.system.service.PaymentSignatureService;
import okhttp3.*; import okhttp3.*;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.Signature; import java.security.Signature;
import java.util.Base64; import java.util.Base64;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.ruoyi.system.service.PaymentSignatureService;
/** 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。 */ import static com.ruoyi.system.rental.RentalValues.*;
/**
* 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。
*/
@Component @Component
public class RentalPaymentClient { public class RentalPaymentClient {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RentalPaymentClient.class); private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RentalPaymentClient.class);
private final ObjectMapper json; private final ObjectMapper json;
private final RentalPaymentProperties properties; private final RentalPaymentProperties properties;
private final ResourceLoader resources; private final ResourceLoader resources;
public RentalPaymentClient(ObjectMapper json, RentalPaymentProperties properties, 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.json = json.copy().enable(com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
this.properties = properties; this.properties = properties;
this.resources = resources; this.resources = resources;
} }
public String publicKey(RentalPaymentProperties.Channel channel) throws Exception { public String publicKey(RentalPaymentProperties.Channel channel) throws Exception {
// 不打印资源路径;配置误填密钥正文或含口令URL时同样不会泄露。 // 不打印资源路径;配置误填密钥正文或含口令URL时同样不会泄露。
String location = channel.getRsaPublicKeyLocation(); String location = channel.getRsaPublicKeyLocation();
@@ -47,6 +53,7 @@ public class RentalPaymentClient {
return pem; return pem;
} }
} }
public Map<String, Object> call(Map<String, Object> order, String operation) throws Exception { public Map<String, Object> call(Map<String, Object> order, String operation) throws Exception {
RentalPaymentProperties.Channel channel = properties.channel(text(order, "network")); RentalPaymentProperties.Channel channel = properties.channel(text(order, "network"));
require(properties.isEnabled() && channel.isEnabled(), "支付充值尚未启用"); require(properties.isEnabled() && channel.isEnabled(), "支付充值尚未启用");
@@ -60,26 +67,35 @@ public class RentalPaymentClient {
} }
Object encrypted = SecureClient.encrypt(text(order, "payment_api_key"), channel.getApiSecret(), Object encrypted = SecureClient.encrypt(text(order, "payment_api_key"), channel.getApiSecret(),
RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")), parameters); RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")), parameters);
OkHttpClient client = new OkHttpClient.Builder() OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(properties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS) .connectTimeout(properties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS)
.readTimeout(properties.getReadTimeoutMs(), TimeUnit.MILLISECONDS) .readTimeout(properties.getReadTimeoutMs(), TimeUnit.MILLISECONDS)
.callTimeout(30, TimeUnit.SECONDS).followRedirects(false).followSslRedirects(false) .callTimeout(30, TimeUnit.SECONDS).followRedirects(false).followSslRedirects(false)
.retryOnConnectionFailure(false).build(); .retryOnConnectionFailure(false);
Request request = new Request.Builder().url(text(order, "payment_base_url") + "/api/v1/order/" + operation) 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(); .post(RequestBody.create(MediaType.parse("application/json"), json.writeValueAsString(encrypted))).build();
long started = System.nanoTime(); 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()) { try (Response response = client.newCall(request).execute()) {
LOG.info("充值支付HTTP响应 topupNo={} operation={} httpStatus={} elapsedMs={}", LOG.info("充值支付HTTP响应 topupNo={} operation={} httpStatus={} elapsedMs={}",
text(order, "topup_no"), operation, response.code(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)); 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={}", LOG.info("充值支付业务响应 topupNo={} operation={} businessCode={} dataObject={}",
text(order, "topup_no"), operation, number(result, "code"), result.get("data") instanceof Map); text(order, "topup_no"), operation, number(result, "code"), result.get("data") instanceof Map);
require(number(result, "code") == 200 && result.get("data") instanceof Map, "支付请求未成功,请稍后核对"); require(number(result, "code") == 200 && result.get("data") instanceof Map, "支付请求未成功,请稍后核对");
return (Map<String, Object>) result.get("data"); 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) { public boolean verify(Map<String, Object> order, Map<String, Object> payload, String key, String signature) {
try { try {
if (!text(order, "payment_api_key").equals(key) || signature == null) return false; 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.initVerify(RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")));
verifier.update(PaymentSignatureService.canonicalText(payload).getBytes(StandardCharsets.UTF_8)); verifier.update(PaymentSignatureService.canonicalText(payload).getBytes(StandardCharsets.UTF_8));
return verifier.verify(Base64.getDecoder().decode(signature)); 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 apiKey = "";
private String apiSecret = ""; private String apiSecret = "";
private String rsaPublicKeyLocation = ""; 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 String notifyUrl = "";
private BigDecimal minAmount = new BigDecimal("1.00"); private BigDecimal minAmount = new BigDecimal("1.00");
private BigDecimal maxAmount = new BigDecimal("10000.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()));
}
}