添加ip白名单功能
This commit is contained in:
1 parent
c12b777a42
commit
4d656ef63c
20 files changed
+436
-6
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user