fix(鉴权): 请求身份全量改走会话出口;公开默认 JWT 密钥从出厂件里摘掉

三件事都属"失败很安静"那一类:

1) 请求自带 user_id 当范围条件。cp-item2 只收了会改状态/花钱的出口,其余 28 支控制器
   (进度/列表/详情,本支 18 支、另 10 支因与租户判定收口同文件而随 cp-item3 那笔)照旧把
   "这单是谁的"交给调用方自报:A 传 B 的 user_id 就读到 B 的进度,
   接口 200、日志无声。现在 190 支取请求身份的 handler 只经一个出口(写类 require/resolve、
   读类 resolve),护栏 RequestSuppliedIdentityOutletTest 钉分母 126 写 + 63 读 + 1 豁免
   (内部代理通道 InternalUserProxyController Get /user-proxy 按内部令牌放行)。DTO 形态
   (控制器把整个 @RequestBody 递给 service)靠"该 DTO 是否声明 userId 字段"的索引识别,
   少了这层判据会漏掉一半;进度类 28 支另由 ProgressQueryOwnershipOutletTest 单独钉。
   桌面执行器 4.0.44 不带凭据是既定事实,[ownership-anonymous] 按 URI 计数留证据,
   哪一支的匿名计数归零才允许把它从 resolve 换成 require。
2) 默认 JWT 密钥。application.yml 原本写的是
   `${AIIMAGE_JWT_SECRET:please-change-this-secret-…}`,那个兜底默认值就是 2026-10-07
   现网取证到的东西:两台都跑 profile server 且 env 里没有这个键,于是 JwtService 的启动闸门
   看到的是公开字面量(非空)——既不拒绝启动也不告警,签出来的 token 任何读过源码的人都能伪造
   (含超管)。现在占位符不带默认值、AuthProperties 缺省空串、isInsecure 同时认空串与该字面量,
   server profile 缺密钥直接拒绝启动(宁可起不来)。JwtSecretFallbackGuardrailTest 五例钉
   "资源文件里不许再出现那个字面量"与"两形都算不安全"。
   发版顺序是硬约束:先在 A/B 两台 .env 配好与对方一致的 AIIMAGE_JWT_SECRET,再上新 jar;
   轮换会把所有 web 会话退出登录。
3) 菜单写侧的无操作者重载(create/update/delete)删掉——三道闸门对 operator==null 的处置是
   return(放行),src/main 里没人调用它们,但这条路在,下一支控制器接上去就是静默的跨公司改删。
   读侧 list(String menuType) 是登录态自读与内部代理用的,故意保留,并被点名只许 1 处。

TaskProgressOwnershipSupport / SimilarAsinTaskLightControllerTest / ResultSuccessTimingContractTest
是 handler 加上 HttpServletRequest 之后的既有契约用例订正;SourceScan 补 withoutComments/methodBody
两支取文助手(源码守卫的匹配面必须剥注释,否则 javadoc 里提一句就能把"必须存在"那形喂绿)。

