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 端点 ⇒ 拒绝启动」这条闸门的守卫。 * *
四个判据分别对应四种会让这条闸门静默失效的方式: *
容器用 {@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 新增一个 {@code @RestController} 挂在没人看守的前缀下 ⇒ 这条红,不必等现网重启。
* 分母来自 {@link MappedPathProbe}(Spring 自己的映射发现),不是正则扫源码。
*/
@Test
void currentMappingsAddNoUncoveredEndpointBeyondTheSnapshot() {
Set 放进 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