feat(安全): 用户态接口的 user_id 归属改由令牌身份判定
带 JWT 的请求若 user_id 参数与登录身份不符直接 403,管理员/超管豁免(后台代客查任务是本职), 匿名与 X-Internal-Token 调用不参与绑定——按 2026-09-28 取证,桌面端 15 个调用文件只有 4 个带凭据 且全走内部令牌,所以现网客户端零影响;网页端 uid 与令牌主体同源于 AuthService.buildResult。 "要求凭据"仍留在 user-tool-guard-enabled 开关后面,新增 user-tool-guard-prefixes 支持按前缀分批收。
This commit is contained in:
@@ -3,6 +3,7 @@ package com.nanri.aiimage.config;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import jakarta.servlet.FilterChain;
|
||||
@@ -38,6 +39,13 @@ import java.util.stream.Collectors;
|
||||
* <p>只保证"已认证",管理员/菜单级校验仍由各控制器 require* 负责,避免拦截普通登录用户本可
|
||||
* 访问的 /api/admin 接口(如权限菜单列表仅 requireUser)。
|
||||
*
|
||||
* <p>对 USER_TOOL_PREFIXES 另有一条**不依赖开关**的收紧:请求带 {@code user_id} 参数且本次能解析出
|
||||
* JWT 登录身份时,参数必须等于登录身份,否则返回 403——这些接口的数据归属从此不再由请求参数说了算。
|
||||
* 管理员/超管豁免(后台按客户查任务是本职)。匿名请求解析不出身份,因而完全不受影响:按 2026-09-28
|
||||
* 取证,桌面端调用这 14 个前缀的 15 个文件里只有 4 个带过凭据头,且带的都是 X-Internal-Token
|
||||
* (在 shouldNotFilter 里就整体放行,同样不参与绑定)。"要求凭据"这一步只能等客户端铺开后再开
|
||||
* (user-tool-guard-enabled,配合 user-tool-guard-prefixes 按前缀分批收)。
|
||||
*
|
||||
* <p>豁免项:OPTIONS 预检;以及 aiimage.security.admin-guard-exempt-prefixes 配置的前缀
|
||||
* (逗号分隔,用于内部自动化/设备回调等确需匿名可达的端点)。紧急回退:
|
||||
* aiimage.security.admin-guard-enabled=false 关闭本过滤器。
|
||||
@@ -116,16 +124,27 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
@Value("${aiimage.security.user-tool-guard-enabled:false}")
|
||||
private boolean userToolGuardEnabled;
|
||||
|
||||
/**
|
||||
* 用户态前缀里本轮纳入"必须带凭据"的子集(逗号分隔)。留空 = 全部 USER_TOOL_PREFIXES 都纳入,
|
||||
* 与 user-tool-guard-enabled 单独打开的语义一致;列出若干前缀则只收这几条,其余留给
|
||||
* 客户端铺开后再收。
|
||||
*/
|
||||
@Value("${aiimage.security.user-tool-guard-prefixes:}")
|
||||
private String userToolGuardPrefixes;
|
||||
|
||||
@Value("${aiimage.security.admin-guard-exempt-prefixes:}")
|
||||
private String exemptPrefixes;
|
||||
|
||||
/** 用户态接口的数据归属参数:收紧前它由客户端随意填。 */
|
||||
private static final String USER_ID_PARAM = "user_id";
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
if (!enabled) {
|
||||
return true;
|
||||
}
|
||||
String uri = request.getRequestURI();
|
||||
if (!isGuarded(uri)) {
|
||||
if (!requiresCredential(uri) && !needsOwnershipBinding(request, uri)) {
|
||||
return true;
|
||||
}
|
||||
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||
@@ -148,27 +167,44 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
try {
|
||||
adminAuthSupport.requireUserOrInternal(request);
|
||||
} catch (BusinessException ex) {
|
||||
ApiResponse<Void> body = ex.getCode() == null
|
||||
? ApiResponse.fail(ex.getMessage())
|
||||
: ApiResponse.fail(ex.getCode(), ex.getMessage());
|
||||
// 401(登录已过期)与被顶下线是前端定时轮询(/api/notifications/summary、/api/user-secrets 等)
|
||||
// 的常态:线上单节点一天近 3000 条,会把真实业务错误淹没。与 GlobalExceptionHandler
|
||||
// 的 isRoutineAuthNoise 同一口径降为 debug。
|
||||
if (isRoutineAuthNoise(ex.getCode())) {
|
||||
log.debug("[admin-guard] {} {} rejected: {}", request.getMethod(), request.getRequestURI(), ex.getMessage());
|
||||
} else {
|
||||
log.warn("[admin-guard] {} {} rejected: {}", request.getMethod(), request.getRequestURI(), ex.getMessage());
|
||||
String uri = request.getRequestURI();
|
||||
AdminUserEntity identity = null;
|
||||
if (requiresCredential(uri)) {
|
||||
try {
|
||||
identity = adminAuthSupport.requireUserOrInternal(request);
|
||||
} catch (BusinessException ex) {
|
||||
Integer code = ex.getCode();
|
||||
// 401(登录已过期)与被顶下线是前端定时轮询(/api/notifications/summary、/api/user-secrets 等)
|
||||
// 的常态:线上单节点一天近 3000 条,会把真实业务错误淹没。与 GlobalExceptionHandler
|
||||
// 的 isRoutineAuthNoise 同一口径降为 debug。
|
||||
if (isRoutineAuthNoise(code)) {
|
||||
log.debug("[admin-guard] {} {} rejected: {}", request.getMethod(), uri, ex.getMessage());
|
||||
} else {
|
||||
log.warn("[admin-guard] {} {} rejected: {}", request.getMethod(), uri, ex.getMessage());
|
||||
}
|
||||
writeFailure(response, code, ex.getMessage());
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// 归属绑定只约束"能解析出身份"的请求:存量匿名客户端(不带 JWT)解析不出身份,行为不变。
|
||||
try {
|
||||
identity = adminAuthSupport.requireUserOrInternal(request);
|
||||
} catch (BusinessException absentOrExpired) {
|
||||
identity = null;
|
||||
}
|
||||
}
|
||||
if (identity != null && isUserToolPrefix(uri) && !mayActForOtherUsers(identity)) {
|
||||
String foreignUserId = foreignUserIdParam(request, identity);
|
||||
if (foreignUserId != null) {
|
||||
log.warn("[admin-guard] {} {} 拒绝:登录身份 id={} 与请求参数 {}={} 不一致,remoteAddr={}",
|
||||
request.getMethod(), uri, identity.getId(), USER_ID_PARAM, foreignUserId,
|
||||
request.getRemoteAddr());
|
||||
writeFailure(response, 403,
|
||||
"无权访问该 " + USER_ID_PARAM + " 的数据:登录账号与请求参数不一致,请重新登录");
|
||||
return;
|
||||
}
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(body));
|
||||
return;
|
||||
}
|
||||
// /debug/** 是应急/诊断入口,调用频次极低但敏感,单独留一条审计日志便于事后追溯
|
||||
String uri = request.getRequestURI();
|
||||
if (matchesPrefix(uri, DEBUG_PREFIX)) {
|
||||
log.warn("[debug-guard] {} {} 通过鉴权放行,remoteAddr={}",
|
||||
request.getMethod(), uri, request.getRemoteAddr());
|
||||
@@ -176,14 +212,43 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求参数里的 user_id 是否指向别人。非数字时返回 null,交回 controller 报它自己的错,
|
||||
* 守卫不抢着当格式校验器。
|
||||
*/
|
||||
private static String foreignUserIdParam(HttpServletRequest request, AdminUserEntity identity) {
|
||||
String raw = request.getParameter(USER_ID_PARAM);
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(raw.trim()) == identity.getId() ? null : raw.trim();
|
||||
} catch (NumberFormatException notNumeric) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 管理员/超管本来就是代客操作的(后台按客户查任务是常态),不参与绑定。 */
|
||||
private boolean mayActForOtherUsers(AdminUserEntity identity) {
|
||||
String role = adminAuthSupport.currentRole(identity);
|
||||
return "admin".equals(role) || "super_admin".equals(role);
|
||||
}
|
||||
|
||||
private void writeFailure(HttpServletResponse response, Integer code, String message) throws IOException {
|
||||
ApiResponse<Void> body = code == null ? ApiResponse.fail(message) : ApiResponse.fail(code, message);
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(body));
|
||||
}
|
||||
|
||||
/** 登录态过期 / 被其他设备顶下线:前端轮询的常态噪声,不占 WARN。 */
|
||||
private static boolean isRoutineAuthNoise(Integer code) {
|
||||
return Integer.valueOf(401).equals(code)
|
||||
|| Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code);
|
||||
}
|
||||
|
||||
/** 命中受保护前缀(/api/admin、/debug、自助接口、用户态工具前缀及其子路径)才进入鉴权,其余请求直接放行。 */
|
||||
private boolean isGuarded(String uri) {
|
||||
/** 必须解析出身份才放行的前缀:/api/admin、/debug、自助接口,以及已纳入收紧清单的用户态前缀。 */
|
||||
private boolean requiresCredential(String uri) {
|
||||
if (matchesPrefix(uri, ADMIN_API_PREFIX) || matchesPrefix(uri, DEBUG_PREFIX)) {
|
||||
return true;
|
||||
}
|
||||
@@ -192,9 +257,19 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!userToolGuardEnabled) {
|
||||
return userToolGuardEnabled && isUserToolPrefix(uri) && listedForGuard(uri);
|
||||
}
|
||||
|
||||
/** 未强制要求凭据的用户态前缀:只要带了 user_id 参数,归属就得和令牌身份对齐。 */
|
||||
private boolean needsOwnershipBinding(HttpServletRequest request, String uri) {
|
||||
if (!isUserToolPrefix(uri)) {
|
||||
return false;
|
||||
}
|
||||
String raw = request.getParameter(USER_ID_PARAM);
|
||||
return raw != null && !raw.isBlank();
|
||||
}
|
||||
|
||||
private boolean isUserToolPrefix(String uri) {
|
||||
for (String prefix : USER_TOOL_PREFIXES) {
|
||||
if (matchesPrefix(uri, prefix)) {
|
||||
return true;
|
||||
@@ -203,15 +278,33 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** user-tool-guard-prefixes 留空时沿用"全量用户态前缀"语义,列出若干则只收这几条。 */
|
||||
private boolean listedForGuard(String uri) {
|
||||
Set<String> listed = splitToSet(userToolGuardPrefixes);
|
||||
if (listed.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
for (String prefix : listed) {
|
||||
if (matchesPrefix(uri, prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean matchesPrefix(String uri, String prefix) {
|
||||
return uri.equals(prefix) || uri.startsWith(prefix + "/");
|
||||
}
|
||||
|
||||
private Set<String> exemptSet() {
|
||||
if (exemptPrefixes == null || exemptPrefixes.isBlank()) {
|
||||
return splitToSet(exemptPrefixes);
|
||||
}
|
||||
|
||||
private static Set<String> splitToSet(String csv) {
|
||||
if (csv == null || csv.isBlank()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return Arrays.stream(exemptPrefixes.split(","))
|
||||
return Arrays.stream(csv.split(","))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Reference in New Issue
Block a user