feat(公司范围): DataReadScope 唯一读范围出口 + G2 扫 company_id 端点

- ReadScope/DataReadScope 落在 common/service:超管不选公司=不筛、选公司=成员集替换、
  选不存在公司=空页(不 403 不全量);非超管永远锁本公司且与分组可见集求交(只能收窄),
  传别家得空结果,没公司归属则炸
- G2 护栏逐文件扫"含 company_id 的 controller 必须走 readScope( 且显式 name=",
  带取样非空自检;白名单点名只放先于本计划存在的 AdminUserController,
  且只豁免 readScope 那一条、不豁免取样与显式 name=
This commit is contained in:
2026-10-05 03:03:06 +08:00
parent fb407bdaee
commit a5a9df650b
4 changed files with 273 additions and 0 deletions
@@ -0,0 +1,84 @@
package com.nanri.aiimage.common.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
/**
* G2(spec §10):每个收 company_id 的 controller 必须走 readScope。
* 漏一处 = 那一页的 tab 是假的,而且不报错。
*
* <p>扫描对象是 controller 层,与计划的定案一致:有的页(如 {@code ShopManageService.page})手上只有
* {@code operatorId} + 一个布尔、没有操作者实体,所以 {@code readScope(AdminUserEntity, Long)} 只能由
* controller 调,再把算好的成员集当参数传进去(docs/plans/19-company-tab.md「Task 11 已确认现状」第 2 条)。
* 因此"controller 里出现 readScope("就是这一页接了唯一出口的证据。</p>
*/
class CompanyIdParamGoesThroughReadScopeTest {
/**
* 点名白名单(精确到文件名,不许通配/前缀)。
*
* <p>只放一条:{@code AdminUserController} 的 {@code GET /api/admin/users?company_id=} 是<b>先于本计划
* 存在、已在生产</b>的那"第二个 if"——用户管理页不在本计划 8 个 tab 页里
* ({@code admin-frontend-vue/src/config/company-scope.ts} 的 {@code COMPANY_SCOPED_PAGES} 无
* {@code admin_users}),而它的实现({@code AdminUserService} 里"筛别家 = 空页、故意不报错也不越权")
* 正是全局约束 2 点名的参考形状。本批次不迁它:迁了等于把 140 值的 {@code id IN(...)} 换回
* {@code company_id =} 直查,性能方向是负的;已另记为批次 1 之后独立一笔。</p>
*
* <p>豁免只作用于第一条断言(必须含 {@code readScope(})。<b>不作用于取样</b>——今天非白名单的
* 含 company_id controller 恰好 0 支,把白名单文件从取样列表里剔掉再自检非空,那条自检当场就红
* (全局约束 15 要的正是这条自检,不能绕过)。也<b>不豁免</b>第二条:白名单内的文件仍然必须显式
* {@code @RequestParam(name = "company_id")},驼峰参数名静默失效那一类错不能被白名单盖住。</p>
*/
private static final Set<String> READ_SCOPE_ALLOWLIST = Set.of("AdminUserController.java");
@Test
void everyCompanyIdEndpointGoesThroughReadScope() throws IOException {
assertThat(READ_SCOPE_ALLOWLIST)
.as("白名单只允许 AdminUserController 一条:多一条 = 有人新开了一个不走唯一出口的 if")
.hasSize(1);
Path root = Path.of("src/main/java");
if (!Files.isDirectory(root)) fail("找不到 " + root + " —— 用例依赖以 backend-java 为工作目录");
List<Path> controllers;
try (Stream<Path> walk = Files.walk(root)) {
controllers = walk.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith("Controller.java"))
.filter(p -> read(p).contains("company_id"))
.collect(Collectors.toList());
}
assertThat(controllers)
.as("取样集非空自检:一条都没扫到说明扫描失效,护栏等于没写")
.isNotEmpty();
for (Path controller : controllers) {
String text = read(controller);
if (!READ_SCOPE_ALLOWLIST.contains(controller.getFileName().toString())) {
assertThat(text)
.as(controller + " 收了 company_id 却没走唯一出口")
.contains("readScope(");
}
// 第二条:参数必须**显式**写 name = "company_id"。
// 本仓库多数 controller 靠"方法参数名即请求名"绑定(ShopManageController:66-71 的 pageSize/groupId/shopName 就是),
// 照那个习惯写成 `Long companyId` 时 Spring 收的是 companyId=,而前端发的是 company_id=
// ⇒ 参数永远 null、接口 200、tab 切了不筛。这是全批次唯一"错了也不红"的形状,所以钉在扫描里。
assertThat(text)
.as(controller + " 的 company_id 没写显式 name=,会和驼峰参数名混成两种拼写")
.contains("name = \"company_id\"");
}
}
private static String read(Path path) {
try {
return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("读不到 " + path, e);
}
}
}
@@ -0,0 +1,99 @@
package com.nanri.aiimage.common.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/** 公司 tab 的唯一范围出口(spec §7)。五种组合必须逐个钉死——它们决定线上会不会越权。 */
class DataReadScopeTest {
private CompanyScopeSupport companyScope;
private AdminAuthSupport adminAuthSupport;
private UserDataScopeSupport userDataScope;
private DataReadScope dataReadScope;
private static AdminUserEntity user(long id, String role, Long companyId) {
AdminUserEntity u = new AdminUserEntity();
u.setId(id); u.setRole(role); u.setCompanyId(companyId);
return u;
}
@BeforeEach
void setUp() {
companyScope = mock(CompanyScopeSupport.class);
adminAuthSupport = mock(AdminAuthSupport.class);
userDataScope = mock(UserDataScopeSupport.class);
when(adminAuthSupport.currentRole(any())).thenAnswer(inv -> ((AdminUserEntity) inv.getArgument(0)).getRole());
dataReadScope = new DataReadScope(companyScope, adminAuthSupport, userDataScope);
}
@Test
@DisplayName("超管不选公司 = 今天的行为:完全不筛")
void superAdminWithoutCompanyStaysUnfiltered() {
ReadScope scope = dataReadScope.readScope(user(1L, "super_admin", 1L), null);
assertThat(scope.isUnfiltered()).isTrue();
assertThat(scope.userIdsOr(List.of(9L))).containsExactly(9L);
assertThat(scope.userIdsOr(null)).isNull();
}
@Test
@DisplayName("超管选公司 = 该公司成员替换掉「不筛」")
void superAdminWithCompanyNarrowsToMembers() {
when(companyScope.memberUserIds(2L)).thenReturn(List.of(11L, 12L));
ReadScope scope = dataReadScope.readScope(user(1L, "super_admin", 1L), 2L);
assertThat(scope.userIdsOr(null)).containsExactlyInAnyOrder(11L, 12L);
}
@Test
@DisplayName("超管选不存在的公司 = 空集 → 空页,不是 403、也不是全量")
void superAdminWithUnknownCompanyYieldsEmpty() {
when(companyScope.memberUserIds(99L)).thenReturn(List.of());
ReadScope scope = dataReadScope.readScope(user(1L, "super_admin", 1L), 99L);
assertThat(scope.isUnfiltered()).isFalse();
assertThat(scope.userIdsOr(null)).isEmpty();
assertThat(scope.userIdsOr(List.of(9L))).isEmpty();
}
@Test
@DisplayName("非超管永远锁本公司,不传也一样")
void adminIsAlwaysPinnedToOwnCompany() {
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L);
when(companyScope.memberUserIds(2L)).thenReturn(List.of(21L, 22L));
when(userDataScope.resolveVisibleUserIds(5L)).thenReturn(List.of(21L, 99L));
ReadScope scope = dataReadScope.readScope(user(5L, "admin", 2L), null);
// 与既有的分组可见集**求交**,不是替换:非超管的组长范围不能被公司 tab 放大。
assertThat(scope.userIdsOr(userDataScope.resolveVisibleUserIds(5L))).containsExactly(21L);
}
@Test
@DisplayName("非超管传别家 = 空结果,不报错也不越权(照 AdminUserService:75-81)")
void adminPassingForeignCompanyGetsEmptyNot403() {
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L);
ReadScope scope = dataReadScope.readScope(user(5L, "admin", 2L), 7L);
assertThat(scope.isUnfiltered()).isFalse();
assertThat(scope.userIds()).isEmpty();
}
@Test
@DisplayName("非超管没有公司归属时炸,不退化成「不筛」")
void adminWithoutCompanyFailsFast() {
when(companyScope.requireCompanyId(any(AdminUserEntity.class)))
.thenThrow(new com.nanri.aiimage.common.exception.BusinessException(403, "当前账号没有所属公司"));
// brief 里这行外面还套了一层 assertThat(...):assertThat 拿到的是 AssertJ 的断言对象本身
// 而不是异常,恒定红("but was instance of: org.assertj.core.api.ThrowableAssert")。
// assertThatThrownBy 已返回可链式断言的对象,直接用即可——断言方向与消息不变。
org.assertj.core.api.Assertions.assertThatThrownBy(
() -> dataReadScope.readScope(user(5L, "admin", null), null))
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class);
}
}