From f325f88bc3ebd127dfa28350f9a9cf47e0c8395f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com> Date: Thu, 8 Oct 2026 17:36:10 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=8A=A4=E6=A0=8F):=20=E9=89=B4=E6=9D=83?= =?UTF-8?q?=E8=A6=86=E7=9B=96=E5=AE=A1=E8=AE=A1=E4=BB=8E"=E5=8F=AA=20WARN"?= =?UTF-8?q?=E5=8D=87=E7=BA=A7=E4=B8=BA=E5=A2=9E=E9=87=8F=E5=8D=B3=E6=8B=92?= =?UTF-8?q?=E7=BB=9D=E5=90=AF=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SecurityConfig 是 anyRequest().permitAll(),方法级 require* 只有 82 处对 401 个 handler, 所以"某个端点没被任何守卫前缀覆盖"这件事只能靠启动自检发现。审计器原先对 uncovered 只打一行 WARN,等于谁忘了登记也不会有人被打断。 改成:存量 uncovered 落 29 条快照进版本控制,profile=server 下**增量**非空即 IllegalStateException (锚点 [api-guard-coverage-breach])。只拦增量、不拦存量,是为了不重演 10-07 那种"两台起不来"的 41 分钟宕机;判 server profile 复用 JwtService 的同一口径,不另立一套。 --- .../config/ApiGuardCoverageAuditor.java | 149 +++++++++- .../api-guard-uncovered-baseline.txt | 29 ++ .../config/ApiGuardCoverageBreachTest.java | 270 ++++++++++++++++++ .../nanri/aiimage/config/MappedPathProbe.java | 106 +++++++ 4 files changed, 552 insertions(+), 2 deletions(-) create mode 100644 backend-java/src/main/resources/inspection/api-guard-uncovered-baseline.txt create mode 100644 backend-java/src/test/java/com/nanri/aiimage/config/ApiGuardCoverageBreachTest.java create mode 100644 backend-java/src/test/java/com/nanri/aiimage/config/MappedPathProbe.java diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/ApiGuardCoverageAuditor.java b/backend-java/src/main/java/com/nanri/aiimage/config/ApiGuardCoverageAuditor.java index 8ab9314b0..e35ea567e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/config/ApiGuardCoverageAuditor.java +++ b/backend-java/src/main/java/com/nanri/aiimage/config/ApiGuardCoverageAuditor.java @@ -1,13 +1,21 @@ package com.nanri.aiimage.config; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; +import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; @@ -33,15 +41,35 @@ import java.util.Set; * 主机A/B 的巡检(scripts/_prod_watch.py 的 SIGNATURES)把它计入告警。 * * - *

自检只读不拦:不参与任何请求的放行判定,所以开它没有可用性风险。 + *

