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.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()); } }