后端(补提交): AdminGuardSwitchConfigTest 7 例进库——上一笔 pathspec 提交漏了未跟踪新文件
闸门那 7 例当时是从工作树跑的,不在版本内容里;尺子执行档已经引用了这个类名, 不补就是别人 clone 后 mvn 找不到这一类 ⇒ 格子读成「这一类没跑出结果行」而判红。
This commit is contained in:
@@ -0,0 +1,294 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.testutil.SourceScan;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.env.YamlPropertySourceLoader;
|
||||
import org.springframework.core.env.EnumerablePropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
/**
|
||||
* 兜底鉴权四开关的<b>配置面</b>判据(2026-10-09 评审「安全」项,服务端这一半)。
|
||||
*
|
||||
* <p>评审量到的事实:{@code admin-guard-enabled} / {@code user-tool-guard-enabled} /
|
||||
* {@code user-tool-guard-prefixes} / {@code admin-guard-exempt-prefixes} 四键<b>只活在
|
||||
* {@link AdminApiGuardFilter} 的 {@code @Value} 默认值里,任何 yml 里 0 处</b>。后果与版本硬地板
|
||||
* 同形:不是"值不对",是<b>"没配置"与"配置成惰性"都长得跟"这个功能不存在"一样</b>。
|
||||
*
|
||||
* <p>现网取证(10-09,6 小时窗口,只读 docker logs):主机A {@code [ownership-anonymous]} 24 条
|
||||
* (其中 20 条打在内部令牌通道 {@code /api/internal/user-secret-usage},属设计内)、主机B 8 条
|
||||
* 全打在 {@code /api/product-risk-resolve/*};A 机另有 4 条在 {@code /api/collect-data/*}。
|
||||
* 后两组都在 {@code USER_TOOL_PREFIXES} 名单里,但开关关着 ⇒ 请求不进"必须带凭据"那一步,
|
||||
* 归属改由 {@code user_id} 参数定。<b>这就是翻 true 的价签</b>,不由这一笔决定。
|
||||
*
|
||||
* <p>这一支钉六件事,每件都是能跑的断言:
|
||||
* <ol>
|
||||
* <li>四键在打进 jar 的 {@code application.yml} 里真存在(读 classpath,不读工作区);</li>
|
||||
* <li><b>yml 出厂默认与代码 {@code @Value} 默认逐键相等</b>——两份真相一分家,
|
||||
* "改了 yml"和"改了代码"就会各说各话;</li>
|
||||
* <li>两份前缀名单条数钉死(数值即 {@code USER_TOOL_PREFIX_COUNT} / {@code SELF_SERVICE_PREFIX_COUNT}),
|
||||
* 并在内存里摘掉一条证明计数真会掉;</li>
|
||||
* <li>用户态收紧关着时启动<b>点名自述</b>(WARN + ASCII 锚点),而不是安静地放行每个请求;</li>
|
||||
* <li>开着时改口,并报出"本轮纳入的子集";总闸被关掉时也要点名;</li>
|
||||
* <li>出厂默认下 {@code /api/collect-data} 的匿名请求<b>行为不变</b>——"这一笔没翻真"的执行证据。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>重跑:{@code mvn -o test -Dtest=AdminGuardSwitchConfigTest}(cwd = backend-java)。
|
||||
*/
|
||||
class AdminGuardSwitchConfigTest {
|
||||
|
||||
private static final String KEY_ADMIN = "aiimage.security.admin-guard-enabled";
|
||||
private static final String KEY_USER_TOOL = "aiimage.security.user-tool-guard-enabled";
|
||||
private static final String KEY_USER_TOOL_PREFIXES = "aiimage.security.user-tool-guard-prefixes";
|
||||
private static final String KEY_EXEMPT = "aiimage.security.admin-guard-exempt-prefixes";
|
||||
|
||||
private static final String ANCHOR = AdminApiGuardFilter.SWITCH_ANCHOR;
|
||||
|
||||
private static final int USER_TOOL_PREFIX_COUNT = 15;
|
||||
private static final int SELF_SERVICE_PREFIX_COUNT = 6;
|
||||
|
||||
/** {@code ${ENV:默认}} 形状;只取默认段,判的是出厂值,不受跑测试的机器上的环境变量影响。 */
|
||||
private static final Pattern PLACEHOLDER = Pattern.compile("^\\$\\{([^:}]+):([^}]*)\\}$");
|
||||
|
||||
/** 代码里的 {@code @Value("${key:default}")},用来和 yml 的出厂默认对撞。 */
|
||||
private static final Pattern VALUE_ANNOTATION =
|
||||
Pattern.compile("@Value\\(\"\\$\\{([A-Za-z0-9.\\-]+)(?::([^\"}]*))?\\}\"\\)");
|
||||
|
||||
// ------------------------------------------------------------------ 1 + 2
|
||||
|
||||
@Test
|
||||
void allFourGuardSwitchesAreDeclaredInYaml() {
|
||||
Map<String, String> flat = flatten("application.yml");
|
||||
assertThat(flat).as("四键缺一即判红(「没写=隐式默认」是版本地板踩过的坑)")
|
||||
.containsKeys(KEY_ADMIN, KEY_USER_TOOL, KEY_USER_TOOL_PREFIXES, KEY_EXEMPT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void yamlDefaultsEqualCodeValueDefaults() {
|
||||
Map<String, String> flat = flatten("application.yml");
|
||||
Map<String, String> codeDefaults = codeDefaultsFromSource();
|
||||
for (String key : List.of(KEY_ADMIN, KEY_USER_TOOL, KEY_USER_TOOL_PREFIXES, KEY_EXEMPT)) {
|
||||
assertThat(codeDefaults).as(key + ":代码 @Value 里没这个键,yml 那行是写给谁看的?").containsKey(key);
|
||||
assertThat(shippedDefault(flat, key))
|
||||
.as(key + ":yml 出厂默认与代码 @Value 默认分家")
|
||||
.isEqualTo(codeDefaults.get(key));
|
||||
}
|
||||
// 出厂态本身也钉住:总闸开、用户态收紧关、两份名单没被写死内容
|
||||
assertThat(shippedDefault(flat, KEY_ADMIN)).isEqualTo("true");
|
||||
assertThat(shippedDefault(flat, KEY_USER_TOOL)).isEqualTo("false");
|
||||
assertThat(shippedDefault(flat, KEY_USER_TOOL_PREFIXES)).isEmpty();
|
||||
assertThat(shippedDefault(flat, KEY_EXEMPT)).isEmpty();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 3
|
||||
|
||||
@Test
|
||||
void guardPrefixListsArePinnedAndCannotBeShuffledAway() {
|
||||
String body = SourceScan.withoutComments(SourceScan.sourceText("AdminApiGuardFilter.java"));
|
||||
assertThat(literalsAfter(body, "USER_TOOL_PREFIXES = {"))
|
||||
.as("用户态名单条数(改名单要连同现网匿名命中取证一起过)")
|
||||
.hasSize(USER_TOOL_PREFIX_COUNT);
|
||||
assertThat(literalsAfter(body, "SELF_SERVICE_PREFIXES = {"))
|
||||
.as("无条件名单(新建端点,不挂开关)")
|
||||
.hasSize(SELF_SERVICE_PREFIX_COUNT);
|
||||
|
||||
// 非零对照:内存里摘掉一条,计数必须掉;不然"15 条"只是我此刻的一句描述
|
||||
String cut = body.replaceFirst(Pattern.quote("\"/api/withdraw\","), "");
|
||||
assertThat(literalsAfter(cut, "USER_TOOL_PREFIXES = {"))
|
||||
.as("摘掉 /api/withdraw 后应少一条")
|
||||
.hasSize(USER_TOOL_PREFIX_COUNT - 1);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 4 + 5
|
||||
|
||||
@Test
|
||||
void userToolGuardDisabledIsAnnouncedNotSilentlyInert() {
|
||||
ListAppender<ILoggingEvent> captured = capture();
|
||||
try {
|
||||
filter(true, false, "").reportGuardState();
|
||||
assertThat(messages(captured))
|
||||
.as("收紧关着 = 名单里一条都不强制,必须点名说出来,不能和「没有这个过滤器」同形")
|
||||
.anySatisfy(line -> assertThat(line)
|
||||
.contains(ANCHOR)
|
||||
.contains(KEY_USER_TOOL + "=false")
|
||||
.contains("名单里 " + USER_TOOL_PREFIX_COUNT + " 条")
|
||||
.contains("不强制凭据")
|
||||
.contains(SELF_SERVICE_PREFIX_COUNT + " 条自助前缀"));
|
||||
assertThat(captured.list)
|
||||
.as("这条自述得是 WARN;INFO 在生产日志级别下会被淹掉")
|
||||
.allSatisfy(event -> assertThat(event.getLevel().toString()).isEqualTo("WARN"));
|
||||
} finally {
|
||||
release(captured);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledGuardAnnouncesTheScopedSubsetInsteadOfWarning() {
|
||||
ListAppender<ILoggingEvent> captured = capture();
|
||||
try {
|
||||
filter(true, true, "/api/collect-data,/api/price-track").reportGuardState();
|
||||
assertThat(messages(captured))
|
||||
.as("开着时必须报出「本轮纳入的子集」,只说一句 true 等于没说")
|
||||
.anySatisfy(line -> assertThat(line)
|
||||
.contains(ANCHOR)
|
||||
.contains(KEY_USER_TOOL + "=true")
|
||||
.contains("scoped=2/" + USER_TOOL_PREFIX_COUNT));
|
||||
assertThat(messages(captured))
|
||||
.as("开着时不许再打「不强制凭据」那句")
|
||||
.noneSatisfy(line -> assertThat(line).contains("不强制凭据"));
|
||||
} finally {
|
||||
release(captured);
|
||||
}
|
||||
|
||||
// 子集留空 = 全部一起收,自述必须改口说"全部",不能报成 scoped=0/15(那是"一条都没收"的反义)
|
||||
ListAppender<ILoggingEvent> whole = capture();
|
||||
try {
|
||||
filter(true, true, "").reportGuardState();
|
||||
assertThat(messages(whole)).anySatisfy(line -> assertThat(line)
|
||||
.contains("scoped=" + USER_TOOL_PREFIX_COUNT + "/" + USER_TOOL_PREFIX_COUNT)
|
||||
.contains("全部"));
|
||||
} finally {
|
||||
release(whole);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledAdminMasterSwitchIsAlsoAnnounced() {
|
||||
ListAppender<ILoggingEvent> captured = capture();
|
||||
try {
|
||||
filter(false, false, "").reportGuardState();
|
||||
assertThat(messages(captured))
|
||||
.as("总闸被关掉是最大的惰性态,自述必须点名")
|
||||
.anySatisfy(line -> assertThat(line)
|
||||
.contains(ANCHOR)
|
||||
.contains("admin-guard-enabled=false")
|
||||
.contains("逐请求整体跳过"));
|
||||
assertThat(captured.list).allSatisfy(e -> assertThat(e.getLevel().toString()).isEqualTo("WARN"));
|
||||
} finally {
|
||||
release(captured);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 6
|
||||
|
||||
@Test
|
||||
void shippedDefaultsLeaveAnonymousUserToolRequestBehaviourUnchanged() throws Exception {
|
||||
AdminApiGuardFilter guard = filter(true, false, "");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/collect-data/dashboard");
|
||||
request.setParameter("user_id", "986");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
|
||||
guard.doFilter(request, response, chain);
|
||||
|
||||
assertThat(chain.getRequest())
|
||||
.as("这一笔没翻真:出厂默认下匿名请求仍放行到业务(现网那 4 条 collect-data 命中走的就是这条路)")
|
||||
.isSameAs(request);
|
||||
assertThat(response.getStatus()).as("放行时不许留下 401/403 痕迹").isEqualTo(200);
|
||||
assertThat(response.getContentAsString()).isEmpty();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 助手
|
||||
|
||||
/** 字段顺序跟 {@code @RequiredArgsConstructor} 生成的构造器一致:先 authSupport,再 objectMapper。 */
|
||||
private AdminApiGuardFilter filter(boolean adminGuard, boolean userToolGuard, String scopedPrefixes) {
|
||||
AdminApiGuardFilter guard = new AdminApiGuardFilter(mock(AdminAuthSupport.class), new ObjectMapper());
|
||||
ReflectionTestUtils.setField(guard, "enabled", adminGuard);
|
||||
ReflectionTestUtils.setField(guard, "userToolGuardEnabled", userToolGuard);
|
||||
ReflectionTestUtils.setField(guard, "userToolGuardPrefixes", scopedPrefixes);
|
||||
ReflectionTestUtils.setField(guard, "exemptPrefixes", "");
|
||||
return guard;
|
||||
}
|
||||
|
||||
private ListAppender<ILoggingEvent> capture() {
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(AdminApiGuardFilter.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
return appender;
|
||||
}
|
||||
|
||||
private void release(ListAppender<ILoggingEvent> appender) {
|
||||
((Logger) LoggerFactory.getLogger(AdminApiGuardFilter.class)).detachAppender(appender);
|
||||
}
|
||||
|
||||
private List<String> messages(ListAppender<ILoggingEvent> appender) {
|
||||
return appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
|
||||
}
|
||||
|
||||
/** 名单声明块里的字符串字面量(按构造点名取段,不锚行号)。 */
|
||||
private List<String> literalsAfter(String body, String declaration) {
|
||||
int at = body.indexOf(declaration);
|
||||
assertThat(at).as("源码里找不到 " + declaration + " —— 常量被改名或挪走了").isGreaterThan(-1);
|
||||
int end = body.indexOf("};", at);
|
||||
List<String> out = new ArrayList<>();
|
||||
Matcher m = Pattern.compile("\"(/[^\"]*)\"").matcher(body.substring(at, end));
|
||||
while (m.find()) {
|
||||
out.add(m.group(1));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 从 java 源码里把 {@code @Value} 的 key→默认值 抠出来(无默认段按空串)。 */
|
||||
private Map<String, String> codeDefaultsFromSource() {
|
||||
String body = SourceScan.withoutComments(SourceScan.sourceText("AdminApiGuardFilter.java"));
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
Matcher m = VALUE_ANNOTATION.matcher(body);
|
||||
while (m.find()) {
|
||||
out.put(m.group(1), m.group(2) == null ? "" : m.group(2));
|
||||
}
|
||||
assertThat(out).as("AdminApiGuardFilter 里没解析出任何 @Value(正则与源码形状脱钩了)").isNotEmpty();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 读打进 classpath 的那份 yml({@code src/main/resources} 会被拷进 target/classes),读不到就红。 */
|
||||
private Map<String, String> flatten(String fileName) {
|
||||
ClassPathResource resource = new ClassPathResource(fileName);
|
||||
assertThat(resource.exists())
|
||||
.as("classpath 上找不到 " + fileName + " —— 判据读不到出厂配置就是空转")
|
||||
.isTrue();
|
||||
try (InputStream in = resource.getInputStream()) {
|
||||
Map<String, String> flat = new LinkedHashMap<>();
|
||||
for (PropertySource<?> source : new YamlPropertySourceLoader().load(fileName, resource)) {
|
||||
if (source instanceof EnumerablePropertySource<?> enumerable) {
|
||||
for (String name : enumerable.getPropertyNames()) {
|
||||
Object value = enumerable.getProperty(name);
|
||||
flat.put(name, value == null ? "" : String.valueOf(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(flat).as(fileName + " 解析出来的键数(0 就是解析坏了)").isNotEmpty();
|
||||
return flat;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("读 " + fileName + " 失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 取 {@code ${ENV:默认}} 的默认段;没占位符就按字面值返回。 */
|
||||
private String shippedDefault(Map<String, String> flat, String key) {
|
||||
assertThat(flat).as(key + " 必须在 yml 里显式存在").containsKey(key);
|
||||
String raw = flat.get(key).trim();
|
||||
Matcher m = PLACEHOLDER.matcher(raw);
|
||||
return m.matches() ? m.group(2).trim() : raw;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user