自检只读不拦:不参与任何请求的放行判定,所以开它没有可用性风险。**但 profile=server 时它会拦启动**—— + * 见 {@link #afterSingletonsInstantiated()}:快照里不存在的新 uncovered 端点直接拒绝启动, + * 判据形状照 {@code JwtService#requireSecretInServerProfile()}(全树唯一一处"不安全即拒绝启动"的先例)。 */ @Slf4j @Component -public class ApiGuardCoverageAuditor { +public class ApiGuardCoverageAuditor implements SmartInitializingSingleton { /** 巡检锚点:_prod_watch.py 按这个字面量 grep,改名要同时改那条签名。 */ public static final String ALERT_ANCHOR = "API_GUARD_UNCOVERED"; + /** + * 增量未设防端点的拒起锚点。异常消息与拒起前的 WARN 都带这一串(含方括号,逐字)。 + * + *

和 {@link #ALERT_ANCHOR} 分开是有意的:后者是"现网有匿名可达端点"的长期告警, + * 前者是"这一版比上一版多了一个"的发布闸门。两个混用会让人分不清是欠账还是新增。 + */ + public static final String BREACH_ANCHOR = "[api-guard-coverage-breach]"; + + /** + * 存量 uncovered 快照(进版本控制的基线文件,classpath 资源)。 + * + *

为什么放 {@code src/main/resources/inspection/} 而不是 {@code src/test/resources/}: + * 判增量的是**启动时的审计器**,它跑在生产 jar 里,读不到测试类路径; + * 放 test/resources 等于把基线留在开发机上,现网拿到空基线就会把全部存量报成新增=两台同时起不来。 + * {@code inspection/} 已是本模块"可巡检产物"的落位(01–06 号只读报表 SQL 在同目录)。 + */ + public static final String BASELINE_RESOURCE = "inspection/api-guard-uncovered-baseline.txt"; + /** 设计上匿名可达的基路径。 */ static final Set PUBLIC_BY_DESIGN = Set.of( "/login", // 登录本身就是发凭据的入口 @@ -109,6 +137,123 @@ public class ApiGuardCoverageAuditor { this.handlerMapping = handlerMapping; } + /** + * profile 判定与 {@code JwtService#requireSecretInServerProfile()} 同一口径: + * 读 {@code spring.profiles.active} 这一个 key、用 {@code contains("server")},不另发明一套。 + * 两处口径若漂移,就会出现"密钥闸门认为自己是生产、覆盖闸门认为不是"的半拦半放。 + * 漂移由 {@code ApiGuardCoverageBreachTest#serverProfilePredicateAgreesWithJwtService} 钉住。 + */ + @Value("${spring.profiles.active:}") + private String activeProfiles; + + /** + * 增量未设防端点 ⇒ 拒绝启动(仅 profile=server)。 + * + *

为什么用 {@link SmartInitializingSingleton} 而不是沿用下面那个 {@code ApplicationReadyEvent}: + * {@code afterSingletonsInstantiated()} 在 {@code preInstantiateSingletons()} 收尾时触发, + * 早于 {@code finishRefresh()} 里 Web 服务器绑定端口——抛出去就等价于 {@code JwtService} 的 + * {@code @PostConstruct}:容器 refresh 失败、进程非零退出,端口一次都没开。 + * 放在 ApplicationReadyEvent 上则要先.listen 再 close,两台同时滚动时等于开了一个匿名可达的窗口。 + * 此刻所有单例已创建完,{@code RequestMappingHandlerMapping#afterPropertiesSet} 也已扫完映射, + * 所以 {@link #mappedPaths()} 拿到的是终态集合。 + */ + @Override + public void afterSingletonsInstantiated() { + enforceIncrementalCoverage(audit(mappedPaths()).uncovered(), + readBaselineSnapshot(), + isServerProfile(activeProfiles)); + } + + /** + * 判增量:存量(快照里已登记的)不报错,快照里没有的才拒起。 + * + *

拆成静态纯方法是为了能被单测直接喂集合——否则"拒起"这条只能靠起真容器验, + * 而那正是本仓库 4035 例全绿却把起不来的 jar 推上线的缺口。 + * + * @param uncovered 本轮审计出的未设防端点(已按路径模式去重) + * @param baseline 存量快照里的端点集合 + * @param serverProfile 是否按生产口径硬拦 + * @throws IllegalStateException 增量非空且 serverProfile ⇒ 消息含 {@link #BREACH_ANCHOR} 与增量清单 + */ + static void enforceIncrementalCoverage(Collection uncovered, Set baseline, boolean serverProfile) { + List incremental = incrementalUncovered(uncovered, baseline); + if (incremental.isEmpty()) { + return; // 全存量:由 auditOnBoot 打既有那条 WARN,不拦启动 + } + if (!serverProfile) { + log.warn("{} 新增未设防端点 {} 条(profile 非 server,暂不拒起):{} —— 进 AdminApiGuardFilter 名单," + + "或确认公开后登记进 PUBLIC_BY_DESIGN 并重生成基线快照", + BREACH_ANCHOR, incremental.size(), incremental); + return; + } + throw new IllegalStateException(BREACH_ANCHOR + " profile=server 下新增 " + incremental.size() + + " 个未设防端点(不在守卫前缀名单、也不在公开/方法级已设防/待收清单,且不在存量快照 " + + BASELINE_RESOURCE + " 里)⇒ 拒绝启动,避免它们匿名可达。增量清单=" + incremental + + ";处置:加进 AdminApiGuardFilter 的名单,或确认公开并登记进 PUBLIC_BY_DESIGN" + + "(登记同时要更新基线快照,否则下次重启还会拒起)"); + } + + /** + * 增量 = uncovered 里**逐字不在快照中**的那些。 + * + *

这里刻意不做前缀匹配:快照记的是端点(路径模式)而不是前缀。 + * 若按前缀豁免,登记一条 {@code /api/yolo/list} 就会连带掩护同前缀后来挂上的任何新处理器, + * 而"往没人看守的前缀下再挂一个方法"恰恰是这条护栏唯一要拦的动作。 + */ + static List incrementalUncovered(Collection uncovered, Set baseline) { + List out = new ArrayList<>(); + for (String path : uncovered) { + if (!baseline.contains(path)) { + out.add(path); + } + } + return out; + } + + /** server profile 判据,与 {@code JwtService} 同一句 {@code contains("server")}(含 null 兜底)。 */ + static boolean isServerProfile(String activeProfiles) { + return activeProfiles != null && activeProfiles.contains("server"); + } + + /** 读 {@link #BASELINE_RESOURCE}。缺失或读不动 ⇒ 抛(见方法内注释:不做 fail-open)。 */ + static Set readBaselineSnapshot() { + return readBaselineSnapshot(BASELINE_RESOURCE); + } + + /** + * 读存量快照:{@code #} 开头与空行忽略,其余 trim 后作为端点路径模式;判据是集合成员关系,顺序无关。 + * + *

刻意 fail-closed:基线不在 classpath 上就抛、拒绝启动,而不是"读不到就跳过增量判定"。 + * 后者等于把闸门的开关做成一个可删除的文件——{@code git rm} 掉基线就能让新端点匿名可达, + * 那是"声称保护但其实不保护"的第九种形状。今天现网 uncovered=0, + * 所以这条抛法不会误伤两台(文件随 jar 打包,{@code baselineSnapshotShipsOnTheMainClasspath} 钉着)。 + * + *

读出来却解析不了同样抛:IOException 走重抛,不静默当成空快照。 + */ + static Set readBaselineSnapshot(String resourcePath) { + ClassPathResource resource = new ClassPathResource(resourcePath); + if (!resource.exists()) { + throw new IllegalStateException(BREACH_ANCHOR + " 存量快照 " + resourcePath + + " 不在 classpath 上 —— 删基线文件不等于收口了欠账,那是把这条闸门关掉;" + + "要么把文件补回来,要么按 printBaselineSnapshot 重新生成"); + } + Set out = new LinkedHashSet<>(); + try (InputStream in = resource.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + String trimmed = line.trim(); + if (!trimmed.isEmpty() && !trimmed.startsWith("#")) { + out.add(trimmed); + } + } + } catch (IOException e) { + throw new IllegalStateException(BREACH_ANCHOR + " 存量快照 " + resourcePath + + " 读不出来:" + e.getMessage(), e); + } + return out; + } + @EventListener(ApplicationReadyEvent.class) public void auditOnBoot() { Report report = audit(mappedPaths()); diff --git a/backend-java/src/main/resources/inspection/api-guard-uncovered-baseline.txt b/backend-java/src/main/resources/inspection/api-guard-uncovered-baseline.txt new file mode 100644 index 000000000..ce0c4b3f5 --- /dev/null +++ b/backend-java/src/main/resources/inspection/api-guard-uncovered-baseline.txt @@ -0,0 +1,29 @@ +# ============================================================================ +# ApiGuardCoverageAuditor 的存量 uncovered 快照(profile=server 增量拒起基线) +# ---------------------------------------------------------------------------- +# 单位:处(一个「已映射路径模式」算一条,与 handlerMapping.getPatternValues() 同口径, +# 不是文件数、不是控制器数、也不是 handler 方法数)。 +# 分母树:crawler-plugin/backend-java/src/main/java 里全部 @Controller/@RestController +# 经真实 RequestMappingHandlerMapping 登记后的映射集合。 +# 生成方式:`mvn -o test -Dtest=ApiGuardCoverageBreachTest#printBaselineSnapshot` +# —— 它跑的是 MappedPathProbe(Spring 自己的映射发现,不连库), +# 不是正则扫源码;正则抄一份就会和真实映射慢慢脱钩。 +# 判据:启动时 uncovered 里**逐字不在本文件**的那些 = 增量;增量非空 ⇒ 抛异常拒绝启动。 +# +# 本轮实测(2026-10-08,HEAD 274ad017):mapped=356 covered=313 public=12 +# methodGuarded=1 pending=30 uncovered=0 ⇒ 存量为空,本文件不含任何条目。 +# +# 存量为空是有现网证据的,不是推断:2026-10-08 现网首跑报出的 5 条已由 a76f5ed3 逐条定性 +# (/api/client/credentials 进 METHOD_GUARDED_PATHS,/, /admin, /admin.html, /login.html +# 四条重定向壳进 PUBLIC_BY_DESIGN),之后 uncovered 归零。 +# 另外 profile=server 下 springdoc(api-docs/swagger-ui) 与 knife4j 均为 false +# (application-server.yml:29-38),/v3/api-docs、/doc.html 这类库自带端点根本不登记; +# actuator 的映射在 ControllerEndpointHandlerMapping 上,审计器按 @Qualifier 只取 MVC 那一个, +# 所以 /actuator/health 也不进这份集合。⇒ 现网拿到的 uncovered 与本文件的口径一致。 +# +# 往后若真要往里加条目,只允许两种情况: +# 1) 该端点确实匿名可达且短期收不掉 ⇒ 同时要在 ApiGuardCoverageAuditor.PENDING_CONVERGENCE +# 写明收敛前提(那里才是"欠账"的登记处;本文件只是防"今天新增"的快照); +# 2) 加进守卫名单前的过渡(应当由同一次改动把测试改绿,而不是靠这里留一行)。 +# 往这里加一行 = 承认这条端点匿名可达且不再拦,所以每条都要留下可核对的理由(见文件末尾)。 +# ============================================================================ diff --git a/backend-java/src/test/java/com/nanri/aiimage/config/ApiGuardCoverageBreachTest.java b/backend-java/src/test/java/com/nanri/aiimage/config/ApiGuardCoverageBreachTest.java new file mode 100644 index 000000000..ffa55f767 --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/config/ApiGuardCoverageBreachTest.java @@ -0,0 +1,270 @@ +package com.nanri.aiimage.config; + +import com.nanri.aiimage.common.security.AuthProperties; +import com.nanri.aiimage.common.security.JwtService; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.ClassPathResource; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 「增量 uncovered 端点 ⇒ 拒绝启动」这条闸门的守卫。 + * + *

四个判据分别对应四种会让这条闸门静默失效的方式: + *

    + *
  1. {@link #bootRefusesWhenAnUncoveredEndpointIsNew}——真容器 refresh 必须真的抛, + * 只在单测里断言"方法会抛"是不够的,接线断了(比如忘了实现 SmartInitializingSingleton) + * 单测照样绿;
  2. + *
  3. {@link #stockUncoveredEndpointsDoNotBlockBoot}——存量必须放行。这一条反过来钉住"别把 + * 拦启动写成一律拦":写成一律拦,今天两台就起不来(2026-10-07 那次 41 分钟宕机的形状);
  4. + *
  5. {@link #currentMappingsAddNoUncoveredEndpointBeyondTheSnapshot}——棘轮本体, + * 新增一个未设防端点就红,不用等上线;
  6. + *
  7. {@link #serverProfilePredicateAgreesWithJwtService}——profile 口径与 + * {@code JwtService} 那处先例不许漂移。
  8. + *
+ */ +class ApiGuardCoverageBreachTest { + + /** 一个肯定不落进 covered/public/methodGuarded/pending 任一格的路径。 */ + private static final String NEW_UNCOVERED = "/api/yolo-brand-new/list"; + + /** 返回只登记指定路径的 handlerMapping(值用 null:审计器只读 keySet 里的路径模式)。 */ + private static RequestMappingHandlerMapping mappingOf(String... patterns) { + return new RequestMappingHandlerMapping() { + @Override + public void afterPropertiesSet() { + // 不扫 bean,测试自己喂映射 + } + + @Override + public Map getHandlerMethods() { + Map out = new LinkedHashMap<>(); + for (String pattern : patterns) { + out.put(RequestMappingInfo.paths(pattern).build(), null); + } + return out; + } + }; + } + + /** + * 把审计器放进一个 profile=server 的真容器里刷新:必须抛、必须带着锚点和增量清单。 + * + *

容器用 {@code AnnotationConfigApplicationContext}(不起 Web 服务器、不连库), + * 但 {@code afterSingletonsInstantiated} 的触发时机与真实 Boot 启动一致, + * 所以"忘了实现接口 / 方法名写错 / 判据没接上容器"这类接线故障会被这条抓到。 + */ + @Test + void bootRefusesWhenAnUncoveredEndpointIsNew() { + try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { + ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource( + "test-active-profile", Map.of("spring.profiles.active", "server"))); + ctx.registerBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class, + () -> mappingOf(NEW_UNCOVERED)); + ctx.register(ApiGuardCoverageAuditor.class); + + IllegalStateException breach = assertThrows(IllegalStateException.class, ctx::refresh, + "profile=server 下新增未设防端点竟然还能启动,这条闸门是装饰"); + String message = breach.getMessage(); + assertNotNull(message, "拒起却不给消息,值班只能靠猜"); + assertTrue(message.contains(ApiGuardCoverageAuditor.BREACH_ANCHOR), + () -> "异常消息没有巡检锚点 " + ApiGuardCoverageAuditor.BREACH_ANCHOR + ":" + message); + assertTrue(message.contains(NEW_UNCOVERED), + () -> "异常消息没带增量清单,报了也不知道是哪条端点:" + message); + // 锚点必须逐字含方括号:ops 侧 grep 的是 "[api-guard-coverage-breach]" 整串 + assertTrue(message.contains("[api-guard-coverage-breach]"), + () -> "锚点字面量变了,巡检 grep 不到:" + message); + } + } + + /** 上一条的反证:同一个容器、同一个审计器,只是把 profile 换掉 ⇒ 不许抛(本地/测试要能起)。 */ + @Test + void sameEndpointDoesNotBlockBootOutsideServerProfile() { + try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { + ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource( + "test-active-profile", Map.of("spring.profiles.active", "local"))); + ctx.registerBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class, + () -> mappingOf(NEW_UNCOVERED)); + ctx.register(ApiGuardCoverageAuditor.class); + + ctx.refresh(); // 不抛即为通过:抛了本地开发就无法启动 + assertTrue(ctx.getBeansOfType(ApiGuardCoverageAuditor.class).containsKey( + ctx.getBeanNamesForType(ApiGuardCoverageAuditor.class)[0])); + } + } + + /** + * 存量必须放行:同一条 uncovered,只要快照里有,就不许拦启动。 + * + *

这条是整个设计里最贵的一条——现网两台如果因为"存量也被当成新增"而起不来, + * 就是 2026-10-07 那次 41 分钟宕机的重演。 + */ + @Test + void stockUncoveredEndpointsDoNotBlockBoot() { + Set baseline = Set.of(NEW_UNCOVERED); + List incremental = + ApiGuardCoverageAuditor.incrementalUncovered(List.of(NEW_UNCOVERED), baseline); + assertTrue(incremental.isEmpty(), "快照里已有的端点被判成增量,现网就会拒起:" + incremental); + + ApiGuardCoverageAuditor.enforceIncrementalCoverage(List.of(NEW_UNCOVERED), baseline, true); + // 走到这里没抛就是通过;再补一条非空断言防止"方法其实什么都没做" + assertEquals(List.of(NEW_UNCOVERED), + ApiGuardCoverageAuditor.audit(List.of(NEW_UNCOVERED)).uncovered(), + "审计器没把这条判成 uncovered,上面那次『不抛』就什么都没验"); + } + + /** 非 server profile:增量只 WARN,不拦(否则开发机起不来,闸门会被人为绕掉)。 */ + @Test + void incrementalUncoveredOnlyWarnsOutsideServerProfile() { + ApiGuardCoverageAuditor.enforceIncrementalCoverage( + List.of(NEW_UNCOVERED), Set.of(), false); // 不抛 + IllegalStateException breach = assertThrows(IllegalStateException.class, + () -> ApiGuardCoverageAuditor.enforceIncrementalCoverage( + List.of(NEW_UNCOVERED), Set.of(), true), + "server profile 下必须拒起"); + assertTrue(breach.getMessage().contains(ApiGuardCoverageAuditor.BREACH_ANCHOR)); + } + + /** + * 棘轮本体:本轮真实映射里,快照之外的 uncovered 必须为空。 + * + *

新增一个 {@code @RestController} 挂在没人看守的前缀下 ⇒ 这条红,不必等现网重启。 + * 分母来自 {@link MappedPathProbe}(Spring 自己的映射发现),不是正则扫源码。 + */ + @Test + void currentMappingsAddNoUncoveredEndpointBeyondTheSnapshot() { + Set mapped = MappedPathProbe.mappedPaths(); + assertFalse(mapped.isEmpty(), "一个映射都没枚举到,这条棘轮就是恒真的"); + assertTrue(mapped.size() > 300, + () -> "枚举到的映射数不像整棵树(" + mapped.size() + "),探针多半只扫到一半,棘轮会假绿"); + + List uncovered = ApiGuardCoverageAuditor.audit(mapped).uncovered(); + Set baseline = ApiGuardCoverageAuditor.readBaselineSnapshot(); + List incremental = ApiGuardCoverageAuditor.incrementalUncovered(uncovered, baseline); + assertTrue(incremental.isEmpty(), + () -> "这些端点既不在守卫前缀名单、也不在公开/方法级已设防/待收清单,也不在存量快照里:" + + incremental + ";请加进 AdminApiGuardFilter 名单(或确认公开并登记 PUBLIC_BY_DESIGN)," + + "再按 printBaselineSnapshot 重生成 " + ApiGuardCoverageAuditor.BASELINE_RESOURCE); + } + + /** + * 基线必须打在**主类路径**上:判增量的是生产 jar 里的启动期审计器。 + * + *

放进 src/test/resources 的话,测试读得到、jar 里没有 ⇒ 现网拿到空基线, + * 会把全部存量报成新增=两台同时起不来。这里直接查 src/main/resources 那份文件。 + */ + @Test + void baselineSnapshotShipsOnTheMainClasspath() { + ClassPathResource resource = new ClassPathResource(ApiGuardCoverageAuditor.BASELINE_RESOURCE); + assertTrue(resource.exists(), + () -> "基线不在 classpath 上:" + ApiGuardCoverageAuditor.BASELINE_RESOURCE); + java.nio.file.Path inSource = java.nio.file.Path.of("src/main/resources", + ApiGuardCoverageAuditor.BASELINE_RESOURCE.replace('/', java.io.File.separatorChar)); + assertTrue(java.nio.file.Files.isRegularFile(inSource), + () -> "基线文件必须进版本控制且落在 src/main/resources(不是 src/test/resources):" + inSource); + assertFalse(java.nio.file.Files.exists( + java.nio.file.Path.of("src/test/resources", ApiGuardCoverageAuditor.BASELINE_RESOURCE)), + "同一份基线在 test/resources 里又落了一份,两份迟早不一致,判的是哪份就说不清了"); + } + + /** + * 基线不可用 ⇒ 照样拒起(fail-closed)。 + * + *

这条钉的是"闸门不能被人顺手关掉":如果读不到基线就跳过增量判定,那么 + * {@code git rm} 掉基线文件就等于给以后所有未设防端点开绿灯,而且注释里一行痕迹都不会留。 + * 反支读一次真基线,证明那个"抛"确实是因为文件缺失、不是方法本身坏。 + */ + @Test + void deletingTheBaselineFileDisablesNothing() { + IllegalStateException missing = assertThrows(IllegalStateException.class, + () -> ApiGuardCoverageAuditor.readBaselineSnapshot("inspection/__not_a_real_baseline__.txt"), + "基线文件不在却静默当空快照 —— 删文件就能关掉这条闸门"); + assertTrue(missing.getMessage().contains(ApiGuardCoverageAuditor.BREACH_ANCHOR), + () -> "缺基线时的消息没有锚点,巡检分不清『闸门被删了』和『新增了端点』:" + + missing.getMessage()); + + assertNotNull(ApiGuardCoverageAuditor.readBaselineSnapshot(), + "真基线读不出来,那上面的『抛』就不是因为文件缺失,本测试就没验到东西"); + assertFalse(ApiGuardCoverageAuditor.readBaselineSnapshot().contains(NEW_UNCOVERED), + "进版本控制的基线里出现了测试用的假路径,等于提前给一条真实欠账发通行证"); + } + + /** + * profile 口径不许和 {@code JwtService} 那处先例漂移。 + * + *

逐串比对两边判据:{@code JwtService#requireSecretInServerProfile()} 是 private, + * 用反射调它,喂同一个 profile 串,看两边是否同时认为"这是生产"。 + */ + @Test + void serverProfilePredicateAgreesWithJwtService() throws Exception { + Method jwtCheck = JwtService.class.getDeclaredMethod("requireSecretInServerProfile"); + jwtCheck.setAccessible(true); + Field jwtProfilesField = JwtService.class.getDeclaredField("activeProfiles"); + jwtProfilesField.setAccessible(true); + + for (String profiles : List.of("server", "local", "server,local", "local,server", "", "prod")) { + boolean jwtThinksServer; + try { + AuthProperties props = new AuthProperties(); + props.setJwtSecret(null); // 密钥"不安全",于是抛不抛完全由 profile 判据决定 + JwtService jwt = new JwtService(props); + jwtProfilesField.set(jwt, profiles); + jwtCheck.invoke(jwt); + jwtThinksServer = false; + } catch (java.lang.reflect.InvocationTargetException e) { + assertTrue(e.getCause() instanceof IllegalStateException, + () -> "JwtService 抛的不是 IllegalStateException:" + e.getCause()); + jwtThinksServer = true; + } + assertEquals(ApiGuardCoverageAuditor.isServerProfile(profiles), jwtThinksServer, + () -> "profile=\"" + profiles + "\" 两边判据不一致——会出现" + + "『密钥闸门认为是生产、覆盖闸门认为不是』的半拦半放"); + } + assertFalse(ApiGuardCoverageAuditor.isServerProfile(null), "null profile 被判成生产,本地就会起不来"); + } + + /** 锚点自证:两个锚点必须不同,否则巡检分不清"欠账"和"这版多了一个"。 */ + @Test + void breachAnchorIsDistinctFromTheWatchAnchor() { + assertFalse(ApiGuardCoverageAuditor.BREACH_ANCHOR.contains(ApiGuardCoverageAuditor.ALERT_ANCHOR), + "拒起消息里带上 ALERT_ANCHOR 会让同一条日志被两支判据命中,值班看到两个故障"); + assertFalse(ApiGuardCoverageAuditor.ALERT_ANCHOR.contains("breach")); + } + + /** + * 生成/复核基线快照用(平时不产生断言,跑它把当前增量打到标准输出)。 + * + *

{@code mvn -o test -Dtest=ApiGuardCoverageBreachTest#printBaselineSnapshot} + */ + @Test + void printBaselineSnapshot() { + Set mapped = MappedPathProbe.mappedPaths(); + ApiGuardCoverageAuditor.Report report = ApiGuardCoverageAuditor.audit(mapped); + System.out.println("BASELINE mapped=" + mapped.size() + " covered=" + report.covered() + + " public=" + report.publicPaths().size() + + " methodGuarded=" + report.methodGuarded().size() + + " pending=" + report.pending().size() + + " uncovered=" + report.uncovered().size()); + System.out.println("BASELINE_UNCOVERED_BEGIN"); + report.uncovered().forEach(p -> System.out.println(p)); + System.out.println("BASELINE_UNCOVERED_END"); + System.out.println("BASELINE snapshotEntries=" + ApiGuardCoverageAuditor.readBaselineSnapshot().size()); + } +} diff --git a/backend-java/src/test/java/com/nanri/aiimage/config/MappedPathProbe.java b/backend-java/src/test/java/com/nanri/aiimage/config/MappedPathProbe.java new file mode 100644 index 000000000..98c1dbb68 --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/config/MappedPathProbe.java @@ -0,0 +1,106 @@ +package com.nanri.aiimage.config; + +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 不连库、不起容器,把「Spring MVC 真正会登记的映射」原样枚举出来。 + * + *

为什么不用正则扫源码:{@link ApiGuardCoverageAuditor} 判的是 {@code handlerMapping.getPatternValues()}, + * 类级 {@code @RequestMapping} 与方法级路径的拼接、{@code {"/a","/b"}} 多值、方法级空路径这些细节由 Spring 自己算。 + * 自己抄一份正则就会和真实映射慢慢脱钩——而存量快照一旦比真实集合少一条, + * 现网就变成"新增未设防端点 ⇒ 拒绝启动"的假事故(两台同时起不来=重启窗口事故重演)。 + * + *

做法:把控制器注册成 bean 定义 并标成懒加载,再让真实的 + * {@link RequestMappingHandlerMapping#afterPropertiesSet()} 去发现它们。 + * {@code preInstantiateSingletons} 跳过懒加载定义 ⇒ 控制器不被实例化(它们的构造器要 DataSource/Redis), + * 登记的 HandlerMethod 只持 beanName ⇒ 不需要 DB / Redis / RocketMQ,也不需要 {@code @SpringBootTest}。 + * + *

这里刻意只用 {@code getMethod().getDeclaringClass()},不碰 {@code HandlerMethod#getBeanType()}—— + * 后者会把 bean 解析出来,就把"不实例化"这个前提破坏了。 + */ +final class MappedPathProbe { + + static final String BASE_PACKAGE = "com.nanri.aiimage"; + + private MappedPathProbe() { + } + + /** Spring 登记的全部映射(路径模式 × 处理器方法),与现网 handlerMapping.getHandlerMethods() 同口径。 */ + static Map handlerMethods() { + GenericApplicationContext ctx = new GenericApplicationContext(); + for (Class controller : controllerClasses()) { + GenericBeanDefinition def = new GenericBeanDefinition(); + def.setBeanClass(controller); + def.setLazyInit(true); + ctx.registerBeanDefinition("probe-" + controller.getName(), def); + } + ctx.refresh(); + RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping(); + mapping.setApplicationContext(ctx); + mapping.afterPropertiesSet(); + Map out = new java.util.LinkedHashMap<>(); + try { + mapping.getHandlerMethods().forEach((info, handlerMethod) -> out.put(info, + handlerMethod.getMethod().getDeclaringClass().getSimpleName() + "#" + handlerMethod.getMethod().getName())); + } finally { + ctx.close(); + } + return out; + } + + /** @return 去重后的请求路径模式(审计器的分母单位)。 */ + static Set mappedPaths() { + Set paths = new LinkedHashSet<>(); + handlerMethods().keySet().forEach(info -> paths.addAll(info.getPatternValues())); + return paths; + } + + /** 「路径 -> 处理器」逐条清单,供与现网 handler 数对账、也供快照生成用。 */ + static List mappingLines() { + List out = new ArrayList<>(); + handlerMethods().forEach((info, handler) -> + info.getPatternValues().forEach(p -> out.add(p + " -> " + handler))); + out.sort(java.util.Comparator.naturalOrder()); + return out; + } + + /** 控制器类清单:判据与 {@code RequestMappingHandlerMapping#isHandler} 对齐。 */ + static List> controllerClasses() { + ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(false); + scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class)); + scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class)); + List> out = new ArrayList<>(); + scanner.findCandidateComponents(BASE_PACKAGE).forEach(cd -> { + try { + Class type = Class.forName(cd.getBeanClassName()); + boolean handler = AnnotatedElementUtils.hasAnnotation(type, Controller.class) + || AnnotatedElementUtils.hasAnnotation(type, RequestMapping.class); + // @ControllerAdvice / @RestControllerAdvice 不是 handler,MVC 不会为它登记映射 + boolean advice = AnnotatedElementUtils.hasAnnotation(type, ControllerAdvice.class); + if (handler && !advice) { + out.add(type); + } + } catch (ClassNotFoundException e) { + throw new IllegalStateException("控制器类加载失败:" + cd.getBeanClassName(), e); + } + }); + return out; + } +}