refactor(boundary): 跨模块循环依赖清零(8 对 → 0),task→业务 依赖归零
共享内核下沉(跨模块共享的"身份/组织/安全"类型进 common) - AdminUserEntity/AdminUserMapper、ShopManageGroupEntity/ShopManageGroupMapper → common - AdminAuthSupport(33 文件 17 模块引用)、JwtService、AuthProperties、DeviceSessionPolicy → common/security(原先放在 admin/auth 里,任何模块用一次就多一条跨模块边) 端口化(消费方声明接口、数据方实现) - task/spi:ResultFileJobHandler 新增 resolveResultFileUrl 钩子(BRAND 特例从 Worker 收回); Worker 改为调用 handler.onSuccess(该钩子历史上从未被调用,withdraw 的收尾靠 Worker 里的 WITHDRAW 特判硬编码——现两者都归位,task 侧不再 import withdraw/brand) - admin/spi/UserSecretCleanupPort(删除用户级联清理密钥)、notification/spi/ProxyBalancePort (代理余额探测)、shopdatacrawl/spi/ManagedShopNamesPort(可管店铺名) - shopkey/spi/GroupDeletionGuardPort:分组删除守卫改由各业务模块实现(invalidasin/dedupe 两个实现), shopkey 不再直连它们的 Mapper 棘轮与量化(2026-09-14 实测) - ArchitectureBoundaryTest:task→业务 119 → **0**(基线钉死为 0,新增跨模块动作必须走 task/spi) - 跨模块 import 行数 650 → 605;双向依赖对 8 → **0**(usersecret/permission/shopkey 三向环、 task↔withdraw、task↔brand、admin↔permission、admin↔usersecret、dedup↔shopkey、 invalidasin↔shopkey、notification↔usersecret、shopdatacrawl↔shopduplicatecheck 全部拆解) 测试同步:接口契约 8→9、品牌 Handler 钩子契约、worker 的 10 个测试构造实参、通知/管理测试端口化。 mvn test 2881 全绿。
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.JwtService;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.nanri.aiimage.common.security.AuthProperties;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAuthSupport {
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final AuthProperties authProperties;
|
||||
|
||||
@Value("${aiimage.security.internal-token:}")
|
||||
private String internalToken;
|
||||
|
||||
@Value("${aiimage.security.internal-token-file:}")
|
||||
private String internalTokenFile;
|
||||
|
||||
/** 解析当前请求的用户;token 缺失或无效抛 401。 */
|
||||
public AdminUserEntity requireUser(HttpServletRequest request) {
|
||||
String token = resolveToken(request);
|
||||
if (token == null || token.isBlank()) {
|
||||
throw new BusinessException(401, "未登录");
|
||||
}
|
||||
Claims claims = jwtService.parse(token);
|
||||
if (claims == null) {
|
||||
throw new BusinessException(401, "登录已过期,请重新登录");
|
||||
}
|
||||
Long userId;
|
||||
try {
|
||||
userId = Long.parseLong(claims.getSubject());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException(401, "登录态无效");
|
||||
}
|
||||
AdminUserEntity user = adminUserMapper.selectById(userId);
|
||||
if (user == null) {
|
||||
throw new BusinessException(401, "用户不存在");
|
||||
}
|
||||
// 单设备登录:被新设备顶下线的旧 token 在此统一拦截(全站 requireUser 调用点自动生效)
|
||||
if (authProperties.isSingleDeviceEnabled()) {
|
||||
DeviceSessionPolicy.assertSameDevice(user.getMachine(), DeviceSessionPolicy.claimDeviceId(claims),
|
||||
DeviceSessionPolicy.isSuperAdmin(user.getRole(), user.getIsAdmin(), user.getCreatedById()),
|
||||
user.getId(), user.getUsername());
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/** 当前用户必须是管理员或超级管理员,否则抛 403。 */
|
||||
public AdminUserEntity requireAdmin(HttpServletRequest request) {
|
||||
AdminUserEntity user = requireUser(request);
|
||||
String role = currentRole(user);
|
||||
if (role == null) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/** 计算当前用户的管理角色:super_admin / admin / null。 */
|
||||
public String currentRole(AdminUserEntity user) {
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
return DeviceSessionPolicy.resolveRole(user.getRole(), user.getIsAdmin(), user.getCreatedById());
|
||||
}
|
||||
|
||||
/** JWT 优先;无 JWT 时以可信内部代理身份(X-Internal-Token + operatorId)回退,仍要求管理员角色。 */
|
||||
public AdminUserEntity requireAdminOrInternal(HttpServletRequest request) {
|
||||
try {
|
||||
return requireAdmin(request);
|
||||
} catch (BusinessException authFailure) {
|
||||
AdminUserEntity internalOperator = resolveInternalOperator(request, true);
|
||||
if (internalOperator != null) {
|
||||
return internalOperator;
|
||||
}
|
||||
throw authFailure;
|
||||
}
|
||||
}
|
||||
|
||||
/** JWT 优先;无 JWT 时以可信内部代理身份回退(仅要求用户存在)。 */
|
||||
public AdminUserEntity requireUserOrInternal(HttpServletRequest request) {
|
||||
try {
|
||||
return requireUser(request);
|
||||
} catch (BusinessException authFailure) {
|
||||
AdminUserEntity internalOperator = resolveInternalOperator(request, false);
|
||||
if (internalOperator != null) {
|
||||
return internalOperator;
|
||||
}
|
||||
throw authFailure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flask 传统后台用 session 登录、无法签发 Java JWT,只能凭共享密钥
|
||||
* (显式配置或每个用户的本地 token 文件)标识已认证管理员。这里仍会
|
||||
* 回库校验管理员角色,superAdmin 查询标志不参与判定。
|
||||
*/
|
||||
private AdminUserEntity resolveInternalOperator(HttpServletRequest request, boolean requireAdmin) {
|
||||
if (!isTrustedInternalRequest(request)) {
|
||||
return null;
|
||||
}
|
||||
String rawOperatorId = request.getParameter("operatorId");
|
||||
if (rawOperatorId == null || rawOperatorId.isBlank()) {
|
||||
rawOperatorId = request.getParameter("operator_id");
|
||||
}
|
||||
if (rawOperatorId == null || rawOperatorId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Long operatorId = Long.parseLong(rawOperatorId.trim());
|
||||
AdminUserEntity operator = adminUserMapper.selectById(operatorId);
|
||||
if (operator == null) {
|
||||
return null;
|
||||
}
|
||||
if (requireAdmin && currentRole(operator) == null) {
|
||||
return null;
|
||||
}
|
||||
return operator;
|
||||
} catch (NumberFormatException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isTrustedInternalRequest(HttpServletRequest request) {
|
||||
String suppliedToken = request.getHeader("X-Internal-Token");
|
||||
String expectedToken = resolveExpectedInternalToken();
|
||||
if (expectedToken.isBlank() || suppliedToken == null || suppliedToken.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
// 常量时间比较:逐字节 equals 可被计时侧信道逐位试探出内部令牌
|
||||
return java.security.MessageDigest.isEqual(
|
||||
expectedToken.getBytes(java.nio.charset.StandardCharsets.UTF_8),
|
||||
suppliedToken.trim().getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅判断请求是否携带可信内部令牌(不要求 operatorId)。供 AdminApiGuardFilter
|
||||
* 在兜底鉴权前放行内部自动化调用(仅凭 X-Internal-Token 即鉴权的端点,如
|
||||
* /api/admin/shop-manages/credential 由 controller 自校验令牌),
|
||||
* 避免 guard 把合法的内部调用误拦为 401。
|
||||
*/
|
||||
public boolean isTrustedInternalToken(HttpServletRequest request) {
|
||||
return isTrustedInternalRequest(request);
|
||||
}
|
||||
|
||||
private String resolveExpectedInternalToken() {
|
||||
if (internalToken != null && !internalToken.isBlank()) {
|
||||
return internalToken.trim();
|
||||
}
|
||||
Path path = resolveInternalTokenFile();
|
||||
if (path == null || !Files.isRegularFile(path)) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return Files.readString(path, StandardCharsets.UTF_8).trim();
|
||||
} catch (Exception ignored) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private Path resolveInternalTokenFile() {
|
||||
String configuredPath = internalTokenFile == null ? "" : internalTokenFile.trim();
|
||||
if (!configuredPath.isEmpty()) {
|
||||
if (configuredPath.equals("~") || configuredPath.startsWith("~/") || configuredPath.startsWith("~\\")) {
|
||||
String userHome = System.getProperty("user.home", "").trim();
|
||||
if (userHome.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
configuredPath = configuredPath.length() == 1
|
||||
? userHome
|
||||
: Path.of(userHome, configuredPath.substring(2)).toString();
|
||||
}
|
||||
Path configuredTokenPath = Path.of(configuredPath);
|
||||
return configuredTokenPath.isAbsolute() ? configuredTokenPath.normalize() : null;
|
||||
}
|
||||
String userHome = System.getProperty("user.home", "").trim();
|
||||
return userHome.isEmpty()
|
||||
? null
|
||||
: Path.of(userHome, ".aiimage", "internal-token").toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String t = authHeader.substring(7).trim();
|
||||
if (!t.isEmpty()) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) {
|
||||
return null;
|
||||
}
|
||||
String cookieName = authProperties.getCookieName();
|
||||
for (Cookie cookie : cookies) {
|
||||
if (cookieName.equals(cookie.getName())) {
|
||||
return cookie.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "aiimage.auth")
|
||||
public class AuthProperties {
|
||||
|
||||
private String jwtSecret = "please-change-this-secret-please-rotate-at-least-32-bytes";
|
||||
private long jwtTtlHours = 168L;
|
||||
private String cookieName = "aiimage_token";
|
||||
private boolean cookieSecure = false;
|
||||
private String cookieSameSite = "Lax";
|
||||
/** 单设备登录(互踢)总开关:关闭后恢复为多设备同时在线(回滚用)。 */
|
||||
private boolean singleDeviceEnabled = true;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 单设备登录(互踢)策略。
|
||||
*
|
||||
* <p>账号当前绑定的设备存放在 users.machine(登录成功即覆盖,last-login-wins);
|
||||
* 非超管账号仅允许「token 内签名的 deviceId」与绑定设备一致的请求通过,
|
||||
* 被新设备顶下线的旧 token 在下一次受保护请求时抛 4011。</p>
|
||||
*
|
||||
* <p>校验只认 token 内签名的 deviceId,绝不使用 X-Device-Id 请求头(头是客户端可控的)。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
public final class DeviceSessionPolicy {
|
||||
|
||||
/** 账号已在其他设备登录(前端据此提示并下线本设备)。 */
|
||||
public static final int CODE_KICKED = 4011;
|
||||
|
||||
private DeviceSessionPolicy() {
|
||||
}
|
||||
|
||||
/** 计算用户管理角色:super_admin / admin / null(含老数据 role 为空时按 created_by_id 推断)。 */
|
||||
public static String resolveRole(String role, Integer isAdmin, Long createdById) {
|
||||
String storedRole = role == null ? "" : role.trim().toLowerCase();
|
||||
if ("super_admin".equals(storedRole)) {
|
||||
return "super_admin";
|
||||
}
|
||||
if ("admin".equals(storedRole)) {
|
||||
return "admin";
|
||||
}
|
||||
boolean isAdminFlag = isAdmin != null && isAdmin == 1;
|
||||
if (storedRole.isEmpty() && isAdminFlag) {
|
||||
return createdById == null ? "super_admin" : "admin";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 是否超级管理员(互踢的唯一豁免角色)。 */
|
||||
public static boolean isSuperAdmin(String role, Integer isAdmin, Long createdById) {
|
||||
return "super_admin".equals(resolveRole(role, isAdmin, createdById));
|
||||
}
|
||||
|
||||
/** 从 JWT claims 中提取签名的设备号;缺失返回空串。 */
|
||||
public static String claimDeviceId(Claims claims) {
|
||||
Object raw = claims == null ? null : claims.get("deviceId");
|
||||
return raw == null ? "" : raw.toString().trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验请求携带的 token 是否仍属于账号当前绑定的设备。
|
||||
* 超管豁免;machine 为空(尚未绑定)放行;不匹配抛 4011。
|
||||
*/
|
||||
public static void assertSameDevice(String storedMachine, String claimDeviceId, boolean exempt,
|
||||
Long userId, String username) {
|
||||
if (exempt) {
|
||||
return;
|
||||
}
|
||||
String bound = storedMachine == null ? "" : storedMachine.trim();
|
||||
if (bound.isEmpty()) {
|
||||
// 尚未绑定(首次登录前 / V118 清空后首个登录前),不做限制
|
||||
return;
|
||||
}
|
||||
String claimed = claimDeviceId == null ? "" : claimDeviceId.trim();
|
||||
if (claimed.isEmpty()) {
|
||||
log.warn("[auth] 单设备登录校验:token 缺少设备标识,拒绝 userId={} username={}", userId, username);
|
||||
throw new BusinessException(401, "登录态无效");
|
||||
}
|
||||
if (!bound.equals(claimed)) {
|
||||
log.warn("[auth] 单设备登录拦截:用户 {} 已被其他设备顶下线,token设备={} 当前绑定设备={}",
|
||||
userId, claimed, bound);
|
||||
throw new BusinessException(CODE_KICKED, "该账号已在其他设备登录,本设备已下线");
|
||||
}
|
||||
}
|
||||
|
||||
/** 登录绑定时的中文日志:首次绑定 / 换设备(顶下线)/ 同设备重登,便于线上排查互踢来源。 */
|
||||
public static void logBindOnLogin(String previousMachine, String deviceId, Long userId, String username) {
|
||||
String previous = previousMachine == null ? "" : previousMachine.trim();
|
||||
if (previous.isEmpty()) {
|
||||
log.info("[auth] 单设备登录:用户 {}({})首次绑定设备 {}", userId, username, deviceId);
|
||||
} else if (!previous.equals(deviceId)) {
|
||||
log.warn("[auth] 单设备登录:用户 {}({})在设备 {} 登录,原设备 {} 已被顶下线",
|
||||
userId, username, deviceId, previous);
|
||||
} else {
|
||||
log.info("[auth] 单设备登录:用户 {}({})同设备重新登录 device={}", userId, username, deviceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
import com.nanri.aiimage.common.security.AuthProperties;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class JwtService {
|
||||
|
||||
private static final String INSECURE_DEFAULT_SECRET = "please-change-this-secret-please-rotate-at-least-32-bytes";
|
||||
|
||||
private final AuthProperties props;
|
||||
|
||||
private volatile SecretKey cachedKey;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${spring.profiles.active:}")
|
||||
private String activeProfiles;
|
||||
|
||||
/**
|
||||
* 生产 profile 下密钥缺失即拒绝启动(2026-09 全维度审查)。
|
||||
*
|
||||
* <p>此前未配置时静默回退到内置默认密钥——那是公开值,任何人可据此伪造 token;
|
||||
* 一次 env 丢失就会让全站鉴权形同虚设,只留一行 warn 日志不足以拦住发布。
|
||||
* 本地/测试 profile 保持宽松(否则开发无法启动)。
|
||||
*/
|
||||
@jakarta.annotation.PostConstruct
|
||||
void requireSecretInServerProfile() {
|
||||
boolean serverProfile = activeProfiles != null && activeProfiles.contains("server");
|
||||
if (serverProfile && (props.getJwtSecret() == null || props.getJwtSecret().isBlank())) {
|
||||
throw new IllegalStateException(
|
||||
"server profile 下必须配置 aiimage.auth.jwt-secret(环境变量 AIIMAGE_JWT_SECRET)——"
|
||||
+ "缺失时会回退到公开的默认密钥,token 可被任意伪造");
|
||||
}
|
||||
}
|
||||
|
||||
private SecretKey signingKey() {
|
||||
SecretKey key = cachedKey;
|
||||
if (key == null) {
|
||||
synchronized (this) {
|
||||
key = cachedKey;
|
||||
if (key == null) {
|
||||
String configured = props.getJwtSecret();
|
||||
byte[] keyBytes;
|
||||
if (configured == null || configured.isBlank()) {
|
||||
// 兜底:未配置时使用内置默认密钥(公开值,等同无防护,任何人可伪造 token)。
|
||||
// 桌面客户端本地 Flask 已退役,服务端可独立轮换密钥;若恢复客户端侧验签,
|
||||
// 需与客户端同步下发密钥后才能轮换。
|
||||
keyBytes = INSECURE_DEFAULT_SECRET.getBytes(StandardCharsets.UTF_8);
|
||||
log.warn("[auth] AIIMAGE_JWT_SECRET 未配置,使用内置默认密钥;"
|
||||
+ "生产环境请在 application-server.yml 配置 aiimage.auth.jwt-secret");
|
||||
} else {
|
||||
keyBytes = configured.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
if (keyBytes.length < 32) {
|
||||
byte[] padded = new byte[32];
|
||||
System.arraycopy(keyBytes, 0, padded, 0, keyBytes.length);
|
||||
keyBytes = padded;
|
||||
}
|
||||
key = Keys.hmacShaKeyFor(keyBytes);
|
||||
cachedKey = key;
|
||||
}
|
||||
}
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
public String issue(Long userId, String username, String deviceId) {
|
||||
Instant now = Instant.now();
|
||||
Instant exp = now.plus(Duration.ofHours(props.getJwtTtlHours()));
|
||||
return Jwts.builder()
|
||||
.subject(String.valueOf(userId))
|
||||
.claim("username", username)
|
||||
.claim("deviceId", deviceId)
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(exp))
|
||||
.signWith(signingKey())
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parse(String token) {
|
||||
try {
|
||||
return Jwts.parser()
|
||||
.verifyWith(signingKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
} catch (JwtException | IllegalArgumentException e) {
|
||||
log.debug("[auth] jwt parse failed: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public long ttlSeconds() {
|
||||
return Duration.ofHours(props.getJwtTtlHours()).toSeconds();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user