变异自证:RequestSuppliedIdentityOutletTest 4/4(M1 删参数形出口、M2 删 DTO 形出口、
M3 出口只写进注释、M4 isBound 恒真);JwtSecretFallbackGuardrailTest 4/4(J1 恢复 yml 默认值、
J2 恢复 AuthProperties 默认值、J3 闸门退回只判 isBlank、J4 isInsecure 恒真);
MenuWriteOutletOperatorTest 4/4。
This commit is contained in:
2026-10-07 20:01:32 +08:00
parent 4660e02efc
commit c1e7d57cce
30 changed files with 1544 additions and 230 deletions
@@ -0,0 +1,146 @@
package com.nanri.aiimage.common.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* 「JWT 密钥不许悄悄回退到公开默认值」这一族的绊线(2026-10-07 架构三期,缺陷 (f) 收口)。
*
* <p>改之前的形状不是「没做检查」而是「检查够不着」:{@code JwtService} 早在 2026-09 就加了
* 「server profile 未配置密钥即拒绝启动」,判据是 {@code isBlank()};而 application.yml 写的是
* {@code ${AIIMAGE_JWT_SECRET:please-change-this-...}} —— 占位符自带默认值,env 丢失时
* {@code getJwtSecret()} 拿到的是那个<b>公开字面量</b>而不是空串,闸门于是不触发,
* 全站继续用一把写在源码里的密钥签 token(任何人可伪造)。同一条链路 2026-09-14 已经在
* 主机 A 的 15126 Flask 上挂过一次:真实用户 token 全 401,用默认密钥自签的反而 200。</p>
*
* <p>现在的口径:默认值从占位符里摘掉 ⇒ 未配置就是空串 ⇒ 闸门真能拦住;并且闸门改成
* 「空 或 等于那把公开密钥」都不许启动,这样即使有人在别的 profile 文件里把字面量抄回来,
* server profile 仍然起不来。非 server profile(本地开发/测试)保持宽松,否则无法启动。</p>
*/
class JwtSecretFallbackGuardrailTest {
private static final String PUBLIC_SECRET =
"please-change-this-secret-please-rotate-at-least-32-bytes";
/** 占位符的正确形状:冒号后必须什么都没有。 */
private static final Pattern JWT_PLACEHOLDER =
Pattern.compile("\\$\\{AIIMAGE_JWT_SECRET:([^}]*)\\}");
@Test
void noResourceFileShipsThePublicSecretAsADefault() {
List<String> offenders = new ArrayList<>();
for (Path file : resources()) {
String name = file.getFileName().toString();
if (!name.endsWith(".yml") && !name.endsWith(".yaml") && !name.endsWith(".properties")) {
continue;
}
String text = read(file);
Matcher m = JWT_PLACEHOLDER.matcher(text);
while (m.find()) {
if (!m.group(1).isEmpty()) {
offenders.add(name + " 占位符带了默认值 →" + m.group(1));
}
}
if (text.contains(PUBLIC_SECRET)) {
offenders.add(name + " 直接写入了那把公开密钥");
}
}
assertThat(offenders)
.as("resources 里 AIIMAGE_JWT_SECRET 的兜底值 —— 有兜底值时 server profile 的启动闸门就够不着")
.isEmpty();
// 反向:占位符本身还得在,否则「摘掉默认值」会变成「整行删掉」,配置通道就断了
assertThat(resources().stream().map(this::read).anyMatch(t -> t.contains("${AIIMAGE_JWT_SECRET:}")))
.as("必须仍从 AIIMAGE_JWT_SECRET 读取").isTrue();
}
@Test
void unconfiguredPropertiesYieldABlankSecret() {
// 这条是「闸门够得着」的前提:字段默认值一旦还是那把公开密钥,yml 摘干净也没用
assertThat(new AuthProperties().getJwtSecret()).as("AuthProperties 的字段默认值").isBlank();
}
@Test
void theBlankAndThePublicLiteralAreBothInsecureWhileARealKeyIsNot() {
assertThat(JwtService.isInsecure(null)).isTrue();
assertThat(JwtService.isInsecure("")).isTrue();
assertThat(JwtService.isInsecure(" ")).as("空白串").isTrue();
assertThat(JwtService.isInsecure(PUBLIC_SECRET)).as("公开默认值必须算不安全").isTrue();
assertThat(JwtService.isInsecure(PUBLIC_SECRET + "x")).as("差一个字符就不是那把公开密钥").isFalse();
assertThat(JwtService.isInsecure("a-real-rotated-secret-of-plenty-of-length-32plus")).isFalse();
}
@Test
void serverProfileRefusesToStartOnEitherInsecureShape() {
for (String secret : List.of("", PUBLIC_SECRET)) {
assertThatThrownBy(() -> bootWith("server", secret))
.as("server profile + jwt-secret=[" + secret + "]")
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("AIIMAGE_JWT_SECRET");
}
assertThatCode(() -> bootWith("server", "a-real-rotated-secret-of-plenty-of-length-32plus"))
.as("server profile + 真密钥:不许误伤正常启动").doesNotThrowAnyException();
}
/** 本地/测试 profile 保持宽松:否则每个开发机和每例集成测试都起不来,只会被绕过。 */
@Test
void nonServerProfileStillBootsWithoutASecret() {
assertThatCode(() -> bootWith("local", "")).doesNotThrowAnyException();
assertThatCode(() -> bootWith("", PUBLIC_SECRET)).doesNotThrowAnyException();
}
// ---- 夹具 ----
private static void bootWith(String activeProfile, String jwtSecret) {
AuthProperties props = new AuthProperties();
props.setJwtSecret(jwtSecret);
JwtService service = new JwtService(props);
ReflectionTestUtils.setField(service, "activeProfiles", activeProfile);
service.requireSecretInServerProfile();
}
private static List<Path> resources() {
Path dir = mainRoot().resolve("main").resolve("resources");
if (!Files.isDirectory(dir)) {
dir = Path.of("src", "main", "resources");
}
List<Path> out = new ArrayList<>();
try (Stream<Path> stream = Files.walk(dir, 2)) {
stream.filter(Files::isRegularFile).forEach(out::add);
} catch (IOException e) {
throw new IllegalStateException("遍历 resources 失败: " + dir, e);
}
assertThat(out).as("resources 文件数过少说明扫描根走错了").hasSizeGreaterThan(5);
return out;
}
private String read(Path file) {
try {
return Files.readString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("读取失败: " + file, e);
}
}
/** src 目录(test 类与 main 同级,surefire 的 cwd 是模块根)。 */
private static Path mainRoot() {
Path here = Path.of("").toAbsolutePath();
Path direct = here.resolve("src");
if (Files.isDirectory(direct)) {
return direct;
}
return here.resolve("backend-java").resolve("src");
}
}
@@ -0,0 +1,334 @@
package com.nanri.aiimage.common.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.queryasin.controller.QueryAsinTaskController;
import com.nanri.aiimage.modules.queryasin.service.QueryAsinResolveService;
import com.nanri.aiimage.modules.queryasin.service.QueryAsinTaskService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.dto.TaskProgressLightRequest;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.TaskProgressOwnershipSupport;
import com.nanri.aiimage.testutil.SourceScan;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* 「轮询类端点的归属只能由会话说了算」这一族的绊线(2026-10-07 架构三期,缺陷 (d) 收口)。
*
* <p>改之前的形状:12 个模块的 {@code /tasks/progress/batch} + {@code /tasks/progress/light} 与
* 4 个模块的 {@code /tasks/batch}(共 28 支 handler)里,归属用的 {@code user_id} <b>全部取自请求体</b>。
* 请求体里的 id 不是身份,是参数——它有两种坏用法,而且都不报错:</p>
* <ol>
* <li>带上<b>别人的</b> user_id:{@code filterOwnedTaskIds} 与 {@code TaskProgressLightAssembler}
* 都是 {@code user_id = ?} 的正向匹配 ⇒ 匹配的就是别人那一堆任务,越权读命中;</li>
* <li>不带 user_id:{@code filterOwnedTaskIds} 见 null 原样返回、assembler 见 null 不加条件 ⇒
* 匿名遍历自增 taskId 就能读他人任务的状态、错误信息与结果文件就绪标记。</li>
* </ol>
*
* <p>现在的口径:这 28 支一律把请求体 id 交给 {@link AdminAuthSupport#requireOwnershipUserId}
* (解析不出会话身份即 401),网页端恒带 JWT({@code frontend-vue/src/shared/api/http.ts} 的
* cookie + Bearer 两路),而这批端点的调用方<b>只有网页端</b>——桌面执行器不轮询进度
* (2026-10-07 全树 grep:{@code app_client} 里 0 个 {@code tasks/progress} 调用点,只有我自己那支
* live 冒烟脚本)。管理身份仍看得到全部(出口对管理角色返回原参数=不加归属条件),所以后台没被挡。</p>
*
* <p>每支判据都带能红/能绿两向探针,且判据打在<b>剥掉注释的源码</b>上:本类的分母与计数都是
* 「必须等于 N」那一形,吃原文的话谁在注释里提一句 {@code requireOwnershipUserId(} 就能把它喂饱。</p>
*/
class ProgressQueryOwnershipOutletTest {
/** 这一族的全部宿主:12 个模块控制器。少一支就是有人把端点挪去了别处,多一支就是新开了页。 */
private static final List<String> FAMILY_CONTROLLERS = List.of(
"modules/appearancepatent/controller/AppearancePatentController.java",
"modules/collectdata/controller/CollectDataController.java",
"modules/deletebrand/controller/DeleteBrandRunController.java",
"modules/patroldelete/controller/PatrolDeleteController.java",
"modules/pricetrack/controller/PriceTrackController.java",
"modules/productrisk/controller/ProductRiskResolveController.java",
"modules/publish/controller/PublishController.java",
"modules/queryasin/controller/QueryAsinTaskController.java",
"modules/shopdatacrawl/controller/ShopDataCrawlTaskController.java",
"modules/shopmatch/controller/ShopMatchController.java",
"modules/similarasin/controller/SimilarAsinController.java",
"modules/withdraw/controller/WithdrawTaskController.java");
private static final String OUTLET = "requireOwnershipUserId(httpRequest, request.getUserId()";
private static final String WRITE_BACK = "request.setUserId(adminAuthSupport." + OUTLET + "))";
private static final String BODY_USER_ID = "request.getUserId()";
/**
* {@link #nullMeansAuthenticatedAdminWhileAnyUserIdFilters} 走的是真 {@code LambdaQueryWrapper},
* 而纯单测没有 Spring 启动去建 TableInfo 缓存 ⇒ 列名解析会抛 "can not find lambda cache"。
* 同 {@code CompanyScopeSupportTest} 的既有做法:手工注册实体。
*/
@BeforeAll
static void initMybatisPlusTableInfo() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
FileTaskEntity.class);
}
@Test
void everyPollingHandlerBindsTheBodyUserIdToTheSession() {
List<String> offenders = new ArrayList<>();
int handlers = 0;
for (String rel : FAMILY_CONTROLLERS) {
String source = SourceScan.withoutComments(read(mainRoot().resolve(rel)));
for (String mapping : List.of("/tasks/progress/batch", "/tasks/progress/light", "/tasks/batch")) {
for (String segment : handlerSegments(source, mapping)) {
handlers++;
if (!isBoundToSession(segment)) {
offenders.add(rel + " " + mapping + " → " + segment.replace('\n', ' ').trim());
}
}
}
}
// 分母先钉死:28 = 12 progress/batch + 12 progress/light + 4 tasks/batch。
// 扫描坏掉(切不出 handler)与「真的没人漏接」在这一步就会分岔,不会一起恒绿。
assertThat(handlers).as("轮询族 handler 总数").isEqualTo(28);
assertThat(offenders)
.as("归属仍取自请求体(没走会话出口)的 handler")
.isEmpty();
}
@Test
void eachMappingKeepsItsOwnDenominator() {
// 三条分母各钉一个数:整批漏接与某一族整批消失是两种不同的事故,红因要能分开说。
assertThat(countHandlers("/tasks/progress/batch")).as("progress/batch 端点数").isEqualTo(12);
assertThat(countHandlers("/tasks/progress/light")).as("progress/light 端点数").isEqualTo(12);
assertThat(countHandlers("/tasks/batch")).as("tasks/batch(任务详情批量)端点数").isEqualTo(4);
}
/**
* 出口绑定的<b>值</b>必须真的进到查询里,而不是绑完丢掉。
*
* <p>这一支是 {@link #everyPollingHandlerBindsTheBodyUserIdToTheSession} 抓不到的那一形:
* 文本上 {@code requireOwnershipUserId(} 还在(甚至结果被赋给一个没人读的局部变量),
* 但传给 service 的仍是请求体原值 ⇒ 归属等于没改。这里用真 MockMvc 走一遍 HTTP,
* 打桩出口返回一个与请求体不同的 id(4242 ≠ 7),要求 service 收到的必须是 4242。</p>
*/
@Test
void theBoundUserIdIsWhatActuallyReachesTheQuery() throws Exception {
QueryAsinTaskService taskService = mock(QueryAsinTaskService.class);
AdminAuthSupport auth = mock(AdminAuthSupport.class);
when(auth.requireOwnershipUserId(any(), eq(7L))).thenReturn(4242L);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new QueryAsinTaskController(
mock(QueryAsinResolveService.class), taskService,
new TaskProgressOwnershipSupport(null), auth)).build();
mockMvc.perform(post("/api/query-asin/tasks/progress/light")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(
new TaskProgressLightRequest(List.of(3938L), 7L))))
.andExpect(status().isOk());
verify(taskService).progressLight(List.of(3938L), 4242L);
}
/**
* 判据本身要能红:三种坏形状必须判不通过,两种好形状必须判通过。
*
* <p>缺了负样本,{@link #isBoundToSession} 写成 {@code return true} 也会一路绿。</p>
*/
@Test
void theBindingPredicateIsNotVacuous() {
String unboundInline = """
@PostMapping("/tasks/progress/batch")
public ApiResponse<Void> x(@RequestBody R request) {
return ApiResponse.success(service.progressBatch(progressOwnershipSupport
.filterOwnedTaskIds(request.getTaskIds(), request.getUserId())));
}
""";
String noFilterAtAll = """
@PostMapping("/tasks/progress/batch")
public ApiResponse<Void> x(@RequestBody R request) {
return ApiResponse.success(service.getTaskProgressBatch(request.getTaskIds()));
}
""";
String boundButDiscarded = """
@PostMapping("/tasks/progress/light")
public ApiResponse<Void> x(@RequestBody R request, HttpServletRequest httpRequest) {
adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId());
return ApiResponse.success(service.progressLight(request.getTaskIds(), request.getUserId()));
}
""";
for (String bad : List.of(unboundInline, noFilterAtAll, boundButDiscarded)) {
assertThat(isBoundToSession(bad)).as("坏形状必须判不通过:" + bad.trim()).isFalse();
}
String goodInline = """
@PostMapping("/tasks/progress/batch")
public ApiResponse<Void> x(@RequestBody R request, HttpServletRequest httpRequest) {
return ApiResponse.success(service.progressBatch(progressOwnershipSupport
.filterOwnedTaskIds(request.getTaskIds(),
adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()))));
}
""";
assertThat(isBoundToSession(goodInline)).as("内联写法(族内 22 支的形状)").isTrue();
String goodWriteBack = """
@PostMapping("/tasks/progress/light")
public ApiResponse<Void> x(@RequestBody R request, HttpServletRequest httpRequest) {
request.setUserId(adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()));
return ApiResponse.success(service.progressLight(request.getUserId(), request.getTaskIds()));
}
""";
assertThat(isBoundToSession(goodWriteBack)).as("写回 DTO 再取用的写法(Publish 那两支的形状)").isTrue();
// 注释里提一句出口名,不许把判据喂饱(本类扫的是剥完注释的源码)
assertThat(isBoundToSession(SourceScan.withoutComments("""
@PostMapping("/tasks/progress/light")
public ApiResponse<Void> x(@RequestBody R request) {
// adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()) 早就接上了
return ApiResponse.success(service.progressLight(request.getTaskIds(), request.getUserId()));
}
"""))).as("注释不得算作已接线").isFalse();
}
/**
* 放宽只剩一条通路:null=已认证的管理身份,不是匿名。
*
* <p>{@code filterOwnedTaskIds} 见 null 原样返回、{@code TaskProgressLightAssembler} 见 null 不加
* 条件,这两处<b>故意</b>留给管理角色(后台按客户看任务是本职)。收口之后它们只可能由
* {@link AdminAuthSupport#requireOwnershipUserId} 交出 null(出口对管理角色返回原参数),
* 匿名请求在出口就 401。这里钉住这条通路的两个方向:null 不过滤、非 null 必须过滤掉别人的 id。</p>
*/
@Test
void nullMeansAuthenticatedAdminWhileAnyUserIdFilters() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
when(mapper.selectList(any())).thenReturn(List.of(task(3938L)));
TaskProgressOwnershipSupport support = new TaskProgressOwnershipSupport(mapper);
// null(管理身份):原样返回,且不发 SQL —— 否则后台每一页轮询都多打一次任务表
List<Long> all = List.of(3938L, 3939L);
assertThat(support.filterOwnedTaskIds(all, null)).isEqualTo(all);
verify(mapper, never()).selectList(any());
// 非 null:只有真属于它的 id 留下,别人的被剔掉
assertThat(support.filterOwnedTaskIds(List.of(3938L, 3939L), 7L)).containsExactly(3938L);
// 光看返回值抓不到「打了 SQL 但没带归属条件」——mock 的 selectList 是无条件回桩的。
// 所以必须把 wrapper 抓出来,钉住 user_id 这一列和会话推出来的那个值。
ArgumentCaptor<LambdaQueryWrapper<FileTaskEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(mapper).selectList(captor.capture());
captor.getValue().getSqlSegment(); // MP 惯例:先求值一次才铺出参数
assertThat(captor.getValue().getSqlSegment()).contains("user_id");
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(7L);
}
// ---- 判据 ----
/** 一支 handler 的归属是不是从会话来的(两种合规写法见 {@link #theBindingPredicateIsNotVacuous})。 */
private static boolean isBoundToSession(String handlerSegment) {
if (!handlerSegment.contains("HttpServletRequest httpRequest")) {
return false;
}
int outlet = count(handlerSegment, OUTLET);
int uses = count(handlerSegment, BODY_USER_ID);
if (outlet == 0) {
return false;
}
if (uses == outlet) {
return true; // 内联:每一次取 body id 都在出口实参里
}
return handlerSegment.contains(WRITE_BACK) && uses == 2 * outlet; // 写回 DTO 后复用
}
private static int countHandlers(String mapping) {
int n = 0;
for (String rel : FAMILY_CONTROLLERS) {
n += handlerSegments(SourceScan.withoutComments(read(mainRoot().resolve(rel))), mapping).size();
}
return n;
}
/** 从 {@code @PostMapping("<mapping>")} 起,按大括号配平取到该方法收尾(含签名,签名里有 httpRequest 参数)。 */
private static List<String> handlerSegments(String source, String mapping) {
String anchor = "@PostMapping(\"" + mapping + "\")";
List<String> out = new ArrayList<>();
for (int i = source.indexOf(anchor); i >= 0; i = source.indexOf(anchor, i + anchor.length())) {
int body = source.indexOf('{', i);
int end = matchBraces(source, body);
if (end < 0) {
continue;
}
out.add(source.substring(i, end + 1));
}
return out;
}
private static int matchBraces(String source, int open) {
if (open < 0) {
return -1;
}
int depth = 0;
for (int i = open; i < source.length(); i++) {
char c = source.charAt(i);
if (c == '{') {
depth++;
} else if (c == '}' && --depth == 0) {
return i;
}
}
return -1;
}
private static FileTaskEntity task(Long id) {
FileTaskEntity entity = new FileTaskEntity();
entity.setId(id);
return entity;
}
private static int count(String text, String needle) {
int n = 0;
for (int i = text.indexOf(needle); i >= 0; i = text.indexOf(needle, i + needle.length())) {
n++;
}
return n;
}
private static Path mainRoot() {
Path here = Path.of("").toAbsolutePath();
Path direct = here.resolve("src/main/java/com/nanri/aiimage");
if (Files.isDirectory(direct)) {
return direct;
}
Path nested = here.resolve("backend-java").resolve("src/main/java/com/nanri/aiimage");
if (Files.isDirectory(nested)) {
return nested;
}
throw new IllegalStateException("无法定位 backend-java 源码目录(cwd=" + here + ")");
}
private static String read(Path file) {
if (!Files.isRegularFile(file)) {
fail("找不到 " + file + " —— 本族有控制器被改名/挪走了,护栏要红在这里而不是跳过");
}
try {
return Files.readString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("读取失败: " + file, e);
}
}
}
@@ -0,0 +1,298 @@
package com.nanri.aiimage.common.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import com.nanri.aiimage.testutil.SourceScan;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
/**
* 「操作者身份不许由请求参数说了算」的全族绊线(2026-10-07 架构三期,缺陷 (d)/(g) 收口)。
*
* <p>收口前的形状:模块控制器里 <b>190 支</b> handler 把 {@code user_id}(query 参数、请求体字段,
* 或"控制器把带 userId 的 DTO 整个交给 service")直接当身份交给下游做归属比对。请求参数不是身份,
* 它有两种坏用法,而且都不报错:</p>
* <ol>
* <li>带<b>别人的</b> user_id ⇒ 归属比对拿它去匹配别人的行,越权读/越权改(删除历史行、
* 停止别人的循环跟价、清空别人的备选店铺);</li>
* <li>不带 ⇒ 归属条件多半写成 {@code userId != null && ...},匿名请求即"不加过滤"。</li>
* </ol>
*
* <p>现在的口径:这类 handler 一律先把请求里的 id 交给 {@code resolveOwnershipUserId} /
* {@code requireOwnershipUserId}。前者对<b>已认证</b>调用方做校验(缺省用会话 id、不一致 403、
* 管理角色豁免),对解析不出身份的调用方原样透传并计入 {@code [ownership-anonymous]};
* fail-closed 的 require 只用在已取证"没有匿名调用方"的进度轮询族(见
* {@link ProgressQueryOwnershipOutletTest})——桌面执行器 4.0.44 出厂版还不带登录 JWT,
* 把写类端点一起翻成 require 会把执行器整批打成 401,所以这一步走的是日志归零再翻。</p>
*
* <p>扫描一律打在 {@link SourceScan#withoutComments} 剥掉注释的源码上,且判据是"必须存在/等于 N"
* 那一形:不剥注释的话,谁在 {@code @Operation} 描述或行尾注释里提一句出口名,就能把护栏喂饱。
* 分母(写 126 / 读 63,另有 1 支在册豁免)同样钉死,扫描器坏掉与"真的没人漏接"不会一起恒绿。
* 这 190 支里有 39 支是 DTO 形态——只 grep 文本上的 {@code getUserId()} 会把它们整批看漏,
* 所以 {@link #dtoTypesWithUserId()} 必须先建一遍"哪些请求类声明了 userId 字段"的索引。</p>
*/
class RequestSuppliedIdentityOutletTest {
/** 一支 handler 只要从请求里取身份,就必须落到这三个出口之一(第三个是各控制器的本人 id 取法)。 */
private static final List<String> OUTLETS = List.of(
"resolveOwnershipUserId(httpRequest",
"requireOwnershipUserId(httpRequest",
"currentUserId(httpRequest");
private static final Pattern MAPPING =
Pattern.compile("@(Post|Put|Delete|Patch|Get|RequestMapping)Mapping(?:\\(([^)]*)\\))?");
private static final Pattern PARAM_UID = Pattern.compile(
"@RequestParam\\(\\s*(?:(?:value|name)\\s*=\\s*)?\"(?:user_id|userId)\"[^)]*\\)"
+ "\\s+(?:@[^,)]+\\s+)*Long\\s+\\w+");
private static final List<String> WRITE_VERBS = List.of("Post", "Put", "Delete", "Patch");
/** Spring 的 @RequestBody(前面是 @,不含 swagger 那个纯文档注解)里的 DTO 类型名。 */
private static final Pattern BODY_DTO =
Pattern.compile("@RequestBody\\s+(?:@[^,)]+\\s+)*([A-Z]\\w*)\\s+\\w+");
/** 自带 userId 字段的请求 DTO:控制器只是把它转交下去,真正读 userId 的是 service。 */
private static final Set<String> DTO_TYPES_WITH_USER_ID = dtoTypesWithUserId();
/**
* 登记在册的豁免:命中 {@code X-Internal-Token} 才可达的服务间查询(方法体内 fail-closed 401),
* 参数是"被查询的用户"而不是"操作者",套归属出口反而会把 Flask 后台的查询打成空值。
*
* <p>这一条必须<b>同时</b>满足:出现在豁免表里、且现在仍然没有接出口。哪天有人把它接上了,
* {@link #allowlistEntriesAreStillNeeded()} 会红,要求把这条从这里删掉——豁免表只许变小。</p>
*/
private static final List<String> ALLOWED_WITHOUT_OUTLET = List.of(
"modules/usersecret/controller/InternalUserProxyController.java Get /user-proxy");
@Test
void everyHandlerReadingARequestSuppliedUserIdRoutesItThroughAnOutlet() {
List<String> violations = new ArrayList<>();
Scan scan = scanAll();
for (String entry : scan.unbound()) {
if (!ALLOWED_WITHOUT_OUTLET.contains(entry)) {
violations.add(entry);
}
}
assertThat(violations)
.as("身份仍取自请求参数(没走会话出口)的 handler —— 带别人的 user_id 就能越权读写")
.isEmpty();
}
@Test
void theScanCoversBothVerbsWithPinnedDenominators() {
Scan scan = scanAll();
// 28 支进度轮询走 require,其余写类/读类走 resolve;两边都算"已接出口"。
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(126);
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(63);
assertThat(scan.unbound()).as("取请求身份但未接出口的 handler:只剩豁免那一条")
.containsExactlyElementsOf(ALLOWED_WITHOUT_OUTLET);
}
/** 豁免不是永久产权:条目自己失效(端点已接上出口或已下线)就必须从表里删掉。 */
@Test
void allowlistEntriesAreStillNeeded() {
Scan scan = scanAll();
assertThat(scan.unbound())
.as("豁免表里的每一条必须仍然处于未接出口状态")
.containsExactlyElementsOf(ALLOWED_WITHOUT_OUTLET);
}
/**
* 判据本身要能红:没接出口的必须被判出来,接上的、以及只在注释里提一句的都不许算数。
*
* <p>缺这一支,{@link #scanAll} 的"已接出口"写成恒真也会一路绿。</p>
*/
@Test
void theOutletDetectionIsNotVacuous() {
String unbound = """
@GetMapping("/dashboard")
public ApiResponse<Void> dashboard(@RequestParam("user_id") Long userId) {
return ApiResponse.success(service.dashboard(userId));
}
""";
assertThat(isBound(unbound)).as("裸转发请求里的 user_id 必须判为未接出口").isFalse();
assertThat(readsRequestIdentity(unbound)).isTrue();
String boundResolve = """
@GetMapping("/dashboard")
public ApiResponse<Void> dashboard(@RequestParam("user_id") Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
return ApiResponse.success(service.dashboard(userId));
}
""";
assertThat(isBound(boundResolve)).as("resolve 写法(写类/读类收口后的形状)").isTrue();
String boundRequire = """
@PostMapping("/tasks/progress/light")
public ApiResponse<Void> light(@RequestBody R request, HttpServletRequest httpRequest) {
return ApiResponse.success(service.progressLight(request.getTaskIds(),
adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId())));
}
""";
assertThat(isBound(boundRequire)).as("require 写法(进度轮询族)").isTrue();
// 注释里把出口名写全,也不许把判据喂饱——这正是本类扫剥注释源码的理由
String commentOnly = SourceScan.withoutComments("""
@GetMapping("/history")
public ApiResponse<Void> history(@RequestParam("user_id") Long userId) {
// adminAuthSupport.resolveOwnershipUserId(httpRequest, userId) 已经接好了
return ApiResponse.success(service.history(userId));
}
""");
assertThat(isBound(commentOnly)).as("注释不得算作已接出口").isFalse();
assertThat(readsRequestIdentity(commentOnly)).as("但请求里的身份仍要被扫出来,否则漏网端点隐身").isTrue();
}
/** DTO 形态:控制器不显式取 getUserId(),而是把 request 整个交给 service,由 service 读里面的 userId。 */
@Test
void dtoCarryingHandlersAreCountedToo() {
String dtoHandler = """
@PostMapping("/candidates")
public ApiResponse<Void> add(@RequestBody ProductRiskCandidateAddRequest request) {
withdrawResolveService.addCandidate(request);
}
""";
// 文本上没有 getUserId(),靠的是「DTO 里声明了 userId 字段」这一层;
// 识别不出来的话,新建的 DTO 型端点会整批隐身在本护栏之外
assertThat(readsRequestIdentity(dtoHandler))
.as("ProductRiskCandidateAddRequest 带 userId 字段,改造前就该被扫出来")
.isTrue();
String boundDto = """
@PostMapping("/candidates")
public ApiResponse<Void> add(@RequestBody ProductRiskCandidateAddRequest request,
HttpServletRequest httpRequest) {
request.setUserId(adminAuthSupport.resolveOwnershipUserId(httpRequest, request.getUserId()));
withdrawResolveService.addCandidate(request);
}
""";
assertThat(readsRequestIdentity(boundDto)).isTrue();
assertThat(isBound(boundDto)).isTrue();
}
// ---- 扫描 ----
private record Scan(List<String> unbound, int boundWrite, int boundRead) {
}
private static Scan scanAll() {
List<String> unbound = new ArrayList<>();
int boundWrite = 0;
int boundRead = 0;
Path controllers = mainRoot().resolve("modules");
List<Path> files = new ArrayList<>();
try (Stream<Path> stream = Files.walk(controllers)) {
stream.filter(p -> p.getFileName().toString().endsWith("Controller.java")).forEach(files::add);
} catch (IOException e) {
throw new IllegalStateException("遍历模块控制器失败", e);
}
assertThat(files).as("模块控制器数量少于 20 说明扫描根走错了").hasSizeGreaterThan(20);
for (Path file : files) {
String source = SourceScan.withoutComments(read(file));
String rel = mainRoot().relativize(file).toString().replace('\\', '/');
Matcher current = MAPPING.matcher(source);
List<int[]> anchors = new ArrayList<>();
List<String> verbs = new ArrayList<>();
List<String> paths = new ArrayList<>();
while (current.find()) {
if ("RequestMapping".equals(current.group(1))) {
continue; // 类级前缀不是 handler
}
anchors.add(new int[]{current.start(), current.end()});
verbs.add(current.group(1));
Matcher vm = Pattern.compile("\"([^\"]+)\"").matcher(current.group(2) == null ? "" : current.group(2));
paths.add(vm.find() ? vm.group(1) : "");
}
for (int i = 0; i < anchors.size(); i++) {
int from = anchors.get(i)[0];
int to = i + 1 < anchors.size() ? anchors.get(i + 1)[0] : source.length();
String region = source.substring(from, to);
if (!readsRequestIdentity(region)) {
continue;
}
if (isBound(region)) {
if (WRITE_VERBS.contains(verbs.get(i))) {
boundWrite++;
} else {
boundRead++;
}
} else {
unbound.add(rel + " " + verbs.get(i) + " " + paths.get(i));
}
}
}
return new Scan(unbound, boundWrite, boundRead);
}
private static boolean readsRequestIdentity(String region) {
if (PARAM_UID.matcher(region).find() || region.contains(".getUserId()")) {
return true;
}
// 只看文本上的 getUserId() 会漏掉「控制器把 DTO 整个交给 service」那一形——
// 新建端点正是这个形状,漏了它本类就成了「只保护已收口的」。
Matcher dto = BODY_DTO.matcher(region);
while (dto.find()) {
if (DTO_TYPES_WITH_USER_ID.contains(dto.group(1))) {
return true;
}
}
return false;
}
private static Set<String> dtoTypesWithUserId() {
List<Path> files = new ArrayList<>();
try (Stream<Path> stream = Files.walk(mainRoot())) {
stream.filter(p -> p.getFileName().toString().endsWith(".java")).forEach(files::add);
} catch (IOException e) {
throw new IllegalStateException("遍历源码求 DTO 索引失败", e);
}
Set<String> out = new java.util.HashSet<>();
Pattern field = Pattern.compile("private\\s+Long\\s+userId\\b");
for (Path file : files) {
try {
String text = SourceScan.withoutComments(Files.readString(file, StandardCharsets.UTF_8));
if (field.matcher(text).find()) {
String name = file.getFileName().toString();
out.add(name.substring(0, name.length() - ".java".length()));
}
} catch (IOException e) {
throw new IllegalStateException("读取失败: " + file, e);
}
}
assertThat(out).as("带 userId 的请求/实体类索引不应为空(空=扫描根走错了)").isNotEmpty();
return out;
}
private static boolean isBound(String region) {
return OUTLETS.stream().anyMatch(region::contains);
}
private static Path mainRoot() {
Path here = Path.of("").toAbsolutePath();
Path direct = here.resolve("src/main/java/com/nanri/aiimage");
if (Files.isDirectory(direct)) {
return direct;
}
return here.resolve("backend-java").resolve("src/main/java/com/nanri/aiimage");
}
private static String read(Path file) {
if (!Files.isRegularFile(file)) {
fail("找不到 " + file + " —— 扫描根不对,护栏的分母会静默变成 0");
}
try {
return Files.readString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("读取失败: " + file, e);
}
}
}