fix(鉴权): 任务归属身份从会话推导,user_id 与不符即 403

客户端任务接口原先把"这单是谁的"交给调用方自报:请求体/查询串带 user_id,服务端拿它当范围
条件。身份应只信会话(JWT),桌面执行器与内部代理通道也不例外:

- AdminAuthSupport 增加 mayActForOtherUsers / resolveOwnershipUserId /
  requireOwnershipUserId / bindOwnershipUserId:会话身份与请求 user_id 不一致直接 403,
  只有平台超管与被授权管理员能代他人;
- 上架(PublishController/PublishTaskService)先接:user_id 缺失即 401,
  仅两个桌面执行器端点允许留空;外观专利/相似 ASIN 的归属谓词补上
  Objects.equals(userId, task.getUserId()),不再只比 moduleType;
- AdminApiGuardFilter 把入口口径与新helper 对齐,护栏测试 AdminAuthSupportOwnershipTest +
  PublishOwnershipGuardrailTest 双向钉(放行面与拒绝面都有样本)。

同族的进度类模块(原先仍以请求体 user_id 为范围)在 cp-item7 一次接完;这一支只管会改状态/花钱的出口。
另外 resolveOwnershipUserId 的 [ownership-anonymous] 日志按 URI 限流也在这支——桌面执行器 4.0.44
不带凭据,只有分得清是哪个端点在打匿名请求,才敢逐支把它们从 resolve 换成 require。
This commit is contained in:
2026-10-07 20:01:10 +08:00
parent 54411c6446
commit 7c7a7f2665
9 changed files with 577 additions and 43 deletions
@@ -0,0 +1,221 @@
package com.nanri.aiimage.common.security;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import io.jsonwebtoken.Claims;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* 归属用户 id 由会话推导(2026-10-07)的六面判定。
*
* <p>背景:用户态工具接口把"这批数据属于谁"完全交给请求参数 {@code user_id},
* 前端从 localStorage 取一个数字填进去,改这个数字就能读别人的任务。
* {@link AdminAuthSupport#resolveOwnershipUserId} 与 {@link AdminAuthSupport#requireOwnershipUserId}
* 把这层关系反过来:先认会话身份,参数只是兼容性输入。</p>
*
* <p>两个变体的分工必须是可证的,否则"fail-closed"只是一句注释:
* resolve 给还带不动凭据的存量客户端留窗口(解析不出身份就原样返回),
* require 只用在已取证**没有匿名调用方**的端点上(解析不出身份即 401)。</p>
*/
class AdminAuthSupportOwnershipTest {
private static final String INTERNAL_TOKEN = "internal-token-value";
// ---------- 会话身份优先:参数缺省 / 一致 / 冒名 ----------
@Test
void sessionIdentityFillsInOmittedUserId() {
AdminAuthSupport support = withJwtUser(user(7L, "normal", 0, null));
assertThat(support.resolveOwnershipUserId(jwtRequest("t"), null)).isEqualTo(7L);
}
@Test
void matchingUserIdIsPassedThroughUnchanged() {
AdminAuthSupport support = withJwtUser(user(7L, "normal", 0, null));
assertThat(support.resolveOwnershipUserId(jwtRequest("t"), 7L)).isEqualTo(7L);
}
@Test
void foreignUserIdIsRejectedWith403NotSilentlyTrusted() {
AdminAuthSupport support = withJwtUser(user(7L, "normal", 0, null));
BusinessException ex = catchThrowableOfType(
() -> support.resolveOwnershipUserId(jwtRequest("t"), 8L), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(403);
assertThat(ex.getMessage()).contains("user_id");
}
/** 冒名在 require 变体上是同一个结果:不能因为"这个端点要求登录"就漏掉归属比对。 */
@Test
void requireVariantRejectsForeignUserIdToo() {
AdminAuthSupport support = withJwtUser(user(7L, "normal", 0, null));
BusinessException ex = catchThrowableOfType(
() -> support.requireOwnershipUserId(jwtRequest("t"), 8L), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(403);
}
// ---------- 管理角色豁免:但不得替它凭空造一个归属 ----------
@Test
void adminMayActForAnotherUser() {
AdminAuthSupport support = withJwtUser(user(1L, "admin", 1, 1L));
assertThat(support.resolveOwnershipUserId(jwtRequest("t"), 8L)).isEqualTo(8L);
}
/**
* 公司超管与超管在业务数据面逻辑一致(2026-10-07 口径)。
* 上一版豁免逐个列角色名,漏了 company_super_admin,公司超管在网页端按客户查任务被自己的守卫挡成 403。
*/
@Test
void companySuperAdminIsExemptedToo() {
AdminAuthSupport support = withJwtUser(user(2L, "company_super_admin", 0, 1L));
assertThat(support.resolveOwnershipUserId(jwtRequest("t"), 8L)).isEqualTo(8L);
assertThat(support.mayActForOtherUsers(user(2L, "company_super_admin", 0, 1L))).isTrue();
}
/** 管理角色不传 user_id 时保持"不预设范围",而不是悄悄换成它自己的 id(后台默认看全量)。 */
@Test
void adminOmittingUserIdGetsNoImplicitOwner() {
AdminAuthSupport support = withJwtUser(user(1L, "super_admin", 1, null));
assertThat(support.resolveOwnershipUserId(jwtRequest("t"), null)).isNull();
}
@Test
void ordinaryRoleIsNotExemptedFromBinding() {
AdminAuthSupport support = withJwtUser(user(7L, "normal", 1, 1L));
assertThat(support.mayActForOtherUsers(user(7L, "normal", 1, 1L))).isFalse();
assertThat(support.mayActForOtherUsers(null)).isFalse();
}
// ---------- 两个变体的分界线:解析不出身份时 ----------
/** 存量桌面客户端不带凭据:resolve 必须原样返回,否则线上集采/跟价整条 401。 */
@Test
void resolveKeepsRequestParamWhenNoIdentityResolves() {
AdminAuthSupport support = withJwtUser(user(7L, "normal", 0, null));
assertThat(support.resolveOwnershipUserId(new MockHttpServletRequest("GET", "/api/publish/tasks/1/items"), 8L))
.isEqualTo(8L);
}
/** require 正相反:没登录就没有"归属"可谈,直接 401。 */
@Test
void requireRejectsAnonymousWith401() {
AdminAuthSupport support = withJwtUser(user(7L, "normal", 0, null));
BusinessException ex = catchThrowableOfType(
() -> support.requireOwnershipUserId(new MockHttpServletRequest("GET", "/api/publish/dashboard"), 8L),
BusinessException.class);
assertThat(ex.getCode()).isEqualTo(401);
}
// ---------- 内部令牌不是冒名通行证 ----------
/**
* X-Internal-Token + operatorId 解析得出身份后按该身份绑定:令牌是硬编码在分发包里的静态密钥,
* 证明得了"走了内部通道",证明不了"这个 user_id 是谁"。
*/
@Test
void internalOperatorIsBoundToItsOwnIdentity() {
AdminUserMapper userMapper = mock(AdminUserMapper.class);
when(userMapper.selectById(3L)).thenReturn(user(3L, "normal", 0, null));
AdminAuthSupport support = internalTokenSupport(userMapper);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/publish/tasks/1/items");
request.addHeader("X-Internal-Token", INTERNAL_TOKEN);
request.setParameter("operatorId", "3");
BusinessException ex = catchThrowableOfType(
() -> support.resolveOwnershipUserId(request, 8L), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(403);
}
/** 纯令牌(不带 JWT、不带 operatorId)解析不出身份 —— 这条形状是存量客户端的实际形态,必须零影响。 */
@Test
void internalTokenWithoutOperatorIdStaysUnbound() {
AdminAuthSupport support = internalTokenSupport(defaultMapper());
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/publish/tasks/1/result");
request.addHeader("X-Internal-Token", INTERNAL_TOKEN);
assertThat(support.resolveOwnershipUserId(request, 8L)).isEqualTo(8L);
}
@Test
void untrustedTokenIsNotAnInternalIdentity() {
AdminAuthSupport support = internalTokenSupport(defaultMapper());
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/publish/dashboard");
request.addHeader("X-Internal-Token", "guessed-token");
assertThat(support.resolveOwnershipUserId(request, 8L)).isEqualTo(8L);
BusinessException ex = catchThrowableOfType(
() -> support.requireOwnershipUserId(request, 8L), BusinessException.class);
assertThat(ex.getCode()).isEqualTo(401);
}
// ---------- 夹具 ----------
private AdminUserMapper defaultMapper() {
AdminUserMapper userMapper = mock(AdminUserMapper.class);
when(userMapper.selectById(any())).thenReturn(null);
return userMapper;
}
/** 只装内部令牌通道:JWT 一律解析失败,用来单独验操作者身份那半条链。 */
private AdminAuthSupport internalTokenSupport(AdminUserMapper userMapper) {
JwtService jwtService = mock(JwtService.class);
when(jwtService.parse(any())).thenReturn(null);
AdminAuthSupport support = new AdminAuthSupport(
jwtService, userMapper, mock(AuthProperties.class), mock(AccountExpiryService.class));
ReflectionTestUtils.setField(support, "internalToken", INTERNAL_TOKEN);
ReflectionTestUtils.setField(support, "internalTokenFile", "");
return support;
}
private AdminAuthSupport withJwtUser(AdminUserEntity user) {
JwtService jwtService = mock(JwtService.class);
Claims claims = mock(Claims.class);
when(claims.getSubject()).thenReturn(String.valueOf(user.getId()));
when(jwtService.parse("t")).thenReturn(claims);
AdminUserMapper userMapper = mock(AdminUserMapper.class);
when(userMapper.selectById(user.getId())).thenReturn(user);
AuthProperties props = mock(AuthProperties.class);
when(props.isSingleDeviceEnabled()).thenReturn(false);
return new AdminAuthSupport(jwtService, userMapper, props, mock(AccountExpiryService.class));
}
private MockHttpServletRequest jwtRequest(String token) {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/publish/dashboard");
request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
return request;
}
private AdminUserEntity user(Long id, String role, int isAdmin, Long createdById) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setUsername("u" + id);
user.setRole(role);
user.setIsAdmin(isAdmin);
user.setCreatedById(createdById);
return user;
}
}
@@ -425,7 +425,9 @@ class AdminApiGuardFilterTest {
void adminJwtMayActForAnotherUser() throws Exception {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.requireUserOrInternal(any())).thenReturn(user(1L, "admin"));
when(authSupport.currentRole(any())).thenReturn("admin");
// 豁免判定只有一个出口(AdminAuthSupport.mayActForOtherUsers),守卫不再自己抄一份角色名单:
// 上一版这里 stub currentRole,改成委托后如果谁把两处又写回各判各的,这两支会一起红。
when(authSupport.mayActForOtherUsers(any())).thenReturn(true);
AdminApiGuardFilter filter = newFilter(authSupport, true, "", false);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/query-asin/tasks/detail");
request.setParameter("user_id", "8");
@@ -435,6 +437,7 @@ class AdminApiGuardFilterTest {
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
verify(authSupport).mayActForOtherUsers(any());
}
/** 桌面端不带 JWT、也就没有身份可绑:这条约束对存量匿名客户端零影响。 */
@@ -556,7 +559,7 @@ class AdminApiGuardFilterTest {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.isTrustedInternalToken(any())).thenReturn(true);
when(authSupport.requireUserOrInternal(any())).thenReturn(user(1L, "admin"));
when(authSupport.currentRole(any())).thenReturn("admin");
when(authSupport.mayActForOtherUsers(any())).thenReturn(true);
AdminApiGuardFilter filter = newFilter(authSupport, true, "", false);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/query-asin/tasks/detail");
request.setParameter("user_id", "8");
@@ -568,6 +571,63 @@ class AdminApiGuardFilterTest {
assertThat(chain.getRequest()).isNotNull();
}
// ---- /api/publish 纳入绑定(2026-10-07)----
// 取证:网页端调 publish 的 activate 三兄弟时**根本不传 user_id**
// (frontend-vue/src/shared/api/types/modules/publish.ts:180,189),桌面执行器只调
// items 与 result(app_client/amazon/add_product.py:973,1048)。此前 publish 一个都不在
// 守卫名单里,控制器也不 require*,匿名请求即可激活/删除任意任务。
@Test
void publishJwtCannotReadAnotherUsersItems() throws Exception {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.requireUserOrInternal(any())).thenReturn(user(7L, "normal"));
when(authSupport.mayActForOtherUsers(any())).thenReturn(false);
AdminApiGuardFilter filter = newFilter(authSupport, true, "", false);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/publish/tasks/9001/items");
request.setParameter("user_id", "8");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).as("带 JWT 却填别人的 user_id 必须挡下").isNull();
JsonNode body = objectMapper.readTree(response.getContentAsString());
assertThat(body.path("code").asInt()).isEqualTo(403);
}
/** 不带凭据的执行器(X-Internal-Token、无 operatorId、无 user_id)解析不出身份,绑定不触发。 */
@Test
void publishExecutorRequestWithoutIdentityIsNotBound() throws Exception {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.isTrustedInternalToken(any())).thenReturn(true);
when(authSupport.requireUserOrInternal(any())).thenThrow(new BusinessException(401, "未登录"));
AdminApiGuardFilter filter = newFilter(authSupport, true, "", false);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/publish/tasks/9001/items");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
assertThat(response.getContentAsString()).isEmpty();
}
/** 前缀边界:/publishing-tools 这类同前缀名字不能被卷进来。 */
@Test
void publishLikeOtherPathsAreNotSweptIn() throws Exception {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminApiGuardFilter filter = newFilter(authSupport, true, "", false);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/publishing-tools/list");
request.setParameter("user_id", "8");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
verify(authSupport, never()).requireUserOrInternal(any());
}
private AdminUserEntity user(Long id, String role) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
@@ -0,0 +1,134 @@
package com.nanri.aiimage.modules.publish.controller;
import com.nanri.aiimage.testutil.SourceScan;
import org.junit.jupiter.api.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 上架(publish)归属绑定的绊线(2026-10-07)。
*
* <p>publish 此前的形状:12 个端点没有一个在兜底守卫名单里,控制器不调 require*,
* {@code user_id} 要么可选要么由前端从 localStorage 取——也就是"数据属于谁"完全由请求说了算。
* 本轮收口后的形状必须是可证的,否则下次有人"顺手"改回参数判定不会有任何东西变红:</p>
*
* <ol>
* <li>带 user_id 的端点分母钉死(查询参数 8 个 + 请求体 4 个 = 12 个走会话推导)。
* 其中 10 个走 {@code requireOwnershipUserId}(解析不出登录身份即 401,网页端/后台专用),
* 2 个走 {@code resolveOwnershipUserId}——只有执行器可达的 {@code items}(取数)和
* {@code result}(回传):桌面端只带 X-Internal-Token、不带 operatorId,给它俩加 require
* 等于把上架整条链路挡在 401。resolve 对匿名请求是原样透传,对带凭据的请求仍然冒名即 403。</li>
* <li>"null 即跳过归属校验"这个形状在服务层只能剩 1 处(publish 的 requireTaskRecord,
* 为执行器留的口子),外观专利与货源的 4 处已改为无条件比对。</li>
* </ol>
*
* <p>数字判据一律打在 {@link SourceScan#withoutComments} 上:javadoc 里提一句 {@code requireOwnershipUserId}
* 就能把"次数等于 N"喂成假绿。只有"豁免必须写明理由"那支刻意吃原文,因为它要钉的就是注释本身。</p>
*/
class PublishOwnershipGuardrailTest {
private static final Pattern QUERY_USER_ID = Pattern.compile(
"@RequestParam\\(\\s*(?:value\\s*=\\s*)?\"user_id\"[^)]*\\)\\s+Long\\s+\\w+");
@Test
void everyUserIdCarryingPublishEndpointIsDerivedFromSession() {
String controller = SourceScan.withoutComments(SourceScan.sourceText("PublishController.java"));
Matcher query = QUERY_USER_ID.matcher(controller);
int queryBindings = 0;
while (query.find()) {
queryBindings++;
}
assertThat(queryBindings)
.as("publish 控制器里 user_id 查询参数绑定数")
.isEqualTo(8);
// 请求体里带 user_id 的四个:parse / progress/batch / progress/light / result
long bodyBindings = Stream.of("PublishParseRequest request",
"PublishTaskBatchRequest request",
"TaskProgressLightRequest request",
"PublishSubmitResultRequest request")
.filter(controller::contains)
.count();
assertThat(bodyBindings).as("publish 控制器里请求体带 user_id 的端点数").isEqualTo(4);
int require = count(controller, "adminAuthSupport.requireOwnershipUserId(");
int resolve = count(controller, "adminAuthSupport.resolveOwnershipUserId(");
assertThat(require)
.as("requireOwnershipUserId 调用数(网页端/后台专用,解析不出身份即 401)")
.isEqualTo(10);
assertThat(resolve)
.as("resolveOwnershipUserId 调用数(执行器可达的两条:items 取数、result 回传)")
.isEqualTo(2);
assertThat(require + resolve)
.as("12 个带归属的端点必须逐个接上会话推导,一个都不能只靠请求参数")
.isEqualTo(queryBindings + bodyBindings);
}
/**
* 执行器回传端点是刻意的例外:给它加 require 等于把上架整条链路挡在 401。
*
* <p>反向钉必须配一条正向取样,否则"方法体切不到"和"方法体真的没调用"这两种情况都是绿的。</p>
*/
@Test
void resultSubmissionStaysReachableWithoutLoginIdentity() {
String controller = SourceScan.withoutComments(SourceScan.sourceText("PublishController.java"));
String body = SourceScan.methodBody(controller, "submitResult");
assertThat(body)
.as("submitResult 只能走透传的 resolve(带凭据时依旧校验归属,匿名执行器不被 401)")
.contains("adminAuthSupport.resolveOwnershipUserId(");
assertThat(body)
.as("给 submitResult 加 require 会把无登录身份的桌面执行器挡在 401")
.doesNotContain("requireOwnershipUserId");
}
/** 同理,items 是执行器唯一的取数口,也只能透传、不能 require。 */
@Test
void executorReadPathStaysReachableWithoutLoginIdentity() {
String controller = SourceScan.withoutComments(SourceScan.sourceText("PublishController.java"));
String body = SourceScan.methodBody(controller, "items");
assertThat(body).contains("adminAuthSupport.resolveOwnershipUserId(");
assertThat(body).doesNotContain("requireOwnershipUserId");
}
/**
* "userId != null 才校验归属"在服务层只剩一处出口,且那一处必须带写明理由的注释
* (匿名执行器 items/result 走 requireTaskRecord)。
*/
@Test
void nullSkipsOwnershipCheckOnlyOnTheExecutorReadPath() {
String publishService = SourceScan.sourceText("PublishTaskService.java");
String publishCode = SourceScan.withoutComments(publishService);
String appearanceCode = SourceScan.withoutComments(SourceScan.sourceText("AppearancePatentTaskService.java"));
String similarAsinCode = SourceScan.withoutComments(SourceScan.sourceText("SimilarAsinTaskService.java"));
assertThat(count(appearanceCode, "userId != null && !Objects.equals(userId, task.getUserId())"))
.as("外观专利的两处条件归属校验必须已改成无条件比对")
.isZero();
assertThat(count(similarAsinCode, "userId != null && !Objects.equals(userId, task.getUserId())"))
.as("货源的两处条件归属校验必须已改成无条件比对")
.isZero();
assertThat(count(publishCode, "userId != null && !userId.equals(task.getUserId())"))
.as("publish 保留的那一处是唯一登记在册的口子,多一处就是有人新开了免校验通道")
.isEqualTo(1);
assertThat(publishService)
.as("保留口子必须写明它只服务于哪个匿名执行器路径(这支刻意扫原文:要钉的就是注释)")
.contains("GET /tasks/{id}/items 与 POST /tasks/{id}/result");
}
private static int count(String haystack, String needle) {
int index = 0;
int total = 0;
while ((index = haystack.indexOf(needle, index)) >= 0) {
total++;
index += needle.length();
}
return total;
}
}