全局白名单

This commit is contained in:
lu7213 committed 2026-11-17 03:12:44 -05:00
1 parent 4d656ef63c
commit 606c50139c
7 files changed
+361

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
# 管理后台全局接口 IP 白名单
## 部署
1. 执行 `sql/admin_access_whitelist.sql`(增量建表,无默认放行规则)。
2. 通过管理接口或 SQL 配置允许访问的路径/IP,必须包含管理员访问的 `/login`、`/captchaImage`、`/getInfo`、`/getRouters` 等实际调用路径;固定管理员 IP 可配置 `/**`。
3. 在后台 application 配置添加以下内容,重启启用:
```yaml
admin:
access-whitelist:
enabled: true # 默认 false,部署前先配置规则
refresh-delay-ms: 30000
```
全局过滤覆盖此后台服务所有入口,包括登录、退出、匿名开放 API、回调和静态资源,没有隐式豁免,也不会绕过原有签名、登录和业务权限。公共支付/回调接口如需对任意 IP 开放,可显式配置该路径与 `*`。空规则、全部停用、首次加载失败时,启用状态下均拒绝访问。关闭开关需要修改配置并重启,可用于规则误配后的恢复。
## 规则
每行 `pathPattern` 与 `ipPattern` 同时匹配即放行,多行取或。路径采用 Ant 规则:`*` 为单段、`**` 为多段、`?` 为单字符;`/system/**` 匹配系统接口。IP 支持精确 IPv4/IPv6 以及 `*`、`?`,如 `192.168.*.*`,不是 CIDR。IPv6 按文本匹配,使用实际连接地址表示形式。
仅匹配应用内路径,不含 context-path、查询串;使用 Servlet 路径解码/分号移除规则。IP 从 `request.getRemoteAddr()` 读取,不直接读取 X-Forwarded-For 或 X-Real-IP。反向代理部署时它默认是代理地址:需要在容器层仅对受信代理做地址还原,且禁止客户端绕过该代理直连后台;否则这里只能限制代理本身。不要配置无边界信任所有代理头。
## 管理接口
基路径 `/system/accessWhitelist`,沿用 `system:config:*` 权限,并保留若依操作审计。
| 方法 | 路径 | 权限 | 说明 |
| --- | --- | --- | --- |
| GET | `/list` | list | 获取全部规则 |
| POST | 基路径 | add | 新建 |
| PUT | `/{id}` | edit | 更新、启停 |
| DELETE | `/{id}` | remove | 删除 |
| POST | `/refresh` | edit | 触发当前节点刷新 |
新增/更新请求示例:
```json
{"pathPattern":"/**","ipPattern":"192.168.1.*","enabled":true,"remark":"管理网络"}
```
更改写入数据库,正常情况下约 30 秒后生效(刷新间隔不含查询耗时);各后台实例独立定时拉取,可调用刷新接口提前更新当前实例。每次刷新完整构建后原子替换快照,请求线程不查库;数据库故障或规则无效会保留最后成功快照并输出不含配置内容的错误日志。首次初始化后调度持续重试。刷新接口返回刷新成功或失败信息。
本次仅新增后台配置 API,未添加前端管理页面。
@@ -0,0 +1,47 @@
package com.ruoyi.web.access;
import java.io.IOException;
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.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UrlPathHelper;
/** 全局入口过滤,早于认证链;白名单不赋予匿名访问或业务权限。 */
@Configuration
@EnableScheduling
public class AdminAccessConfiguration {
@Bean
public FilterRegistrationBean<OncePerRequestFilter> adminAccessFilter(
AdminAccessWhitelist whitelist,
@Value("${admin.access-whitelist.enabled:false}") boolean enabled) {
OncePerRequestFilter filter = new OncePerRequestFilter() {
private final UrlPathHelper paths = new UrlPathHelper();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
// 仅使用 TCP 对端地址,绝不直接信任客户端可伪造的 X-Forwarded-For/X-Real-IP。
if (!enabled || whitelist.allows(paths.getPathWithinApplication(request), request.getRemoteAddr())) {
chain.doFilter(request, response);
return;
}
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":403,\"msg\":\"来源 IP 不在接口访问白名单中\"}");
}
};
FilterRegistrationBean<OncePerRequestFilter> registration = new FilterRegistrationBean<>(filter);
registration.setName("adminAccessWhitelistFilter");
registration.addUrlPatterns("/*");
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 20);
return registration;
}
}
@@ -0,0 +1,65 @@
package com.ruoyi.web.access;
import javax.validation.Valid;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
/** 白名单管理接口,复用系统参数管理权限;数据库写入使用绑定参数。 */
@RestController
@RequestMapping("/system/accessWhitelist")
public class AdminAccessController {
private final JdbcTemplate jdbc;
private final AdminAccessWhitelist whitelist;
public AdminAccessController(JdbcTemplate jdbc, AdminAccessWhitelist whitelist) {
this.jdbc = jdbc;
this.whitelist = whitelist;
}
@GetMapping("/list")
@PreAuthorize("@ss.hasPermi('system:config:list')")
public AjaxResult list() {
return AjaxResult.success(jdbc.queryForList("select id, path_pattern as pathPattern, "
+ "ip_pattern as ipPattern, enabled, remark, created_at, updated_at "
+ "from sys_admin_access_whitelist order by id"));
}
@PostMapping
@PreAuthorize("@ss.hasPermi('system:config:add')")
@Log(title = "全局接口访问白名单", businessType = BusinessType.INSERT)
public AjaxResult add(@Valid @RequestBody AdminAccessRule rule) {
int count = jdbc.update("insert into sys_admin_access_whitelist "
+ "(path_pattern, ip_pattern, enabled, remark) values (?, ?, ?, ?)",
rule.getPathPattern(), rule.getIpPattern(), rule.getEnabled(), rule.getRemark());
return AjaxResult.success(count);
}
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermi('system:config:edit')")
@Log(title = "全局接口访问白名单", businessType = BusinessType.UPDATE)
public AjaxResult edit(@PathVariable Long id, @Valid @RequestBody AdminAccessRule rule) {
return AjaxResult.success(jdbc.update("update sys_admin_access_whitelist set "
+ "path_pattern=?, ip_pattern=?, enabled=?, remark=? where id=?",
rule.getPathPattern(), rule.getIpPattern(), rule.getEnabled(), rule.getRemark(), id));
}
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermi('system:config:remove')")
@Log(title = "全局接口访问白名单", businessType = BusinessType.DELETE)
public AjaxResult remove(@PathVariable Long id) {
return AjaxResult.success(jdbc.update("delete from sys_admin_access_whitelist where id=?", id));
}
@PostMapping("/refresh")
@PreAuthorize("@ss.hasPermi('system:config:edit')")
@Log(title = "刷新全局接口访问白名单", businessType = BusinessType.UPDATE)
public AjaxResult refresh() {
whitelist.refresh();
return whitelist.isLastRefreshSuccessful() ? AjaxResult.success("刷新成功")
: AjaxResult.error("刷新失败,已保留上一版本,请检查服务日志");
}
}
@@ -0,0 +1,34 @@
package com.ruoyi.web.access;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
/** 管理后台全局访问规则;一行中的路径和 IP 必须同时匹配。 */
public class AdminAccessRule {
private Long id;
@NotBlank
@Size(max = 255)
@Pattern(regexp = "/[^\\s?#;\\\\]*", message = "路径须以 / 开头,且不能包含空白、查询串、分号或反斜杠")
private String pathPattern;
@NotBlank
@Size(max = 64)
@Pattern(regexp = "[0-9a-fA-F:.*?]+", message = "IP 仅支持数字地址及 *、? 通配符")
private String ipPattern;
@NotNull
private Boolean enabled;
@Size(max = 255)
private String remark;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getPathPattern() { return pathPattern; }
public void setPathPattern(String pathPattern) { this.pathPattern = pathPattern; }
public String getIpPattern() { return ipPattern; }
public void setIpPattern(String ipPattern) { this.ipPattern = ipPattern; }
public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
public String getRemark() { return remark; }
public void setRemark(String remark) { this.remark = remark; }
}
@@ -0,0 +1,81 @@
package com.ruoyi.web.access;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
/**
* 数据库规则的进程内快照。请求线程不访问数据库;完整加载成功后一次性发布快照,
* 刷新失败保留最近成功版本。首次加载失败时快照为空,启用拦截后默认拒绝。
*/
@Service
public class AdminAccessWhitelist {
private static final Logger LOG = LoggerFactory.getLogger(AdminAccessWhitelist.class);
private final JdbcTemplate jdbc;
private final AntPathMatcher paths = new AntPathMatcher();
private volatile List<CompiledRule> snapshot = Collections.emptyList();
private volatile boolean lastRefreshSuccessful;
public AdminAccessWhitelist(JdbcTemplate jdbc) { this.jdbc = jdbc; }
@PostConstruct
@Scheduled(fixedDelayString = "${admin.access-whitelist.refresh-delay-ms:30000}")
public synchronized void refresh() {
try {
List<CompiledRule> next = jdbc.query(
"select path_pattern, ip_pattern from sys_admin_access_whitelist where enabled = 1",
(rs, row) -> new CompiledRule(rs.getString(1), rs.getString(2)));
snapshot = Collections.unmodifiableList(new ArrayList<>(next));
lastRefreshSuccessful = true;
} catch (RuntimeException ex) {
lastRefreshSuccessful = false;
// 不记录配置值或数据库异常正文,避免日志泄漏连接信息。
LOG.error("管理后台访问白名单刷新失败,保留上一版本,异常类型: {}", ex.getClass().getSimpleName());
}
}
public boolean isLastRefreshSuccessful() { return lastRefreshSuccessful; }
public boolean allows(String path, String ip) {
if (path == null || ip == null) { return false; }
for (CompiledRule rule : snapshot) {
if (paths.match(rule.path, path) && rule.ip.matcher(ip.toLowerCase(Locale.ROOT)).matches()) {
return true;
}
}
return false;
}
/** 仅 * 和 ? 具有特殊意义,其他字符逐个转义,禁止将数据库内容作为任意正则执行。 */
static Pattern compileIp(String value) {
if (value == null || value.length() > 64 || !value.matches("[0-9a-fA-F:.*?]+")) {
throw new IllegalArgumentException("无效 IP 规则");
}
StringBuilder regex = new StringBuilder();
for (char c : value.toLowerCase(Locale.ROOT).toCharArray()) {
regex.append(c == '*' ? ".*" : c == '?' ? "." : Pattern.quote(String.valueOf(c)));
}
return Pattern.compile(regex.toString());
}
private static final class CompiledRule {
private final String path;
private final Pattern ip;
private CompiledRule(String path, String ip) {
if (path == null || !path.startsWith("/") || path.length() > 255) {
throw new IllegalArgumentException("无效接口规则");
}
this.path = path;
this.ip = compileIp(ip);
}
}
}
@@ -0,0 +1,78 @@
package com.ruoyi.web.access;
import java.sql.ResultSet;
import java.util.Collections;
import javax.servlet.FilterChain;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/** 隔离数据库和 Servlet 链,覆盖规则配对、快照替换、故障保留及真实响应。 */
public class AdminAccessWhitelistTest {
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void refreshPublishesWholeSnapshotAndRetainsItOnDatabaseFailure() throws Exception {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.query(anyString(), any(RowMapper.class))).thenAnswer(call -> {
ResultSet rs = mock(ResultSet.class);
when(rs.getString(1)).thenReturn("/system/**");
when(rs.getString(2)).thenReturn("192.168.*.*");
return Collections.singletonList(((RowMapper) call.getArgument(1)).mapRow(rs, 0));
});
AdminAccessWhitelist whitelist = new AdminAccessWhitelist(jdbc);
assertFalse(whitelist.allows("/system/user", "192.168.1.2"));
whitelist.refresh();
assertTrue(whitelist.allows("/system/user/list", "192.168.1.2"));
assertFalse(whitelist.allows("/login", "192.168.1.2"));
assertFalse(whitelist.allows("/system/user/list", "192x168.1.2"));
when(jdbc.query(anyString(), any(RowMapper.class))).thenThrow(new IllegalStateException());
whitelist.refresh();
assertTrue(whitelist.allows("/system/user/list", "192.168.1.2"));
when(jdbc.query(anyString(), any(RowMapper.class))).thenReturn(Collections.emptyList());
whitelist.refresh();
assertFalse(whitelist.allows("/system/user/list", "192.168.1.2"));
}
@Test
public void rejectsSpoofedForwardingHeaderAndAllowsDisabledMode() throws Exception {
AdminAccessWhitelist whitelist = mock(AdminAccessWhitelist.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/system/user/list");
request.setRemoteAddr("203.0.113.9");
request.addHeader("X-Forwarded-For", "127.0.0.1");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
new AdminAccessConfiguration().adminAccessFilter(whitelist, true).getFilter()
.doFilter(request, response, chain);
assertEquals(403, response.getStatus());
verify(whitelist).allows("/system/user/list", "203.0.113.9");
verifyZeroInteractions(chain);
new AdminAccessConfiguration().adminAccessFilter(whitelist, false).getFilter()
.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(eq(request), any());
}
@Test
public void allowedRequestContinuesThroughOriginalChain() throws Exception {
AdminAccessWhitelist whitelist = mock(AdminAccessWhitelist.class);
when(whitelist.allows("/login", "127.0.0.1")).thenReturn(true);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/admin/login");
request.setContextPath("/admin");
request.setRemoteAddr("127.0.0.1");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
new AdminAccessConfiguration().adminAccessFilter(whitelist, true).getFilter()
.doFilter(request, response, chain);
verify(chain).doFilter(request, response);
}
@Test
public void wildcardMatchesEntireIpAndSupportsIpv6() {
assertTrue(AdminAccessWhitelist.compileIp("2001:db8:*").matcher("2001:db8::1").matches());
assertTrue(AdminAccessWhitelist.compileIp("10.0.0.?").matcher("10.0.0.1").matches());
assertFalse(AdminAccessWhitelist.compileIp("10.0.0.?").matcher("10.0.0.12").matches());
}
}
+12
View File
@@ -0,0 +1,12 @@
-- 增量初始化,不修改或删除现有业务表;不插入允许任意来源的默认规则。
CREATE TABLE IF NOT EXISTS sys_admin_access_whitelist (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '规则 ID',
path_pattern VARCHAR(255) NOT NULL COMMENT 'Ant 接口路径,如 /system/**',
ip_pattern VARCHAR(64) NOT NULL COMMENT 'IP 通配规则,如 192.168.*.*',
enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1 启用,0 停用',
remark VARCHAR(255) DEFAULT NULL COMMENT '备注',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_admin_access_enabled (enabled)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='管理后台全局接口 IP 访问白名单';