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:
+221
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user