diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/security/AdminAuthSupport.java b/backend-java/src/main/java/com/nanri/aiimage/common/security/AdminAuthSupport.java index 106a2728d..2891e087d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/security/AdminAuthSupport.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/security/AdminAuthSupport.java @@ -50,10 +50,13 @@ public class AdminAuthSupport { if (token == null || token.isBlank()) { throw new BusinessException(401, "未登录"); } - Claims claims = jwtService.parse(token); - if (claims == null) { + JwtService.ParseResult parsed = jwtService.parseWithVerdict(token); + if (parsed.verdict() == JwtService.Verdict.INVALID) { throw new BusinessException(401, "登录已过期,请重新登录"); } + // 三态里只有「签名有效但已过期」继续往下走,且最终仍要被 tolerateExpiredSession 拦住; + // 伪造与格式错在这里就出局,与改造前逐字同语义 + Claims claims = parsed.claims(); Long userId; try { userId = Long.parseLong(claims.getSubject()); @@ -62,8 +65,12 @@ public class AdminAuthSupport { } AdminUserEntity user = adminUserMapper.selectById(userId); if (user == null) { + // 硬删账号会留下孤儿在跑行:认人必须排在容忍之前,否则已删账号被自己的孤儿行继续供着 throw new BusinessException(401, "用户不存在"); } + // 吊销先于单设备比对:那条路径第一行就是 if (exempt) return;(超管豁免), + // 把吊销挂在它下面等于超管永不见吊销 + DeviceSessionPolicy.assertNotRevoked(user.getMachine(), user.getId(), user.getUsername()); // 单设备登录:被新设备顶下线的旧 token 在此统一拦截(全站 requireUser 调用点自动生效) if (authProperties.isSingleDeviceEnabled()) { DeviceSessionPolicy.assertSameDevice(user.getMachine(), DeviceSessionPolicy.claimDeviceId(claims), @@ -73,9 +80,36 @@ public class AdminAuthSupport { // 到期拦截(含级联):管理员过期→组下账户停、公司超管过期→全公司停。 // 任务心跳接口刻意匿名、不走本方法,过期账号的在跑任务仍能靠 alive=false 协作停止。 accountExpiryService.assertSessionAllowed(user); + if (parsed.isExpiredSigned()) { + tolerateExpiredSession(user, claims); + } return user; } + /** + * 容忍不是宽限:只有确有任务在 15 分钟内还在跑,才让这张过期令牌再活一次。 + * + *
读库失败(含 {@code timeout="2"} 超时)按「没有在跑」处理——这条分支的默认方向必须是拒绝, + * 否则一次库抖动就把"过期即拒"变成"过期即放行"。
+ * + *命中打 {@code [session-tolerance]} 日志:上线后要回答"到底放行了多少次、放行了谁"只能靠它。
+ */ + private void tolerateExpiredSession(AdminUserEntity user, Claims claims) { + String deviceId = DeviceSessionPolicy.claimDeviceId(claims); + int live; + try { + live = adminUserMapper.countLiveWorkFor(user.getId(), deviceId); + } catch (RuntimeException e) { + log.warn("[session-tolerance] 在跑判定读库失败,按拒绝处理 userId={} err={}", user.getId(), e); + live = 0; + } + if (live <= 0) { + throw new BusinessException(401, "登录已过期,请重新登录"); + } + log.info("[session-tolerance] 容忍已过期令牌 userId={} username={} liveWork={} device={}", + user.getId(), user.getUsername(), live, deviceId); + } + /** * 解析当前请求 JWT 中**签名的**设备标识(deviceId claim);识别不出时返回空串。 * diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportConsoleEntryTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportConsoleEntryTest.java index 347dc24f8..0b1f07ddd 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportConsoleEntryTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportConsoleEntryTest.java @@ -150,6 +150,8 @@ class AdminAuthSupportConsoleEntryTest { when(claims.getSubject()).thenReturn(String.valueOf(user.getId())); when(claims.get("deviceId")).thenReturn("devA"); when(jwtService.parse("t")).thenReturn(claims); + when(jwtService.parseWithVerdict("t")).thenReturn( + new JwtService.ParseResult(JwtService.Verdict.VALID, claims)); when(userMapper.selectById(user.getId())).thenReturn(user); when(props.isSingleDeviceEnabled()).thenReturn(false); return new AdminAuthSupport(jwtService, userMapper, props, mock(AccountExpiryService.class)); diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportOwnershipTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportOwnershipTest.java index c3ec5eedf..a927baf05 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportOwnershipTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportOwnershipTest.java @@ -184,6 +184,9 @@ class AdminAuthSupportOwnershipTest { private AdminAuthSupport internalTokenSupport(AdminUserMapper userMapper) { JwtService jwtService = mock(JwtService.class); when(jwtService.parse(any())).thenReturn(null); + // 原语义是「一律解析失败」:三态里对应 INVALID,不许留 null(requireUser 会 NPE) + when(jwtService.parseWithVerdict(any())).thenReturn( + new JwtService.ParseResult(JwtService.Verdict.INVALID, null)); AdminAuthSupport support = new AdminAuthSupport( jwtService, userMapper, mock(AuthProperties.class), mock(AccountExpiryService.class)); ReflectionTestUtils.setField(support, "internalToken", INTERNAL_TOKEN); @@ -196,6 +199,8 @@ class AdminAuthSupportOwnershipTest { Claims claims = mock(Claims.class); when(claims.getSubject()).thenReturn(String.valueOf(user.getId())); when(jwtService.parse("t")).thenReturn(claims); + when(jwtService.parseWithVerdict("t")).thenReturn( + new JwtService.ParseResult(JwtService.Verdict.VALID, claims)); AdminUserMapper userMapper = mock(AdminUserMapper.class); when(userMapper.selectById(user.getId())).thenReturn(user); AuthProperties props = mock(AuthProperties.class); diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportTest.java index 3f8345c7e..1acee3c0f 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/common/security/AdminAuthSupportTest.java @@ -207,6 +207,8 @@ class AdminAuthSupportTest { when(claims.getSubject()).thenReturn(String.valueOf(user.getId())); when(claims.get("deviceId")).thenReturn(claimDeviceId); when(jwtService.parse("t")).thenReturn(claims); + when(jwtService.parseWithVerdict("t")).thenReturn( + new JwtService.ParseResult(JwtService.Verdict.VALID, claims)); when(userMapper.selectById(user.getId())).thenReturn(user); when(props.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled); diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/security/SessionToleranceTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/security/SessionToleranceTest.java new file mode 100644 index 000000000..703d547ec --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/common/security/SessionToleranceTest.java @@ -0,0 +1,137 @@ +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 jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; + +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.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * 容忍的口径只有一句:确有任务在跑,才让这张过期令牌再活一次。 + * 这里逐条钉四个条件与判定顺序,尤其钉「读库失败也放行」这种最容易写错的形状。 + */ +class SessionToleranceTest { + + private static final String EXPIRED_MSG = "登录已过期,请重新登录"; + + private final JwtService jwt = mock(JwtService.class); + private final AdminUserMapper mapper = mock(AdminUserMapper.class); + private final AccountExpiryService expiry = mock(AccountExpiryService.class); + + private AdminAuthSupport support() { + AuthProperties props = new AuthProperties(); + props.setSingleDeviceEnabled(true); + // 既有 4 参构造:故意不给 AdminAuthSupport 加第 5 个依赖,否则现网 11 处构造点全要跟着改 + return new AdminAuthSupport(jwt, mapper, props, expiry); + } + + private JwtService.ParseResult expired(String deviceId) { + return new JwtService.ParseResult(JwtService.Verdict.EXPIRED_SIGNED, claims(deviceId)); + } + + private Claims claims(String deviceId) { + Claims claims = mock(Claims.class); + when(claims.getSubject()).thenReturn("9"); + when(claims.get("deviceId")).thenReturn(deviceId); + return claims; + } + + private AdminUserEntity stored(String machine) { + AdminUserEntity user = new AdminUserEntity(); + user.setId(9L); + user.setUsername("小魏16"); + user.setMachine(machine); + user.setRole("user"); + user.setIsAdmin(0); + return user; + } + + private HttpServletRequest request() { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer whatever"); + return request; + } + + private void stubVerdict(JwtService.ParseResult result, AdminUserEntity user) { + when(jwt.parseWithVerdict(any())).thenReturn(result); + when(mapper.selectById(9L)).thenReturn(user); + } + + @Test + void expiredTokenWithLiveWorkIsAccepted() { + AdminUserEntity user = stored("dev-1"); + stubVerdict(expired("dev-1"), user); + when(mapper.countLiveWorkFor(9L, "dev-1")).thenReturn(1); + assertThat(support().requireUser(request())).isSameAs(user); + verify(expiry).assertSessionAllowed(user); // 到期/停用那条闸照旧跑过 + } + + @Test + void expiredTokenWithoutLiveWorkIsRejected() { + // 反向钉子:只有麦象在排队(aiimage 里没有行)时不许放行——排队态本期不算 + stubVerdict(expired("dev-1"), stored("dev-1")); + when(mapper.countLiveWorkFor(9L, "dev-1")).thenReturn(0); + BusinessException e = catchThrowableOfType(() -> support().requireUser(request()), BusinessException.class); + assertThat(e).isNotNull(); + assertThat(e.getCode()).isEqualTo(401); + assertThat(e.getMessage()).isEqualTo(EXPIRED_MSG); + } + + @Test + void liveWorkQueryFailureFailsClosed() { + // 读库异常/超时 → 按「没有在跑」处理:仍是 401,绝不 500、绝不因读不到而放行 + stubVerdict(expired("dev-1"), stored("dev-1")); + when(mapper.countLiveWorkFor(9L, "dev-1")).thenThrow(new RuntimeException("timeout 2000ms")); + BusinessException e = catchThrowableOfType(() -> support().requireUser(request()), BusinessException.class); + assertThat(e).isNotNull(); + assertThat(e.getCode()).isEqualTo(401); + } + + @Test + void deletedAccountWithOrphanLiveRowIsStillRejected() { + // 账号硬删、无外键,会留下孤儿 RUNNING 行:认人必须排在容忍之前 + JwtService.ParseResult result = expired("dev-1"); + when(jwt.parseWithVerdict(any())).thenReturn(result); + when(mapper.selectById(9L)).thenReturn(null); + BusinessException e = catchThrowableOfType(() -> support().requireUser(request()), BusinessException.class); + assertThat(e).isNotNull(); + assertThat(e.getMessage()).isEqualTo("用户不存在"); + verify(mapper, never()).countLiveWorkFor(anyLong(), any()); + } + + @Test + void revokedMachineIsRejectedEvenForSuperAdminAndNeverAsksLiveWork() { + // 超管在 DeviceSessionPolicy 里是 exempt 直接 return:吊销若挂在那条路径之后就会对超管失明 + AdminUserEntity admin = stored("revoked@1#20261009120000"); + admin.setRole("super_admin"); + admin.setIsAdmin(1); + stubVerdict(expired("dev-1"), admin); + when(mapper.countLiveWorkFor(9L, "dev-1")).thenReturn(3); + BusinessException e = catchThrowableOfType(() -> support().requireUser(request()), BusinessException.class); + assertThat(e).isNotNull(); + assertThat(e.getCode()).isEqualTo(401); + verify(mapper, never()).countLiveWorkFor(anyLong(), any()); + } + + @Test + void freshTokenNeverTouchesLiveWorkQuery() { + // 正常路径零额外开销:容忍查询只可能发生在「过期」这条稀有分支上 + AdminUserEntity user = stored("dev-1"); + JwtService.ParseResult valid = new JwtService.ParseResult(JwtService.Verdict.VALID, claims("dev-1")); + when(jwt.parseWithVerdict(any())).thenReturn(valid); + when(mapper.selectById(9L)).thenReturn(user); + assertThat(support().requireUser(request())).isSameAs(user); + verify(mapper, never()).countLiveWorkFor(anyLong(), any()); + } +}