安全防护

This commit is contained in:
lu7213 committed 2026-11-16 02:09:23 -05:00
1 parent 1daf477899
commit 98657ace5b
25 files changed
+570 -4

No files matched your search

@@ -18,6 +18,7 @@ public class DmPlayerentOnlineStatusTask {
private IDmPlayerentService dmPlayerentService;
@Scheduled(cron = "0/5 * * * * ?")
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void execute() {
// com.license.LicenseBootstrap.init();
LambdaQueryWrapper<DmPlayerentPlus> queryWrapper = new LambdaQueryWrapper<>();
@@ -38,4 +39,4 @@ public class DmPlayerentOnlineStatusTask {
int count = dmPlayerentService.count(queryWrapper);
System.setProperty("globalCount", count+"");
}
}
}
@@ -20,6 +20,7 @@ public class PaymentLedgerReconciliationTask {
}
@org.springframework.scheduling.annotation.Scheduled(fixedDelay = 30000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void reconcile() {
List<Long> orderIds = ledgerPostingService.findOrderIdsRequiringSettlement(BATCH_SIZE);
for (Long orderId : orderIds) {
@@ -15,6 +15,7 @@ public class PaymentOrderExpireTask {
@Autowired private IUsdtOrdersService orders;
@Scheduled(fixedDelay = 10000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void expireOrders() {
LambdaQueryWrapper<UsdtOrdersPlus> query = new LambdaQueryWrapper<UsdtOrdersPlus>()
.eq(UsdtOrdersPlus::getStatus, 1)
@@ -16,6 +16,7 @@ public class PayoutConfirmationTask {
}
@Scheduled(fixedDelay = 30000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void confirm() {
service.confirmPending();
}
@@ -39,6 +39,7 @@ public class TronPaymentTask {
private TronChainDataClient chainDataClient;
@Scheduled(fixedDelay = 10000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void scan() {
ITronService tron = null;
try {
@@ -32,6 +32,7 @@ public class UsdtConfigBalanceRefreshTask {
/** 默认每 30 秒刷新一次,完成上一轮后再计算间隔,防止慢查询堆积。 */
@Scheduled(fixedDelayString = "${payment.usdt-config-balance.refresh-delay-ms:15000}")
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void refresh() {
UsdtConfigPlus config = usdtConfigMapper.selectOne(new LambdaQueryWrapper<UsdtConfigPlus>()
.select(UsdtConfigPlus::getId, UsdtConfigPlus::getTokenAddress)
@@ -13,6 +13,7 @@ public class WalletSnapshotRefreshTask {
/** 每轮按更新时间投递五个钱包。 */
@Scheduled(fixedDelayString = "${payment.wallet-snapshot.producer-delay-ms:10000}")
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void produce() {
walletSnapshotRefreshService.enqueueScheduledBatch();
}
@@ -0,0 +1,64 @@
package com.ruoyi.web.core.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.web.util.matcher.IpAddressMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* 调度管理/数据库监控的额外来源限制,不替代原有登录与权限检查。
* 只信任 TCP 对端地址,绝不采信客户端可伪造的 X-Forwarded-For。
* 使用本机反向代理时必须同时启用代理层来源限制,否则应用只看得到代理地址。
* 默认仅回环访问;跨主机代理或直连管理员通过受控外部配置加入明确 CIDR。
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 20)
public class ManagementSourceFilter extends OncePerRequestFilter {
private final List<IpAddressMatcher> allowed = new ArrayList<>();
public ManagementSourceFilter(@Value("${security.management.allowed-cidrs:127.0.0.1/32,::1/128}")
String cidrs) {
for (String value : cidrs.split(",")) {
String cidr = value.trim();
// 地址必须为数值格式,配置错误时启动失败,避免把主机名交给 DNS 解析。
if (!cidr.matches("[0-9a-fA-F:.]+(?:/[0-9]{1,3})?")) {
throw new IllegalArgumentException("管理来源配置必须是数值 IP/CIDR");
}
allowed.add(new IpAddressMatcher(cidr));
}
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
// servletPath 来自容器映射,避免使用带 contextPath/查询串的原始请求 URI。
String path = request.getServletPath();
if (protectedPath(path)) {
boolean permitted = false;
for (IpAddressMatcher matcher : allowed) {
if (matcher.matches(request)) { permitted = true; break; }
}
if (!permitted) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":403,\"msg\":\"管理接口来源不允许\"}");
return;
}
}
chain.doFilter(request, response);
}
private boolean protectedPath(String path) {
// 同时覆盖旧 MVC 的后缀匹配和分号路径参数,不能靠 .json 绕过来源检查。
return path.matches("/(?:monitor/(?:job|jobLog)|druid)(?:[/.;].*)?");
}
}
@@ -0,0 +1,9 @@
# 仅在同机 Nginx 部署时追加 hardening profile;原 prod/rental 等 profile 保留。
# 所有公共 API 仍由 Nginx 转发,不再允许绕过代理直接访问 Java 端口。
# 跨主机代理需将 address 改成实际私网地址,并由主机防火墙只放行代理来源。
server:
address: 127.0.0.1
security:
management:
allowed-cidrs: ${SECURITY_MANAGEMENT_ALLOWED_CIDRS:127.0.0.1/32,::1/128}
@@ -0,0 +1,18 @@
package com.ruoyi.web.core.filter;
import com.ruoyi.system.security.SafeYamlPropertySourceLoader;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import static org.junit.Assert.*;
/** 只解析当前项目配置,不启动应用、不连接数据库,且不打印配置中的秘密。 */
public class ExistingYamlCompatibilityTest {
@Test
public void allShippedConfigurationFilesRemainReadable() throws Exception {
SafeYamlPropertySourceLoader loader = new SafeYamlPropertySourceLoader();
for (String name : new String[] {"application.yml", "application-prod.yml", "application-local.yml",
"application-druid.yml", "application-rental.yml", "application-hardening.yml"}) {
assertFalse(name, loader.load(name, new ClassPathResource(name)).isEmpty());
}
}
}
@@ -0,0 +1,49 @@
package com.ruoyi.web.core.filter;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.Assert.*;
public class ManagementSourceFilterTest {
private boolean invoke(String path, String remote, String forwarded, String cidrs) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath(path);
request.setRemoteAddr(remote);
request.addHeader("X-Forwarded-For", forwarded);
MockHttpServletResponse response = new MockHttpServletResponse();
AtomicBoolean passed = new AtomicBoolean();
new ManagementSourceFilter(cidrs).doFilter(request, response,
(req, res) -> passed.set(true));
if (!passed.get()) assertEquals(403, response.getStatus());
return passed.get();
}
@Test
public void directPublicClientCannotSpoofLoopback() throws Exception {
for (String path : new String[] {"/monitor/job", "/monitor/job/run", "/monitor/jobLog/list",
"/monitor/job.json", "/monitor/job;id=1", "/druid/"}) {
assertFalse(invoke(path, "203.0.113.10", "127.0.0.1", "127.0.0.1/32,::1/128"));
}
}
@Test
public void trustedIpv4AndIpv6CanReachOriginalAuthenticationChain() throws Exception {
assertTrue(invoke("/monitor/job/list", "10.8.0.10", "203.0.113.10", "10.8.0.0/24"));
assertTrue(invoke("/monitor/job/list", "::1", "203.0.113.10", "::1/128"));
}
@Test
public void paymentCallbackAndOtherBusinessRoutesRemainUnchanged() throws Exception {
for (String path : new String[] {"/api/v1/order/query", "/api/rental/payment/notify/1",
"/api/telegram/webhook", "/node/v1/socket", "/login", "/system/wallet/list"}) {
assertTrue(invoke(path, "203.0.113.10", "203.0.113.10", "127.0.0.1/32"));
}
}
@Test(expected = IllegalArgumentException.class)
public void invalidHostnameFailsClosedWithoutDns() {
new ManagementSourceFilter("example.invalid");
}
}