feat(护栏): 鉴权覆盖审计从"只 WARN"升级为增量即拒绝启动

SecurityConfig 是 anyRequest().permitAll(),方法级 require* 只有 82 处对 401 个 handler,
所以"某个端点没被任何守卫前缀覆盖"这件事只能靠启动自检发现。审计器原先对 uncovered 只打一行
WARN,等于谁忘了登记也不会有人被打断。

改成:存量 uncovered 落 29 条快照进版本控制,profile=server 下**增量**非空即 IllegalStateException
(锚点 [api-guard-coverage-breach])。只拦增量、不拦存量,是为了不重演 10-07 那种"两台起不来"的
41 分钟宕机;判 server profile 复用 JwtService 的同一口径,不另立一套。
This commit is contained in:
2026-10-08 17:36:10 +08:00
parent 419ab3be64
commit f325f88bc3
4 changed files with 552 additions and 2 deletions
@@ -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 端点 ⇒ 拒绝启动」这条闸门的守卫。
*
* <p>四个判据分别对应四种会让这条闸门静默失效的方式:
* <ol>
* <li>{@link #bootRefusesWhenAnUncoveredEndpointIsNew}——真容器 refresh 必须真的抛,
* 只在单测里断言"方法会抛"是不够的,接线断了(比如忘了实现 SmartInitializingSingleton)
* 单测照样绿;</li>
* <li>{@link #stockUncoveredEndpointsDoNotBlockBoot}——存量必须放行。这一条反过来钉住"别把
* 拦启动写成一律拦":写成一律拦,今天两台就起不来(2026-10-07 那次 41 分钟宕机的形状);</li>
* <li>{@link #currentMappingsAddNoUncoveredEndpointBeyondTheSnapshot}——棘轮本体,
* 新增一个未设防端点就红,不用等上线;</li>
* <li>{@link #serverProfilePredicateAgreesWithJwtService}——profile 口径与
* {@code JwtService} 那处先例不许漂移。</li>
* </ol>
*/
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<RequestMappingInfo, HandlerMethod> getHandlerMethods() {
Map<RequestMappingInfo, HandlerMethod> out = new LinkedHashMap<>();
for (String pattern : patterns) {
out.put(RequestMappingInfo.paths(pattern).build(), null);
}
return out;
}
};
}
/**
* 把审计器放进一个 profile=server 的真容器里刷新:必须抛、必须带着锚点和增量清单。
*
* <p>容器用 {@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,只要快照里有,就不许拦启动。
*
* <p>这条是整个设计里最贵的一条——现网两台如果因为"存量也被当成新增"而起不来,
* 就是 2026-10-07 那次 41 分钟宕机的重演。
*/
@Test
void stockUncoveredEndpointsDoNotBlockBoot() {
Set<String> baseline = Set.of(NEW_UNCOVERED);
List<String> 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 必须为空。
*
* <p>新增一个 {@code @RestController} 挂在没人看守的前缀下 ⇒ 这条红,不必等现网重启。
* 分母来自 {@link MappedPathProbe}(Spring 自己的映射发现),不是正则扫源码。
*/
@Test
void currentMappingsAddNoUncoveredEndpointBeyondTheSnapshot() {
Set<String> mapped = MappedPathProbe.mappedPaths();
assertFalse(mapped.isEmpty(), "一个映射都没枚举到,这条棘轮就是恒真的");
assertTrue(mapped.size() > 300,
() -> "枚举到的映射数不像整棵树(" + mapped.size() + "),探针多半只扫到一半,棘轮会假绿");
List<String> uncovered = ApiGuardCoverageAuditor.audit(mapped).uncovered();
Set<String> baseline = ApiGuardCoverageAuditor.readBaselineSnapshot();
List<String> incremental = ApiGuardCoverageAuditor.incrementalUncovered(uncovered, baseline);
assertTrue(incremental.isEmpty(),
() -> "这些端点既不在守卫前缀名单、也不在公开/方法级已设防/待收清单,也不在存量快照里:"
+ incremental + ";请加进 AdminApiGuardFilter 名单(或确认公开并登记 PUBLIC_BY_DESIGN),"
+ "再按 printBaselineSnapshot 重生成 " + ApiGuardCoverageAuditor.BASELINE_RESOURCE);
}
/**
* 基线必须打在**主类路径**上:判增量的是生产 jar 里的启动期审计器。
*
* <p>放进 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)。
*
* <p>这条钉的是"闸门不能被人顺手关掉":如果读不到基线就跳过增量判定,那么
* {@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} 那处先例漂移。
*
* <p>逐串比对两边判据:{@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"));
}
/**
* 生成/复核基线快照用(平时不产生断言,跑它把当前增量打到标准输出)。
*
* <p>{@code mvn -o test -Dtest=ApiGuardCoverageBreachTest#printBaselineSnapshot}
*/
@Test
void printBaselineSnapshot() {
Set<String> 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());
}
}
@@ -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 真正会登记的映射」原样枚举出来。
*
* <p>为什么不用正则扫源码:{@link ApiGuardCoverageAuditor} 判的是 {@code handlerMapping.getPatternValues()},
* 类级 {@code @RequestMapping} 与方法级路径的拼接、{@code {"/a","/b"}} 多值、方法级空路径这些细节由 Spring 自己算。
* 自己抄一份正则就会和真实映射慢慢脱钩——而存量快照一旦比真实集合少一条,
* 现网就变成"新增未设防端点 ⇒ 拒绝启动"的假事故(两台同时起不来=重启窗口事故重演)。
*
* <p>做法:把控制器注册成 bean <b>定义</b> 并标成懒加载,再让真实的
* {@link RequestMappingHandlerMapping#afterPropertiesSet()} 去发现它们。
* {@code preInstantiateSingletons} 跳过懒加载定义 ⇒ 控制器不被实例化(它们的构造器要 DataSource/Redis),
* 登记的 HandlerMethod 只持 beanName ⇒ 不需要 DB / Redis / RocketMQ,也不需要 {@code @SpringBootTest}。
*
* <p>这里刻意只用 {@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<RequestMappingInfo, String> 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<RequestMappingInfo, String> 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<String> mappedPaths() {
Set<String> paths = new LinkedHashSet<>();
handlerMethods().keySet().forEach(info -> paths.addAll(info.getPatternValues()));
return paths;
}
/** 「路径 -> 处理器」逐条清单,供与现网 handler 数对账、也供快照生成用。 */
static List<String> mappingLines() {
List<String> 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<Class<?>> controllerClasses() {
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
List<Class<?>> 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;
}
}