feat(安全): 内部令牌支持过渡期新旧两把并行接受
换 AIIMAGE_INTERNAL_TOKEN 会让没升级的老客户端立刻全部失败(这把令牌有 4 个客户端字面量 点位并已分发到用户机器)。照仓内 shop-credential-key-previous 的惯例加 internal-token-previous: 逗号分隔的旧值与当前值并入同一接受集合,置空即关窗。 原先 8 处各自持有 @Value 字段并重复实现比较,其中 2 处用的是 equals 而非常量时间比较; 判断收进 AdminAuthSupport.isTrustedSuppliedToken 一处,controller 改为委派。
This commit is contained in:
+56
-21
@@ -1,5 +1,7 @@
|
|||||||
package com.nanri.aiimage.common.security;
|
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.exception.BusinessException;
|
||||||
import com.nanri.aiimage.common.security.JwtService;
|
import com.nanri.aiimage.common.security.JwtService;
|
||||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||||
@@ -35,6 +37,10 @@ public class AdminAuthSupport {
|
|||||||
@Value("${aiimage.security.internal-token-file:}")
|
@Value("${aiimage.security.internal-token-file:}")
|
||||||
private String internalTokenFile;
|
private String internalTokenFile;
|
||||||
|
|
||||||
|
/** 轮换过渡期用:逗号分隔的旧令牌,新旧同时接受;旧客户端铺完(或确认无残留)后置空。 */
|
||||||
|
@Value("${aiimage.security.internal-token-previous:}")
|
||||||
|
private String internalTokenPrevious;
|
||||||
|
|
||||||
/** 解析当前请求的用户;token 缺失或无效抛 401。 */
|
/** 解析当前请求的用户;token 缺失或无效抛 401。 */
|
||||||
public AdminUserEntity requireUser(HttpServletRequest request) {
|
public AdminUserEntity requireUser(HttpServletRequest request) {
|
||||||
String token = resolveToken(request);
|
String token = resolveToken(request);
|
||||||
@@ -170,15 +176,58 @@ public class AdminAuthSupport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private boolean isTrustedInternalRequest(HttpServletRequest request) {
|
private boolean isTrustedInternalRequest(HttpServletRequest request) {
|
||||||
String suppliedToken = request.getHeader("X-Internal-Token");
|
return isTrustedSuppliedToken(request.getHeader("X-Internal-Token"));
|
||||||
String expectedToken = resolveExpectedInternalToken();
|
}
|
||||||
if (expectedToken.isBlank() || suppliedToken == null || suppliedToken.isBlank()) {
|
|
||||||
|
/**
|
||||||
|
* 只判断令牌本身:命中当前配置值(配置为空时退到令牌文件)、或过渡期旧值之一即可信。
|
||||||
|
* 一个期望值都没配时一律拒绝,免得属性漂成空串就把内部端点变成匿名可达。
|
||||||
|
* 各 controller 请复用这里,别再各自复制一份比较逻辑 —— 轮换时漏一处就是半条链路 401。
|
||||||
|
*/
|
||||||
|
public boolean isTrustedSuppliedToken(String suppliedToken) {
|
||||||
|
if (suppliedToken == null || suppliedToken.isBlank()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// 常量时间比较:逐字节 equals 可被计时侧信道逐位试探出内部令牌
|
byte[] supplied = suppliedToken.trim().getBytes(StandardCharsets.UTF_8);
|
||||||
return java.security.MessageDigest.isEqual(
|
for (String expected : acceptedInternalTokens()) {
|
||||||
expectedToken.getBytes(java.nio.charset.StandardCharsets.UTF_8),
|
// 常量时间比较:逐字节 equals 可被计时侧信道逐位试探出内部令牌
|
||||||
suppliedToken.trim().getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
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);
|
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() {
|
private Path resolveInternalTokenFile() {
|
||||||
String configuredPath = internalTokenFile == null ? "" : internalTokenFile.trim();
|
String configuredPath = internalTokenFile == null ? "" : internalTokenFile.trim();
|
||||||
|
|||||||
+3
-45
@@ -66,11 +66,7 @@ public class DedupeTotalDataController {
|
|||||||
private final AdminAuthSupport adminAuthSupport;
|
private final AdminAuthSupport adminAuthSupport;
|
||||||
private final PermissionMenuService permissionMenuService;
|
private final PermissionMenuService permissionMenuService;
|
||||||
|
|
||||||
@Value("${aiimage.security.internal-token:}")
|
|
||||||
private String internalToken;
|
|
||||||
|
|
||||||
@Value("${aiimage.security.internal-token-file:}")
|
|
||||||
private String internalTokenFile;
|
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
@Operation(summary = "分页查询总数据", description = "分页查询数据去重总数据,支持按值模糊搜索。")
|
@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 record RequestOperator(Long id, boolean superAdmin) {
|
||||||
}
|
}
|
||||||
|
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||||
|
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-45
@@ -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_COLUMN_KEY = "admin_invalid_asin_data";
|
||||||
private static final String INVALID_ASIN_DATA_ROUTE_PATH = "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 InvalidAsinDataService invalidAsinDataService;
|
||||||
private final AdminAuthSupport adminAuthSupport;
|
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 record RequestOperator(Long id, boolean superAdmin) {
|
||||||
}
|
}
|
||||||
|
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||||
|
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-45
@@ -43,11 +43,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
|
|||||||
@Tag(name = "菜单权限管理", description = "统一维护软件端与后台管理端的菜单权限配置")
|
@Tag(name = "菜单权限管理", description = "统一维护软件端与后台管理端的菜单权限配置")
|
||||||
public class PermissionMenuController {
|
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 AdminAuthSupport adminAuthSupport;
|
||||||
private final PermissionMenuService permissionMenuService;
|
private final PermissionMenuService permissionMenuService;
|
||||||
@@ -229,47 +225,9 @@ public class PermissionMenuController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private boolean isTrustedInternalRequest(HttpServletRequest request, String suppliedToken) {
|
private boolean isTrustedInternalRequest(HttpServletRequest request, String suppliedToken) {
|
||||||
String expectedToken = resolveExpectedInternalToken();
|
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-45
@@ -40,11 +40,7 @@ public class AdminShopDataCrawlTaskController {
|
|||||||
/** 代理下载 OSS 文件转发给浏览器的超时:必须有上限,避免上游挂起占死 Tomcat 工作线程。 */
|
/** 代理下载 OSS 文件转发给浏览器的超时:必须有上限,避免上游挂起占死 Tomcat 工作线程。 */
|
||||||
private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(5);
|
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 ShopDataCrawlTaskService taskService;
|
||||||
private final AdminAuthSupport adminAuthSupport;
|
private final AdminAuthSupport adminAuthSupport;
|
||||||
@@ -112,47 +108,9 @@ public class AdminShopDataCrawlTaskController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private boolean isTrustedInternalRequest(String suppliedToken) {
|
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||||
String expectedToken = resolveExpectedInternalToken();
|
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-45
@@ -71,11 +71,7 @@ public class AdminShopDataCrawlTasksController {
|
|||||||
/** 代理下载 OSS 文件转发给浏览器的超时:必须有上限,避免上游挂起占死 Tomcat 工作线程。 */
|
/** 代理下载 OSS 文件转发给浏览器的超时:必须有上限,避免上游挂起占死 Tomcat 工作线程。 */
|
||||||
private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(5);
|
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 AdminAuthSupport adminAuthSupport;
|
||||||
private final PermissionMenuService permissionMenuService;
|
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) {
|
private static int parseInt(String raw, int defaultValue, String errorMessage) {
|
||||||
if (raw == null || raw.isBlank()) {
|
if (raw == null || raw.isBlank()) {
|
||||||
@@ -364,4 +319,7 @@ public class AdminShopDataCrawlTasksController {
|
|||||||
throw new BusinessException(400, errorMessage);
|
throw new BusinessException(400, errorMessage);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||||
|
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-45
@@ -44,11 +44,7 @@ import java.util.Set;
|
|||||||
@Tag(name = "店铺数据重复检查")
|
@Tag(name = "店铺数据重复检查")
|
||||||
public class AdminShopDataDuplicateCheckController {
|
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 AdminAuthSupport adminAuthSupport;
|
||||||
private final PermissionMenuService permissionMenuService;
|
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) {
|
private static int parsePage(String page) {
|
||||||
if (page == null || page.isBlank()) {
|
if (page == null || page.isBlank()) {
|
||||||
@@ -351,4 +306,7 @@ public class AdminShopDataDuplicateCheckController {
|
|||||||
private static int clamp(int value, int min, int max) {
|
private static int clamp(int value, int min, int max) {
|
||||||
return Math.max(min, Math.min(max, value));
|
return Math.max(min, Math.min(max, value));
|
||||||
}
|
}
|
||||||
|
private boolean isTrustedInternalRequest(String suppliedToken) {
|
||||||
|
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -156,7 +156,7 @@ public class ShopManageController {
|
|||||||
public ApiResponse<ShopManageCredentialVo> getCredentialByShopName(
|
public ApiResponse<ShopManageCredentialVo> getCredentialByShopName(
|
||||||
@RequestParam("shopName") String shopName,
|
@RequestParam("shopName") String shopName,
|
||||||
@RequestHeader(value = "X-Internal-Token", required = false) String token) {
|
@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("无权访问凭据");
|
throw new com.nanri.aiimage.common.exception.BusinessException("无权访问凭据");
|
||||||
}
|
}
|
||||||
return ApiResponse.success(shopManageService.getCredentialByShopName(shopName));
|
return ApiResponse.success(shopManageService.getCredentialByShopName(shopName));
|
||||||
@@ -173,6 +173,4 @@ public class ShopManageController {
|
|||||||
return ApiResponse.success(shopManageService.getCredentialById(id));
|
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:}
|
shop-credential-key-previous: ${AIIMAGE_SHOP_CREDENTIAL_KEY_PREVIOUS:}
|
||||||
internal-token: ${AIIMAGE_INTERNAL_TOKEN:}
|
internal-token: ${AIIMAGE_INTERNAL_TOKEN:}
|
||||||
|
# 轮换过渡期用:逗号分隔的旧令牌,新旧同时接受;旧客户端铺完(或确认无残留)后置空
|
||||||
|
internal-token-previous: ${AIIMAGE_INTERNAL_TOKEN_PREVIOUS:}
|
||||||
internal-token-file: ${AIIMAGE_INTERNAL_TOKEN_FILE:}
|
internal-token-file: ${AIIMAGE_INTERNAL_TOKEN_FILE:}
|
||||||
auth:
|
auth:
|
||||||
jwt-secret: ${AIIMAGE_JWT_SECRET:please-change-this-secret-please-rotate-at-least-32-bytes}
|
jwt-secret: ${AIIMAGE_JWT_SECRET:please-change-this-secret-please-rotate-at-least-32-bytes}
|
||||||
|
|||||||
+105
@@ -8,6 +8,10 @@ import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
|||||||
import io.jsonwebtoken.Claims;
|
import io.jsonwebtoken.Claims;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
@@ -90,6 +94,107 @@ class AdminAuthSupportTest {
|
|||||||
assertThatCode(() -> support.requireUser(requestWithBearer("t"))).doesNotThrowAnyException();
|
assertThatCode(() -> support.requireUser(requestWithBearer("t"))).doesNotThrowAnyException();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- 内部令牌:轮换过渡期新旧两把同时接受 ----------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenAcceptsConfiguredValueOnly(@TempDir Path tempDir) {
|
||||||
|
AdminAuthSupport support = tokenSupport("new-token", "", tempDir.resolve("unused").toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("new-token")).isTrue();
|
||||||
|
assertThat(support.isTrustedSuppliedToken("old-token")).isFalse();
|
||||||
|
assertThat(support.isTrustedSuppliedToken("")).isFalse();
|
||||||
|
assertThat(support.isTrustedSuppliedToken(null)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenAcceptsPreviousValueDuringRotationWindow(@TempDir Path tempDir) {
|
||||||
|
AdminAuthSupport support = tokenSupport("new-token", "old-token", tempDir.resolve("unused").toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("new-token")).isTrue();
|
||||||
|
assertThat(support.isTrustedSuppliedToken("old-token")).isTrue();
|
||||||
|
assertThat(support.isTrustedSuppliedToken("stale-token")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenRejectsPreviousValueOnceWindowIsClosed(@TempDir Path tempDir) {
|
||||||
|
AdminAuthSupport support = tokenSupport("new-token", "", tempDir.resolve("unused").toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("old-token")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenIgnoresBlankEntriesInPreviousList(@TempDir Path tempDir) {
|
||||||
|
AdminAuthSupport support = tokenSupport("new-token", " , old-a ,,old-b, "
|
||||||
|
, tempDir.resolve("unused").toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("old-a")).isTrue();
|
||||||
|
assertThat(support.isTrustedSuppliedToken("old-b")).isTrue();
|
||||||
|
assertThat(support.isTrustedSuppliedToken(" , ")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenWithNothingConfiguredRejectsEverySuppliedValue(@TempDir Path tempDir) {
|
||||||
|
// 属性漂成空串时不能"空对空"放行,否则内部端点变成匿名可达
|
||||||
|
AdminAuthSupport support = tokenSupport("", "", tempDir.resolve("unused").toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("anything")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenFallsBackToTokenFileWhenPropertyIsBlank(@TempDir Path tempDir) throws Exception {
|
||||||
|
Path tokenFile = tempDir.resolve("internal-token");
|
||||||
|
Files.writeString(tokenFile, "file-token\n");
|
||||||
|
AdminAuthSupport support = tokenSupport("", "", tokenFile.toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("file-token")).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenPropertyTakesPrecedenceOverTokenFile(@TempDir Path tempDir) throws Exception {
|
||||||
|
// 属性有值就不读文件:否则轮换后残留的旧文件会把旧令牌一直续命
|
||||||
|
Path tokenFile = tempDir.resolve("internal-token");
|
||||||
|
Files.writeString(tokenFile, "file-token\n");
|
||||||
|
AdminAuthSupport support = tokenSupport("configured-token", "", tokenFile.toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("configured-token")).isTrue();
|
||||||
|
assertThat(support.isTrustedSuppliedToken("file-token")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenRejectsWhenTokenFileIsMissing(@TempDir Path tempDir) {
|
||||||
|
AdminAuthSupport support = tokenSupport("", "", tempDir.resolve("missing-token").toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("guessed-token")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void internalTokenKeepsFileValueAndPreviousListBothAcceptedDuringWindow(@TempDir Path tempDir) throws Exception {
|
||||||
|
Path tokenFile = tempDir.resolve("internal-token");
|
||||||
|
Files.writeString(tokenFile, "file-token\n");
|
||||||
|
AdminAuthSupport support = tokenSupport("", "old-token", tokenFile.toString());
|
||||||
|
|
||||||
|
assertThat(support.isTrustedSuppliedToken("file-token")).isTrue();
|
||||||
|
assertThat(support.isTrustedSuppliedToken("old-token")).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isTrustedInternalTokenReadsTheInternalHeader() {
|
||||||
|
AdminAuthSupport support = tokenSupport("new-token", "old-token", "");
|
||||||
|
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||||
|
when(request.getHeader("X-Internal-Token")).thenReturn("old-token");
|
||||||
|
|
||||||
|
assertThat(support.isTrustedInternalToken(request)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminAuthSupport tokenSupport(String current, String previous, String tokenFile) {
|
||||||
|
AdminAuthSupport support = new AdminAuthSupport(
|
||||||
|
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class));
|
||||||
|
ReflectionTestUtils.setField(support, "internalToken", current);
|
||||||
|
ReflectionTestUtils.setField(support, "internalTokenPrevious", previous);
|
||||||
|
ReflectionTestUtils.setField(support, "internalTokenFile", tokenFile);
|
||||||
|
return support;
|
||||||
|
}
|
||||||
|
|
||||||
private AdminAuthSupport support(AdminUserEntity user, String claimDeviceId, boolean singleDeviceEnabled) {
|
private AdminAuthSupport support(AdminUserEntity user, String claimDeviceId, boolean singleDeviceEnabled) {
|
||||||
JwtService jwtService = mock(JwtService.class);
|
JwtService jwtService = mock(JwtService.class);
|
||||||
AdminUserMapper userMapper = mock(AdminUserMapper.class);
|
AdminUserMapper userMapper = mock(AdminUserMapper.class);
|
||||||
|
|||||||
+5
-2
@@ -14,7 +14,6 @@ import org.mockito.InjectMocks;
|
|||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import org.springframework.mock.web.MockHttpServletRequest;
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
import org.springframework.test.util.ReflectionTestUtils;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -24,6 +23,8 @@ import static org.mockito.ArgumentMatchers.eq;
|
|||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.lenient;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
@@ -40,7 +41,9 @@ class InvalidAsinDataControllerTest {
|
|||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "test-internal-token");
|
// 令牌比较已经收进 AdminAuthSupport:这里按真实语义打桩(只对正确的值返回 true)
|
||||||
|
lenient().when(adminAuthSupport.isTrustedSuppliedToken(any()))
|
||||||
|
.thenAnswer(call -> "test-internal-token".equals(call.getArgument(0)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+3
-73
@@ -11,7 +11,6 @@ import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
|||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
import org.springframework.test.util.ReflectionTestUtils;
|
|
||||||
|
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
@@ -59,7 +58,7 @@ class PermissionMenuControllerTest {
|
|||||||
PermissionMenuService service = mock(PermissionMenuService.class);
|
PermissionMenuService service = mock(PermissionMenuService.class);
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||||
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "shared-token");
|
when(authSupport.isTrustedSuppliedToken("shared-token")).thenReturn(true);
|
||||||
AdminUserEntity currentUser = new AdminUserEntity();
|
AdminUserEntity currentUser = new AdminUserEntity();
|
||||||
currentUser.setId(9L);
|
currentUser.setId(9L);
|
||||||
currentUser.setRole("normal");
|
currentUser.setRole("normal");
|
||||||
@@ -117,7 +116,7 @@ class PermissionMenuControllerTest {
|
|||||||
PermissionMenuService service = mock(PermissionMenuService.class);
|
PermissionMenuService service = mock(PermissionMenuService.class);
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||||
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "shared-token");
|
when(authSupport.isTrustedSuppliedToken("shared-token")).thenReturn(true);
|
||||||
AdminUserEntity operator = new AdminUserEntity();
|
AdminUserEntity operator = new AdminUserEntity();
|
||||||
operator.setId(12L);
|
operator.setId(12L);
|
||||||
operator.setRole("admin");
|
operator.setRole("admin");
|
||||||
@@ -141,7 +140,7 @@ class PermissionMenuControllerTest {
|
|||||||
PermissionMenuService service = mock(PermissionMenuService.class);
|
PermissionMenuService service = mock(PermissionMenuService.class);
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||||
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "shared-token");
|
// mock 的 isTrustedSuppliedToken 对任何值都返回 false,正是"令牌不匹配"要演的场景
|
||||||
BusinessException authFailure = new BusinessException(401, "未登录");
|
BusinessException authFailure = new BusinessException(401, "未登录");
|
||||||
|
|
||||||
when(authSupport.requireAdmin(request)).thenThrow(authFailure);
|
when(authSupport.requireAdmin(request)).thenThrow(authFailure);
|
||||||
@@ -153,75 +152,6 @@ class PermissionMenuControllerTest {
|
|||||||
verify(service, never()).list(any(AdminUserEntity.class), eq("app"), eq(false));
|
verify(service, never()).list(any(AdminUserEntity.class), eq("app"), eq(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void internalProxyUsesSharedTokenFileWhenEnvironmentTokenIsUnconfigured(@TempDir Path tempDir) throws Exception {
|
|
||||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
|
||||||
PermissionMenuService service = mock(PermissionMenuService.class);
|
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
|
||||||
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "");
|
|
||||||
Path tokenFile = tempDir.resolve("internal-token");
|
|
||||||
Files.writeString(tokenFile, "file-token\n");
|
|
||||||
ReflectionTestUtils.setField(controller, "internalTokenFile", tokenFile.toString());
|
|
||||||
AdminUserEntity operator = new AdminUserEntity();
|
|
||||||
operator.setId(12L);
|
|
||||||
operator.setRole("admin");
|
|
||||||
|
|
||||||
when(authSupport.requireAdmin(request)).thenThrow(new BusinessException(401, "未登录"));
|
|
||||||
when(request.getHeader("X-Internal-Token")).thenReturn("file-token");
|
|
||||||
when(request.getParameter("operatorId")).thenReturn("12");
|
|
||||||
when(service.requireAdminOperator(12L)).thenReturn(operator);
|
|
||||||
when(service.list(operator, "admin", false)).thenReturn(List.of());
|
|
||||||
|
|
||||||
controller.listMenus(request, "admin", false);
|
|
||||||
|
|
||||||
verify(service).requireAdminOperator(12L);
|
|
||||||
verify(service).list(operator, "admin", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void internalProxyRejectsMissingSharedTokenFileWhenEnvironmentTokenIsUnconfigured(@TempDir Path tempDir) {
|
|
||||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
|
||||||
PermissionMenuService service = mock(PermissionMenuService.class);
|
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
|
||||||
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "");
|
|
||||||
ReflectionTestUtils.setField(controller, "internalTokenFile", tempDir.resolve("missing-token").toString());
|
|
||||||
BusinessException authFailure = new BusinessException(401, "未登录");
|
|
||||||
|
|
||||||
when(authSupport.requireAdmin(request)).thenThrow(authFailure);
|
|
||||||
when(request.getHeader("X-Internal-Token")).thenReturn("guessed-token");
|
|
||||||
when(request.getRemoteAddr()).thenReturn("127.0.0.1");
|
|
||||||
when(request.getParameter("operatorId")).thenReturn("12");
|
|
||||||
|
|
||||||
assertThatThrownBy(() -> controller.listMenus(request, "admin", false))
|
|
||||||
.isSameAs(authFailure);
|
|
||||||
verify(service, never()).requireAdminOperator(anyLong());
|
|
||||||
verify(service, never()).list("admin");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void configuredInternalTokenTakesPrecedenceOverTokenFile(@TempDir Path tempDir) throws Exception {
|
|
||||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
|
||||||
PermissionMenuService service = mock(PermissionMenuService.class);
|
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
|
||||||
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
|
|
||||||
Path tokenFile = tempDir.resolve("internal-token");
|
|
||||||
Files.writeString(tokenFile, "file-token\n");
|
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "configured-token");
|
|
||||||
ReflectionTestUtils.setField(controller, "internalTokenFile", tokenFile.toString());
|
|
||||||
BusinessException authFailure = new BusinessException(401, "未登录");
|
|
||||||
|
|
||||||
when(authSupport.requireAdmin(request)).thenThrow(authFailure);
|
|
||||||
when(request.getHeader("X-Internal-Token")).thenReturn("file-token");
|
|
||||||
when(request.getParameter("operatorId")).thenReturn("12");
|
|
||||||
|
|
||||||
assertThatThrownBy(() -> controller.listMenus(request, "admin", false))
|
|
||||||
.isSameAs(authFailure);
|
|
||||||
verify(service, never()).requireAdminOperator(anyLong());
|
|
||||||
verify(service, never()).list("admin");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void imageVideoPermissionEndpointsDelegateAuthenticatedOperator() {
|
void imageVideoPermissionEndpointsDelegateAuthenticatedOperator() {
|
||||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||||
|
|||||||
+1
-2
@@ -7,7 +7,6 @@ import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
|||||||
import com.nanri.aiimage.modules.shopdatacrawl.service.ShopDataCrawlTaskService;
|
import com.nanri.aiimage.modules.shopdatacrawl.service.ShopDataCrawlTaskService;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.test.util.ReflectionTestUtils;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
@@ -42,7 +41,7 @@ class AdminShopDataCrawlTaskControllerTest {
|
|||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||||
AdminShopDataCrawlTaskController controller = new AdminShopDataCrawlTaskController(
|
AdminShopDataCrawlTaskController controller = new AdminShopDataCrawlTaskController(
|
||||||
taskService, authSupport, permissionService);
|
taskService, authSupport, permissionService);
|
||||||
ReflectionTestUtils.setField(controller, "internalToken", "shared-token");
|
when(authSupport.isTrustedSuppliedToken("shared-token")).thenReturn(true);
|
||||||
AdminUserEntity operator = admin(8L);
|
AdminUserEntity operator = admin(8L);
|
||||||
when(authSupport.requireAdmin(request)).thenThrow(new BusinessException(401, "not logged in"));
|
when(authSupport.requireAdmin(request)).thenThrow(new BusinessException(401, "not logged in"));
|
||||||
when(request.getHeader("X-Internal-Token")).thenReturn("shared-token");
|
when(request.getHeader("X-Internal-Token")).thenReturn("shared-token");
|
||||||
|
|||||||
Reference in New Issue
Block a user