From fd9aa2caa516d6d19afe7c9f622f0f5778f0f9b3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com>
Date: Sat, 3 Oct 2026 03:22:40 +0800
Subject: [PATCH] =?UTF-8?q?test(=E5=AE=89=E5=85=A8):=20=E5=86=85=E9=83=A8?=
=?UTF-8?q?=E4=BB=A4=E7=89=8C=E5=88=A4=E6=8D=AE=E6=94=B6=E5=8F=A3=E4=B8=BA?=
=?UTF-8?q?=E5=8D=95=E7=82=B9=EF=BC=8C=E8=A1=A5=E7=BB=93=E6=9E=84=E6=8A=A4?=
=?UTF-8?q?=E6=A0=8F=E7=94=A8=E4=BE=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 新增 InternalTokenSingleOutletTest:5 例,检查全仓唯一比较点仍是
AdminAuthSupport、读头位置全部委派、过渡期属性与 yml 键仍存在
- 自带防恒绿自检(读取点少于 6 处即判扫描失效)
---
.../InternalTokenSingleOutletTest.java | 155 ++++++++++++++++++
1 file changed, 155 insertions(+)
create mode 100644 backend-java/src/test/java/com/nanri/aiimage/common/security/InternalTokenSingleOutletTest.java
diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/security/InternalTokenSingleOutletTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/security/InternalTokenSingleOutletTest.java
new file mode 100644
index 000000000..690ccd1dd
--- /dev/null
+++ b/backend-java/src/test/java/com/nanri/aiimage/common/security/InternalTokenSingleOutletTest.java
@@ -0,0 +1,155 @@
+package com.nanri.aiimage.common.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+
+/**
+ * 内部令牌(X-Internal-Token)的判据只允许存在于 {@link AdminAuthSupport} 一处。
+ *
+ *
轮换密钥要靠一个属性({@code aiimage.security.internal-token-previous})让新旧两把同时生效,
+ * 而历史上这个判断在 8 个类里各抄了一份、其中两份还是 {@code equals} 而非常量时间比较。
+ * 谁再抄一份,轮换时就会漏掉那半条链路(漏的那处继续只认旧值或只认新值),所以把"只许一处"做成用例。
+ */
+class InternalTokenSingleOutletTest {
+
+ private static final String OUTLET_CLASS = "AdminAuthSupport.java";
+ private static final String HEADER_LITERAL = "\"X-Internal-Token\"";
+
+ @Test
+ void everyHeaderReadSiteDelegatesToAdminAuthSupport() throws IOException {
+ List offenders = mainSources().stream()
+ .filter(file -> !file.getFileName().toString().equals(OUTLET_CLASS))
+ .filter(file -> readsHeader(read(file)))
+ .filter(file -> !delegatesToSupport(read(file)))
+ .collect(Collectors.toList());
+
+ assertThat(offenders)
+ .as("读 X-Internal-Token 却不委派给 AdminAuthSupport 的文件(请改成 adminAuthSupport.isTrusted…,"
+ + "否则轮换时这一处不会跟随 internal-token-previous)")
+ .isEmpty();
+ }
+
+ @Test
+ void onlyAdminAuthSupportComparesTokenValues() throws IOException {
+ List offenders = mainSources().stream()
+ .filter(file -> !file.getFileName().toString().equals(OUTLET_CLASS))
+ .filter(file -> redeclaresTokenConfig(read(file)))
+ .collect(Collectors.toList());
+
+ assertThat(offenders)
+ .as("在 AdminAuthSupport 之外重新声明内部令牌属性/env 的文件 —— 每多一处,"
+ + "轮换时就要多点一个开关,漏掉的那处会静默只认一把")
+ .isEmpty();
+ }
+
+ @Test
+ void supportItselfHoldsTheTransitionalProperty() throws IOException {
+ String text = read(sourceOf(OUTLET_CLASS));
+ assertThat(text).contains("MessageDigest.isEqual");
+ assertThat(text).contains("${aiimage.security.internal-token-previous:}");
+ assertThat(text).contains("${aiimage.security.internal-token:}");
+ }
+
+ /** 取样集非空自检:扫描一旦 0 命中,上面几条就会恒绿,等于没护栏。 */
+ @Test
+ void headerReadSitesAreActuallyBeingScanned() throws IOException {
+ List readSites = mainSources().stream()
+ .filter(p -> readsHeader(read(p)))
+ .map(p -> p.getFileName().toString())
+ .collect(Collectors.toList());
+
+ assertThat(readSites)
+ .as("应当扫到 AdminAuthSupport 与若干个委派它的 controller")
+ .hasSizeGreaterThanOrEqualTo(6)
+ .contains(OUTLET_CLASS);
+ }
+
+ @Test
+ void applicationYmlDeclaresTheTransitionalKey() throws IOException {
+ Path yml = moduleRoot().resolve("src/main/resources/application.yml");
+ assertThat(yml).exists();
+ assertThat(read(yml)).contains("internal-token-previous: ${AIIMAGE_INTERNAL_TOKEN_PREVIOUS:}");
+ }
+
+ /** 头部读取点必须把判断交给 AdminAuthSupport;私有同名 helper 里再转委派也算。 */
+ private static boolean delegatesToSupport(String text) {
+ return text.contains("adminAuthSupport.isTrustedInternalToken(")
+ || text.contains("adminAuthSupport.isTrustedSuppliedToken(");
+ }
+
+ /**
+ * 真读取点才算,光出现在名单里不算:{@code SecurityConfig} 的 CORS allowedHeaders
+ * 也含这个字面量,按"提到即违规"判会假红,规则一旦假红就没人再信它。
+ */
+ private static boolean readsHeader(String text) {
+ return text.contains("getHeader(" + HEADER_LITERAL + ")")
+ || (text.contains("@RequestHeader") && text.contains(HEADER_LITERAL));
+ }
+
+ /**
+ * 令牌期望值只允许在 AdminAuthSupport 一处声明(属性或 env 各算一种声明方式)。
+ * 只看声明/可执行行:注释里引用令牌来源(如 {@code InternalBrandTaskController} 的鉴权说明)
+ * 不算重新声明 —— 判据一旦误红,下一次就没人信它也不会再修它。
+ */
+ private static boolean redeclaresTokenConfig(String text) {
+ for (String raw : text.split("\n", -1)) {
+ String line = raw.trim();
+ if (line.isEmpty() || line.startsWith("//") || line.startsWith("*") || line.startsWith("/*")) {
+ continue;
+ }
+ if (line.contains("aiimage.security.internal-token") || line.contains("AIIMAGE_INTERNAL_TOKEN")) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static List mainSources() throws IOException {
+ Path root = moduleRoot().resolve("src/main/java");
+ if (!Files.isDirectory(root)) {
+ fail("找不到 " + root + " —— 用例依赖以 backend-java 为工作目录运行,别让守卫静默通过");
+ }
+ try (Stream walk = Files.walk(root)) {
+ return walk.filter(Files::isRegularFile)
+ .filter(p -> p.getFileName().toString().endsWith(".java"))
+ .collect(Collectors.toList());
+ }
+ }
+
+ private static Path sourceOf(String fileName) throws IOException {
+ return mainSources().stream()
+ .filter(p -> p.getFileName().toString().equals(fileName))
+ .findFirst()
+ .orElseThrow(() -> new IllegalStateException("找不到 " + fileName));
+ }
+
+ /** surefire 的工作目录是模块目录;从仓库根或 IDE 跑时退到 backend-java/。 */
+ private static Path moduleRoot() {
+ Path here = Path.of("").toAbsolutePath();
+ if (Files.isDirectory(here.resolve("src/main/java"))) {
+ return here;
+ }
+ Path nested = here.resolve("backend-java");
+ if (Files.isDirectory(nested.resolve("src/main/java"))) {
+ return nested;
+ }
+ throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
+ }
+
+ private static String read(Path file) {
+ try {
+ return Files.readString(file, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new IllegalStateException("读取失败: " + file, e);
+ }
+ }
+}