全局白名单

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

@@ -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());
}
}