feat(安全): 内部令牌支持过渡期新旧两把并行接受

换 AIIMAGE_INTERNAL_TOKEN 会让没升级的老客户端立刻全部失败(这把令牌有 4 个客户端字面量
点位并已分发到用户机器)。照仓内 shop-credential-key-previous 的惯例加 internal-token-previous:
逗号分隔的旧值与当前值并入同一接受集合,置空即关窗。

原先 8 处各自持有 @Value 字段并重复实现比较,其中 2 处用的是 equals 而非常量时间比较;
判断收进 AdminAuthSupport.isTrustedSuppliedToken 一处,controller 改为委派。
This commit is contained in:
2026-10-03 01:49:13 +08:00
parent 005cda9379
commit 4f03ea1808
13 changed files with 191 additions and 371 deletions
@@ -1,5 +1,7 @@
package com.nanri.aiimage.common.security;
import java.util.List;
import java.util.ArrayList;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.JwtService;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
@@ -35,6 +37,10 @@ public class AdminAuthSupport {
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
/** 轮换过渡期用:逗号分隔的旧令牌,新旧同时接受;旧客户端铺完(或确认无残留)后置空。 */
@Value("${aiimage.security.internal-token-previous:}")
private String internalTokenPrevious;
/** 解析当前请求的用户;token 缺失或无效抛 401。 */
public AdminUserEntity requireUser(HttpServletRequest request) {
String token = resolveToken(request);
@@ -170,15 +176,58 @@ public class AdminAuthSupport {
}
private boolean isTrustedInternalRequest(HttpServletRequest request) {
String suppliedToken = request.getHeader("X-Internal-Token");
String expectedToken = resolveExpectedInternalToken();
if (expectedToken.isBlank() || suppliedToken == null || suppliedToken.isBlank()) {
return isTrustedSuppliedToken(request.getHeader("X-Internal-Token"));
}
/**
* 只判断令牌本身:命中当前配置值(配置为空时退到令牌文件)、或过渡期旧值之一即可信。
* 一个期望值都没配时一律拒绝,免得属性漂成空串就把内部端点变成匿名可达。
* 各 controller 请复用这里,别再各自复制一份比较逻辑 —— 轮换时漏一处就是半条链路 401。
*/
public boolean isTrustedSuppliedToken(String suppliedToken) {
if (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));
byte[] supplied = suppliedToken.trim().getBytes(StandardCharsets.UTF_8);
for (String expected : acceptedInternalTokens()) {
// 常量时间比较:逐字节 equals 可被计时侧信道逐位试探出内部令牌
if (java.security.MessageDigest.isEqual(
expected.getBytes(StandardCharsets.UTF_8), supplied)) {
return true;
}
}
return false;
}
/** 当前值优先;当前值为空才用令牌文件;过渡期旧值(逗号分隔)始终并入,重复值剔除。 */
private List<String> acceptedInternalTokens() {
List<String> accepted = new ArrayList<>();
String configured = internalToken == null ? "" : internalToken.trim();
if (configured.isEmpty()) {
configured = readInternalTokenFile().trim();
}
if (!configured.isEmpty()) {
accepted.add(configured);
}
for (String previous : (internalTokenPrevious == null ? "" : internalTokenPrevious).split(",")) {
String old = previous.trim();
if (!old.isEmpty() && !old.equals(configured) && !accepted.contains(old)) {
accepted.add(old);
}
}
return accepted;
}
private String readInternalTokenFile() {
Path path = resolveInternalTokenFile();
if (path == null || !Files.isRegularFile(path)) {
return "";
}
try {
return Files.readString(path, StandardCharsets.UTF_8).trim();
} catch (Exception ignored) {
return "";
}
}
/**
@@ -191,20 +240,6 @@ public class AdminAuthSupport {
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();
@@ -66,11 +66,7 @@ public class DedupeTotalDataController {
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
@GetMapping
@Operation(summary = "分页查询总数据", description = "分页查询数据去重总数据,支持按值模糊搜索。")
@@ -268,50 +264,12 @@ public class DedupeTotalDataController {
}
}
private boolean isTrustedInternalRequest(String suppliedToken) {
String expectedToken = resolveExpectedInternalToken();
return !expectedToken.isBlank() && suppliedToken != null && !suppliedToken.isBlank()
&& MessageDigest.isEqual(
expectedToken.getBytes(StandardCharsets.UTF_8),
suppliedToken.trim().getBytes(StandardCharsets.UTF_8));
}
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 record RequestOperator(Long id, boolean superAdmin) {
}
private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
}
}
@@ -44,11 +44,7 @@ public class InvalidAsinDataController {
private static final String INVALID_ASIN_DATA_COLUMN_KEY = "admin_invalid_asin_data";
private static final String INVALID_ASIN_DATA_ROUTE_PATH = "invalid-asin-data";
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
private final InvalidAsinDataService invalidAsinDataService;
private final AdminAuthSupport adminAuthSupport;
@@ -165,50 +161,12 @@ public class InvalidAsinDataController {
}
}
private boolean isTrustedInternalRequest(String suppliedToken) {
String expectedToken = resolveExpectedInternalToken();
return !expectedToken.isBlank() && suppliedToken != null && !suppliedToken.isBlank()
&& MessageDigest.isEqual(
expectedToken.getBytes(StandardCharsets.UTF_8),
suppliedToken.trim().getBytes(StandardCharsets.UTF_8));
}
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 record RequestOperator(Long id, boolean superAdmin) {
}
private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
}
}
@@ -43,11 +43,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
@Tag(name = "菜单权限管理", description = "统一维护软件端与后台管理端的菜单权限配置")
public class PermissionMenuController {
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@@ -229,47 +225,9 @@ public class PermissionMenuController {
}
}
private boolean isTrustedInternalRequest(HttpServletRequest request, String suppliedToken) {
String expectedToken = resolveExpectedInternalToken();
if (expectedToken.isBlank() || suppliedToken == null || suppliedToken.isBlank()) {
return false;
}
return expectedToken.equals(suppliedToken);
}
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();
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
}
}
@@ -40,11 +40,7 @@ public class AdminShopDataCrawlTaskController {
/** 代理下载 OSS 文件转发给浏览器的超时:必须有上限,避免上游挂起占死 Tomcat 工作线程。 */
private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(5);
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
private final ShopDataCrawlTaskService taskService;
private final AdminAuthSupport adminAuthSupport;
@@ -112,47 +108,9 @@ public class AdminShopDataCrawlTaskController {
}
}
private boolean isTrustedInternalRequest(String suppliedToken) {
String expectedToken = resolveExpectedInternalToken();
return !expectedToken.isBlank() && suppliedToken != null && !suppliedToken.isBlank()
&& MessageDigest.isEqual(
expectedToken.getBytes(StandardCharsets.UTF_8),
suppliedToken.trim().getBytes(StandardCharsets.UTF_8));
}
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();
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
}
}
@@ -71,11 +71,7 @@ public class AdminShopDataCrawlTasksController {
/** 代理下载 OSS 文件转发给浏览器的超时:必须有上限,避免上游挂起占死 Tomcat 工作线程。 */
private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(5);
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@@ -310,49 +306,8 @@ public class AdminShopDataCrawlTasksController {
}
}
private boolean isTrustedInternalRequest(String suppliedToken) {
String expectedToken = resolveExpectedInternalToken();
return !expectedToken.isBlank() && suppliedToken != null && !suppliedToken.isBlank()
&& MessageDigest.isEqual(
expectedToken.getBytes(StandardCharsets.UTF_8),
suppliedToken.trim().getBytes(StandardCharsets.UTF_8));
}
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 static int parseInt(String raw, int defaultValue, String errorMessage) {
if (raw == null || raw.isBlank()) {
@@ -364,4 +319,7 @@ public class AdminShopDataCrawlTasksController {
throw new BusinessException(400, errorMessage);
}
}
private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
}
}
@@ -44,11 +44,7 @@ import java.util.Set;
@Tag(name = "店铺数据重复检查")
public class AdminShopDataDuplicateCheckController {
@Value("${aiimage.security.internal-token:}")
private String internalToken;
@Value("${aiimage.security.internal-token-file:}")
private String internalTokenFile;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@@ -282,49 +278,8 @@ public class AdminShopDataDuplicateCheckController {
}
}
private boolean isTrustedInternalRequest(String suppliedToken) {
String expectedToken = resolveExpectedInternalToken();
return !expectedToken.isBlank() && suppliedToken != null && !suppliedToken.isBlank()
&& MessageDigest.isEqual(
expectedToken.getBytes(StandardCharsets.UTF_8),
suppliedToken.trim().getBytes(StandardCharsets.UTF_8));
}
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 static int parsePage(String page) {
if (page == null || page.isBlank()) {
@@ -351,4 +306,7 @@ public class AdminShopDataDuplicateCheckController {
private static int clamp(int value, int min, int max) {
return Math.max(min, Math.min(max, value));
}
private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
}
}
@@ -156,7 +156,7 @@ public class ShopManageController {
public ApiResponse<ShopManageCredentialVo> getCredentialByShopName(
@RequestParam("shopName") String shopName,
@RequestHeader(value = "X-Internal-Token", required = false) String token) {
if (internalToken == null || internalToken.isBlank() || token == null || !internalToken.equals(token)) {
if (!adminAuthSupport.isTrustedSuppliedToken(token)) {
throw new com.nanri.aiimage.common.exception.BusinessException("无权访问凭据");
}
return ApiResponse.success(shopManageService.getCredentialByShopName(shopName));
@@ -173,6 +173,4 @@ public class ShopManageController {
return ApiResponse.success(shopManageService.getCredentialById(id));
}
@Value("${aiimage.security.internal-token:}")
private String internalToken;
}
@@ -468,6 +468,8 @@ aiimage:
# 轮换过渡期用:逗号分隔的旧密钥,解密按顺序回试,加密只用上面那个;迁完就清空
shop-credential-key-previous: ${AIIMAGE_SHOP_CREDENTIAL_KEY_PREVIOUS:}
internal-token: ${AIIMAGE_INTERNAL_TOKEN:}
# 轮换过渡期用:逗号分隔的旧令牌,新旧同时接受;旧客户端铺完(或确认无残留)后置空
internal-token-previous: ${AIIMAGE_INTERNAL_TOKEN_PREVIOUS:}
internal-token-file: ${AIIMAGE_INTERNAL_TOKEN_FILE:}
auth:
jwt-secret: ${AIIMAGE_JWT_SECRET:please-change-this-secret-please-rotate-at-least-32-bytes}