添加ip白名单功能

This commit is contained in:
lu7213 committed 2026-11-16 10:30:21 -05:00
1 parent c12b777a42
commit 4d656ef63c
20 files changed
+436 -6

No files matched your search

+2
View File
@@ -1,5 +1,7 @@
## 平台简介
支付和租赁应用支持[外部 API 来源 IP 白名单](docs/app-ip-whitelist.md)。升级先执行 [增量 SQL](sql/app_ip_whitelist_upgrade.sql),并为现有应用配置允许来源;空白名单拒绝全部请求,独立 `*` 显式允许全部来源。
Quartz 任意调用和 YAML 远程加载链已增加执行允许列表及安全解析,管理接口默认仅允许回环来源。
部署必须同步更新 Quartz/system/YAML 依赖,并按[安全加固说明](docs/security-hardening.md)配置可信来源和代理规则。
+30
View File
@@ -0,0 +1,30 @@
# 支付与租赁应用 IP 白名单
`apps.ip_whitelist` 和 `rent_app.ip_whitelist` 使用 `VARCHAR(2048) NOT NULL DEFAULT ''`。
支付应用 JSON 字段为 `ipWhitelist`,租赁工作台 JSON 字段为 `ip_whitelist`。
## 规则
- 空值或空白:拒绝此应用全部外部 API 请求。不会影响后台 JWT 管理页面,仍可登录修改白名单。
- 精确 IPv4 / IPv6:例如 `203.0.113.10`、`2001:db8::1`。
- IPv4 完整地址段通配:例如 `192.168.*.*`、`10.*.1.*`。`*` 不能匹配半个地址段,不支持 CIDR、主机名或 URL。
- 独立 `*`:显式允许所有来源,签名及原有鉴权仍必须通过。
- 多条使用换行、逗号、分号或空白分隔;保存时去重,最多2048字符。
支付覆盖所有调用 `ApiSecurityService` 的创建订单、查询、代付和钱包开放接口。
租赁覆盖 `/api/rental/v1/{operation}` 和 `/api/rental/v1/address-onchain/{operation}`。
供应节点 Agent、后台管理、链上扫描和平台接收回调不属于应用商户调用,不套用本规则。
拒绝响应为原 JSON 协议的 `code=403`,签名、密钥及抗重放逻辑继续保留。
## 真实来源与反向代理
默认取 Servlet `request.getRemoteAddr()`,不直接使用 `X-Forwarded-For`、`X-Real-IP` 或 `Forwarded`,防止调用者伪造来源。
直接部署填写客户端实际 IP。反向代理部署须由运维在可信代理/容器层配置来源地址恢复,并且只信任确定的代理地址、限制直连后端和覆盖外部转发头;未配置时服务看到的是代理 IP。
不要仅把所有用户共用的反向代理地址加入名单后将其当作按客户端隔离。
## 部署
1. 先在业务库执行 `sql/app_ip_whitelist_upgrade.sql`,可重复执行,不重建、不删除已有表。新租赁库的 `rent_init.sql` 已包含该列。
2. 按每个应用配置实际来源 IP;旧记录默认空白,新版上线后会拒绝其 API 请求,必须提前配置。
3. 编译部署前后端并重启服务。支付应用在创建/编辑对话框维护;租赁商户在应用详情保存,运营在应用列表的“IP 白名单”操作维护。
4. 使用名单内、名单外和伪造转发头的请求验证。测试不广播任何链上交易。
@@ -0,0 +1,29 @@
package com.ruoyi.system.rental;
import org.junit.Test;
import static org.mockito.Mockito.*;
import static com.ruoyi.system.rental.RentalValues.map;
/** 白名单保存必须依据持久化应用归属鉴权,且只写归一化后的配置(复用 admin 测试依赖)。 */
public class RentalAppIpWhitelistTest {
@Test
public void ownerCanSaveNormalizedRules() {
RentalStore store = mock(RentalStore.class);
when(store.get("app", 7L, true)).thenReturn(map("user_id", 9L));
new RentalProvisioning(store, mock(RentalOrders.class))
.updateAppIpWhitelist(7L, "192.168.*.* , 203.0.113.1", 9L);
verify(store).update("app", 7L, map("ip_whitelist", "192.168.*.*\n203.0.113.1"));
}
@Test
public void otherOwnerCannotChangeWhitelist() {
RentalStore store = mock(RentalStore.class);
when(store.get("app", 7L, true)).thenReturn(map("user_id", 9L));
try {
new RentalProvisioning(store, mock(RentalOrders.class)).updateAppIpWhitelist(7L, "*", 10L);
org.junit.Assert.fail("其他商户不得修改白名单");
} catch (IllegalArgumentException expected) {
verify(store, never()).update(anyString(), anyLong(), anyMap());
}
}
}
@@ -0,0 +1,96 @@
package com.ruoyi.web.controller.system;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.AppApiKeysPlus;
import com.ruoyi.system.domain.Apps;
import com.ruoyi.system.domain.dto.EncryptedRequest;
import com.ruoyi.system.mapper.AppsMapper;
import com.ruoyi.system.rental.*;
import com.ruoyi.system.service.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.junit.After;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/** 使用可控凭证和请求,验证两套真实API入口不会因伪造转发头而绕过白名单。 */
public class AppIpWhitelistSecurityTest {
@After
public void clearRequest() { RequestContextHolder.resetRequestAttributes(); }
@Test
public void paymentRejectsNonWhitelistedPeerBeforeDecrypting() {
ApiSecurityService service = new ApiSecurityService();
IAppApiKeysService keys = mock(IAppApiKeysService.class);
AppsMapper apps = mock(AppsMapper.class);
AppPrivateKeyCipher cipher = mock(AppPrivateKeyCipher.class);
AppApiKeysPlus credential = new AppApiKeysPlus();
credential.setAppId(7L); credential.setUserId(8L);
Apps app = new Apps();
app.setId(7L); app.setUserId(8L); app.setStatus(1); app.setIpWhitelist("203.0.113.*");
when(keys.getOne(any())).thenReturn(credential);
when(apps.selectAppsById(7L)).thenReturn(app);
ReflectionTestUtils.setField(service, "apiKeysService", keys);
ReflectionTestUtils.setField(service, "appsMapper", apps);
ReflectionTestUtils.setField(service, "privateKeyCipher", cipher);
MockHttpServletRequest request = request("198.51.100.1");
request.addHeader("X-Forwarded-For", "203.0.113.10");
request.addHeader("X-Real-IP", "203.0.113.10");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
EncryptedRequest encrypted = new EncryptedRequest();
encrypted.setApiKey("key"); encrypted.setTimestamp(System.currentTimeMillis()); encrypted.setNonce("nonce");
encrypted.setEncryptedKey("key"); encrypted.setIv("iv"); encrypted.setData("data"); encrypted.setHmac("hmac");
denied(() -> service.decryptAndVerify(encrypted));
app.setIpWhitelist("");
denied(() -> service.decryptAndVerify(encrypted));
verifyNoInteractions(cipher);
}
@Test
public void rentalEnforcesApplicationWhitelistAcrossOperations() throws Exception {
RentalIdentity identity = mock(RentalIdentity.class);
RentalStore store = mock(RentalStore.class);
RentalOrders orders = mock(RentalOrders.class);
Map<String, Object> credential = new HashMap<>(); credential.put("owner_id", 7L);
Map<String, Object> app = new HashMap<>(); app.put("status", "ACTIVE"); app.put("user_id", 8L);
app.put("ip_whitelist", "203.0.113.*");
when(identity.authenticate(anyString(), eq("APP"), eq("API"), anyLong(), anyString(), eq("POST"), anyString(), anyString(), anyString())).thenReturn(credential);
when(store.get("app", 7L, false)).thenReturn(app);
RentalApiController controller = new RentalApiController(identity, store, orders, new ObjectMapper());
for (String operation : Arrays.asList("create", "query", "quote", "packages")) {
MockHttpServletRequest request = request("198.51.100.1");
request.addHeader("X-Forwarded-For", "203.0.113.10");
try {
controller.execute(operation, request);
fail("非白名单来源不能调用租赁API");
} catch (CustomException expected) { assertEquals(Integer.valueOf(403), expected.getCode()); }
}
controller.execute("packages", request("203.0.113.10"));
try {
controller.executeOnchain("quote", request("198.51.100.1"));
fail("地址上链入口同样需要白名单");
} catch (CustomException expected) { assertEquals(Integer.valueOf(403), expected.getCode()); }
verifyNoInteractions(orders);
}
private MockHttpServletRequest request(String ip) {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/rental/v1/packages");
request.setRemoteAddr(ip);
request.setContent("{\"network\":\"NILE\"}".getBytes(StandardCharsets.UTF_8));
request.addHeader("X-Rent-Key", "key"); request.addHeader("X-Rent-Timestamp", "1");
request.addHeader("X-Rent-Nonce", "nonce"); request.addHeader("X-Rent-Signature", "signature");
return request;
}
private void denied(Runnable operation) {
try { operation.run(); fail("必须拒绝白名单以外的IP"); }
catch (CustomException expected) { assertEquals(Integer.valueOf(403), expected.getCode()); }
}
}
@@ -19,6 +19,11 @@ public class Apps extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 外部 API 来源 IP 白名单,空值拒绝,支持 IPv4 整段通配符。 */
private String ipWhitelist;
public String getIpWhitelist() { return ipWhitelist; }
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
/** 主键 */
private Long id;
@@ -22,6 +22,11 @@ public class AppsPlus implements Serializable
{
private static final long serialVersionUID = 1L;
/** 外部 API 来源 IP 白名单。 */
private String ipWhitelist;
public String getIpWhitelist() { return ipWhitelist; }
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
/** 主键 */
private Long id;
/** 用户ID */
@@ -17,6 +17,11 @@ public class RentApp extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 外部 API 来源 IP 白名单,空值拒绝,支持 IPv4 整段通配符。 */
private String ipWhitelist;
public String getIpWhitelist() { return ipWhitelist; }
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
/** 记录主键 */
private Long id;
@@ -20,6 +20,11 @@ public class RentAppPlus implements Serializable
{
private static final long serialVersionUID = 1L;
/** 外部 API 来源 IP 白名单。 */
private String ipWhitelist;
public String getIpWhitelist() { return ipWhitelist; }
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
/** 记录主键 */
private Long id;
/** 所有者sys_user.user_id */
@@ -88,6 +88,8 @@ public class RentalApiController {
request.getHeader("X-Rent-Signature"));
Map<String, Object> app = store.get("app", number(credential, "owner_id"), false);
require("ACTIVE".equals(text(app, "status")), "应用已禁用");
// 与支付应用使用相同策略;商户查询、报价、套餐、下单和地址上链均不可绕过。
com.ruoyi.system.security.AppIpWhitelist.requireAllowed(text(app, "ip_whitelist"), request.getRemoteAddr());
Map<String, Object> data =
json.readValue(body, new TypeReference<Map<String, Object>>() {
});
@@ -121,7 +121,7 @@ public class RentalController {
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
public AjaxResult appDetail(@PathVariable long id) {
Map<String, Object> app = store.one(
"SELECT id,name,status,notify_url,created_at,updated_at FROM rent_app WHERE id=? AND user_id=?",
"SELECT id,name,status,notify_url,ip_whitelist,created_at,updated_at FROM rent_app WHERE id=? AND user_id=?",
id, user());
require(app != null, "应用不存在或无权访问");
// DATETIME(3) 约定存服务器本地时间;统一输出毫秒,避免驱动返回 Timestamp/LocalDateTime 的差异。
@@ -143,6 +143,24 @@ public class RentalController {
return AjaxResult.success(map("app", app, "credentials", credentials));
}
/** 商户只能维护本人应用,白名单不是商户外部API,避免配置错误后无法修复。 */
@PostMapping("/app/{id}/ip-whitelist")
@PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:app:create') or @ss.hasPermi('rent:app:edit')")
public AjaxResult updateAppIpWhitelist(@PathVariable long id, @RequestBody Map<String, Object> body) {
require(body.containsKey("ip_whitelist"), "缺少IP白名单配置");
provisioning.updateAppIpWhitelist(id, text(body, "ip_whitelist"), user());
return AjaxResult.success();
}
/** 运营配置入口与商户入口分离,不能通过提交应用ID越权。 */
@PostMapping("/manage/app/{id}/ip-whitelist")
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
public AjaxResult manageAppIpWhitelist(@PathVariable long id, @RequestBody Map<String, Object> body) {
require(body.containsKey("ip_whitelist"), "缺少IP白名单配置");
provisioning.updateAppIpWhitelist(id, text(body, "ip_whitelist"), null);
return AjaxResult.success();
}
/** 仅允许删除本人未产生业务关联的空应用。 */
@DeleteMapping("/app/{id}")
@PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:app:remove')")
@@ -25,6 +25,16 @@ public class RentalProvisioning {
this.orders = orders;
}
/** actor=null 仅由已校验运营权限的入口传入;商户入口必须校验持久化归属,不能信任请求 user_id。 */
@Transactional(rollbackFor = Exception.class)
public void updateAppIpWhitelist(long appId, String whitelist, Long actor) {
String normalized = com.ruoyi.system.security.AppIpWhitelist.normalize(whitelist);
Map<String, Object> app = store.get("app", appId, true);
require(actor == null || number(app, "user_id") == actor, "应用不存在或无权访问");
store.update("app", appId, map("ip_whitelist", normalized));
store.event("APP", appId, "UPDATE_IP_WHITELIST", actor == null ? 0 : actor, "更新外部API来源IP白名单");
}
/**
* 删除未使用的应用。actor 为 null 仅供已有运营权限校验的内部入口使用。
* 与下单和凭证签发使用相同父行锁,保证检查与删除之间不会插入新关联。
@@ -63,6 +73,7 @@ public class RentalProvisioning {
"ACTIVE",
"notify_url",
url.isEmpty() ? null : url);
row.put("ip_whitelist", com.ruoyi.system.security.AppIpWhitelist.normalize(text(request, "ip_whitelist")));
} else if ("node".equals(type)) {
row =
map(
@@ -0,0 +1,130 @@
package com.ruoyi.system.security;
import com.ruoyi.common.exception.CustomException;
import java.net.InetAddress;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* 商户应用共用的来源 IP 白名单。只解析 IP 字面量,不做 DNS 查询,不接受 URL、主机名或正则。
* IPv4 的 * 匹配一个完整地址段;独立 * 显式允许所有来源。空配置和非法配置一律拒绝。
*/
public final class AppIpWhitelist {
public static final int MAX_LENGTH = 2048;
private AppIpWhitelist() { }
/** 保存前校验并归一化。多条可使用逗号、分号、空白或换行分隔。 */
public static String normalize(String value) {
if (value == null || value.trim().isEmpty()) {
return "";
}
if (value.length() > MAX_LENGTH) {
throw new CustomException("IP 白名单不能超过2048个字符");
}
Set<String> rules = new LinkedHashSet<>();
for (String rule : value.trim().split("[,;\\s]+")) {
if (!validRule(rule)) {
throw new CustomException("IP 白名单格式错误:支持IP地址、IPv4整段通配符(如192.168.*.*)或独立*");
}
rules.add(rule);
}
return String.join("\n", rules);
}
public static void requireAllowed(String whitelist, String sourceIp) {
if (!isAllowed(whitelist, sourceIp)) {
throw new CustomException("来源 IP 不在应用白名单中", 403);
}
}
/** 运行时也完整校验配置,防止直接改库写入非法规则后意外放行。 */
public static boolean isAllowed(String whitelist, String sourceIp) {
String normalized;
try {
normalized = normalize(whitelist);
} catch (CustomException exception) {
return false;
}
byte[] source = address(sourceIp);
if (normalized.isEmpty() || source == null) {
return false;
}
for (String rule : normalized.split("\n")) {
if ("*".equals(rule)) {
return true;
}
if (rule.indexOf('*') >= 0) {
if (source.length != 4) {
continue;
}
String[] parts = rule.split("\\.");
boolean matches = true;
for (int index = 0; index < 4; index++) {
if (!"*".equals(parts[index]) && Integer.parseInt(parts[index]) != (source[index] & 255)) {
matches = false;
break;
}
}
if (matches) {
return true;
}
} else if (java.util.Arrays.equals(source, address(rule))) {
return true;
}
}
return false;
}
private static boolean validRule(String rule) {
if ("*".equals(rule)) {
return true;
}
if (rule.indexOf('*') < 0) {
return address(rule) != null;
}
String[] parts = rule.split("\\.", -1);
if (parts.length != 4) {
return false;
}
for (String part : parts) {
if (!"*".equals(part) && !octet(part)) {
return false;
}
}
return true;
}
private static boolean octet(String value) {
return value.matches("0|[1-9][0-9]{0,2}") && Integer.parseInt(value) <= 255;
}
/** IPv6 先限定字符集并要求冒号,避免 InetAddress 对任意字符串发起域名解析。 */
private static byte[] address(String value) {
if (value == null || value.length() > 45) {
return null;
}
if (value.indexOf(':') >= 0) {
if (!value.matches("[0-9a-fA-F:.]+")) {
return null;
}
try {
return InetAddress.getByName(value).getAddress();
} catch (Exception exception) {
return null;
}
}
String[] parts = value.split("\\.", -1);
if (parts.length != 4) {
return null;
}
byte[] result = new byte[4];
for (int index = 0; index < 4; index++) {
if (!octet(parts[index])) {
return null;
}
result[index] = (byte) Integer.parseInt(parts[index]);
}
return result;
}
}
@@ -50,6 +50,10 @@ public class ApiSecurityService {
|| !Objects.equals(credential.getUserId(), app.getUserId())) {
throw new CustomException("API 凭证无效");
}
// 只使用连接对端地址,不信任调用者可伪造的 X-Forwarded-For / X-Real-IP。
javax.servlet.http.HttpServletRequest httpRequest = com.ruoyi.common.utils.ServletUtils.getRequest();
com.ruoyi.system.security.AppIpWhitelist.requireAllowed(app.getIpWhitelist(),
httpRequest == null ? null : httpRequest.getRemoteAddr());
byte[] aesKey = null;
try {
@@ -395,6 +395,7 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
@Transactional(rollbackFor = Exception.class)
public int insertApps(Apps apps, boolean isUser) {
validateAppForCreate(apps, isUser);
apps.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(apps.getIpWhitelist()));
Long ownerUserId = isUser ? SecurityUtils.getUserId() : apps.getUserId();
if (ownerUserId == null || appsMapper.lockUserById(ownerUserId) == null) {
throw new CustomException("所属用户不存在");
@@ -447,6 +448,9 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
update.setId(current.getId());
update.setName(apps.getName().trim());
update.setDescription(apps.getDescription());
if (apps.getIpWhitelist() != null) {
update.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(apps.getIpWhitelist()));
}
update.setStatus(apps.getStatus());
update.setUpdatedAt(DateUtils.getNowDate());
if (!isUser) {
@@ -215,6 +215,7 @@ public class RentAppServiceImpl extends ServiceImpl<RentAppMapper, RentAppPlus>
@Override
public int insertRentApp(RentApp rentApp,boolean isUser)
{
rentApp.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(rentApp.getIpWhitelist()));
rentApp.setCreatedAt(DateUtils.getNowDate());
rentApp.setUpdatedAt(DateUtils.getNowDate());
if(isUser){
@@ -232,9 +233,18 @@ public class RentAppServiceImpl extends ServiceImpl<RentAppMapper, RentAppPlus>
@Override
public int updateRentApp(RentApp rentApp,boolean isUser)
{
if (rentApp.getIpWhitelist() != null) {
rentApp.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(rentApp.getIpWhitelist()));
}
rentApp.setUpdatedAt(DateUtils.getNowDate());
if(isUser){
checkUser(rentApp);
if (isUser) {
// 必须依据数据库归属鉴权,禁止通过请求中的 userId 修改其他商户的安全配置。
RentApp persisted = rentAppMapper.selectRentAppById(rentApp.getId());
Long actor = SecurityUtils.getUserId();
if (persisted == null || actor == null || !actor.equals(persisted.getUserId())) {
throw new com.ruoyi.common.exception.CustomException("应用不存在或无权访问", 403);
}
rentApp.setUserId(persisted.getUserId());
}
return rentAppMapper.updateRentApp(rentApp);
}
@@ -10,6 +10,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</update>
<resultMap type="Apps" id="AppsResult">
<result property="ipWhitelist" column="ip_whitelist" />
<result property="id" column="id" />
<result property="userId" column="user_id" />
<result property="name" column="name" />
@@ -33,7 +34,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<sql id="selectAppsVo">
select id, user_id, name, description, status, created_at, updated_at, deleted_at, trx_balance, usdt_balance, usdt_frozen_balance, trx_frozen_balance, public_key, private_key, credit_limit, google_sub, google_email, google_name, google_picture, dist_token_address from apps
select id, ip_whitelist, user_id, name, description, status, created_at, updated_at, deleted_at, trx_balance, usdt_balance, usdt_frozen_balance, trx_frozen_balance, public_key, private_key, credit_limit, google_sub, google_email, google_name, google_picture, dist_token_address from apps
</sql>
<select id="lockUserById" resultType="Long">
@@ -104,6 +105,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<insert id="insertApps" parameterType="Apps" useGeneratedKeys="true" keyProperty="id">
insert into apps
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="ipWhitelist != null">ip_whitelist,</if>
<if test="userId != null">user_id,</if>
<if test="name != null and name != ''">name,</if>
<if test="description != null">description,</if>
@@ -125,6 +127,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="distTokenAddress != null">dist_token_address,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="ipWhitelist != null">#{ipWhitelist},</if>
<if test="userId != null">#{userId},</if>
<if test="name != null and name != ''">#{name},</if>
<if test="description != null">#{description},</if>
@@ -150,6 +153,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<update id="updateApps" parameterType="Apps">
update apps
<trim prefix="SET" suffixOverrides=",">
<if test="ipWhitelist != null">ip_whitelist = #{ipWhitelist},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="name != null and name != ''">name = #{name},</if>
<if test="description != null">description = #{description},</if>
@@ -5,6 +5,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="com.ruoyi.system.mapper.RentAppMapper">
<resultMap type="RentApp" id="RentAppResult">
<result property="ipWhitelist" column="ip_whitelist" />
<result property="id" column="id" />
<result property="userId" column="user_id" />
<result property="name" column="name" />
@@ -16,7 +17,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<sql id="selectRentAppVo">
select id, user_id, name, status, notify_url, version, created_at, updated_at from rent_app
select id, ip_whitelist, user_id, name, status, notify_url, version, created_at, updated_at from rent_app
</sql>
<select id="selectRentAppList" parameterType="RentApp" resultMap="RentAppResult">
@@ -34,6 +35,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<insert id="insertRentApp" parameterType="RentApp" useGeneratedKeys="true" keyProperty="id">
insert into rent_app
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="ipWhitelist != null">ip_whitelist,</if>
<if test="userId != null">user_id,</if>
<if test="name != null and name != ''">name,</if>
<if test="status != null and status != ''">status,</if>
@@ -43,6 +45,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="updatedAt != null">updated_at,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="ipWhitelist != null">#{ipWhitelist},</if>
<if test="userId != null">#{userId},</if>
<if test="name != null and name != ''">#{name},</if>
<if test="status != null and status != ''">#{status},</if>
@@ -56,6 +59,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<update id="updateRentApp" parameterType="RentApp">
update rent_app
<trim prefix="SET" suffixOverrides=",">
<if test="ipWhitelist != null">ip_whitelist = #{ipWhitelist},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="name != null and name != ''">name = #{name},</if>
<if test="status != null and status != ''">status = #{status},</if>
@@ -77,4 +81,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
#{id}
</foreach>
</delete>
</mapper>
</mapper>
@@ -0,0 +1,50 @@
package com.ruoyi.system.security;
import com.ruoyi.common.exception.CustomException;
import org.junit.Test;
import static org.junit.Assert.*;
/** 不连接网络:验证精确匹配、整段通配、非法配置失败关闭及 IPv6 规范化。 */
public class AppIpWhitelistTest {
@Test
public void emptyAndInvalidConfigurationsDeny() {
for (String value : new String[] {null, "", " ", "192.168.*", "*\nexample.com", "999.1.1.1"}) {
assertFalse(AppIpWhitelist.isAllowed(value, "192.168.1.2"));
}
assertFalse(AppIpWhitelist.isAllowed("*", null));
assertFalse(AppIpWhitelist.isAllowed("*", "203.0.113.1,127.0.0.1"));
assertFalse(AppIpWhitelist.isAllowed("*", "example.com"));
}
@Test
public void matchesWholeIpv4OctetsOnly() {
assertTrue(AppIpWhitelist.isAllowed("192.168.*.*", "192.168.0.255"));
assertFalse(AppIpWhitelist.isAllowed("192.168.*.*", "192.169.0.1"));
assertFalse(AppIpWhitelist.isAllowed("203.0.113.1", "203.0.113.10"));
assertTrue(AppIpWhitelist.isAllowed("10.*.1.*", "10.255.1.0"));
assertTrue(AppIpWhitelist.isAllowed("*", "203.0.113.10"));
assertFalse(AppIpWhitelist.isAllowed("192.168.*.*", "2001:db8::1"));
}
@Test
public void supportsMultipleRulesAndIpv6Literals() {
assertEquals("203.0.113.1\n192.168.*.*", AppIpWhitelist.normalize("203.0.113.1, 192.168.*.*;203.0.113.1"));
assertTrue(AppIpWhitelist.isAllowed("203.0.113.1\n2001:db8::1", "2001:0db8:0:0:0:0:0:1"));
assertTrue(AppIpWhitelist.isAllowed("203.0.113.1", "::ffff:203.0.113.1"));
assertFalse(AppIpWhitelist.isAllowed("2001:db8::1", "2001:db8::2"));
}
@Test
public void rejectsAmbiguousAndUnboundedInputBeforeSave() {
for (String value : new String[] {"192.168.1*.*", "1.2.3.256", "01.2.3.4", "1.2.3.4/24", "localhost", "::1%lo", "[::1]"}) {
try {
AppIpWhitelist.normalize(value);
fail("必须拒绝非法规则: " + value);
} catch (CustomException expected) { }
}
try {
AppIpWhitelist.normalize(new String(new char[2049]).replace('\0', '*'));
fail("必须限制配置长度");
} catch (CustomException expected) { }
}
}
+15
View File
@@ -0,0 +1,15 @@
-- 支付及租赁应用共用来源IP白名单。先执行迁移,再部署新代码。
-- 可重复执行,兼容已在 rent_init.sql 中创建该列的新库;不修改任何已有业务行。
-- 空白名单拒绝外部API访问,请在启用新版前按应用填写实际来源IP。
SET @ip_ddl = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='apps' AND COLUMN_NAME='ip_whitelist')=0,
'ALTER TABLE apps ADD COLUMN ip_whitelist VARCHAR(2048) NOT NULL DEFAULT '''' COMMENT ''API来源IP白名单;空拒绝,支持IPv4整段通配''', 'SELECT 1');
PREPARE ip_stmt FROM @ip_ddl;
EXECUTE ip_stmt;
DEALLOCATE PREPARE ip_stmt;
SET @ip_ddl = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='rent_app' AND COLUMN_NAME='ip_whitelist')=0,
'ALTER TABLE rent_app ADD COLUMN ip_whitelist VARCHAR(2048) NOT NULL DEFAULT '''' COMMENT ''API来源IP白名单;空拒绝,支持IPv4整段通配''', 'SELECT 1');
PREPARE ip_stmt FROM @ip_ddl;
EXECUTE ip_stmt;
DEALLOCATE PREPARE ip_stmt;
+1
View File
@@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS `rent_app` (
`name` VARCHAR(100) NOT NULL COMMENT '应用名称',
`status` VARCHAR(32) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE启用、DISABLED禁用',
`notify_url` VARCHAR(512) NULL COMMENT '默认HTTPS回调地址,必须检查SSRF',
`ip_whitelist` VARCHAR(2048) NOT NULL DEFAULT '' COMMENT 'API来源IP白名单;空拒绝,*允许全部,IPv4整段通配',
`version` BIGINT NOT NULL DEFAULT 0 COMMENT 'CAS乐观锁版本,更新须条件递增;追加记录保持0',
`created_at` DATETIME(3) NOT NULL COMMENT '创建服务器本地时间,应用显式写入',
`updated_at` DATETIME(3) NOT NULL COMMENT '更新服务器本地时间,追加记录与创建时间相同',