diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/service/DataReadScope.java b/backend-java/src/main/java/com/nanri/aiimage/common/service/DataReadScope.java index 5738605a2..23e13c791 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/service/DataReadScope.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/service/DataReadScope.java @@ -61,4 +61,36 @@ public class DataReadScope { } return requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null; } + + /** + * 第三道门:归属物化成 {@code company_id} 列、且可见集不靠账号/分组的表(商品类目)。 + * + *

与 {@link #readCompanyId} 只差非超管那一支。差别不是省事,是那张表没有可以保护的东西: + * 品牌库的"非超管不筛"靠的是账号/分组谓词兜住可见集,而 {@code biz_product_category} + * 连账号列都没有(V147 才加的 {@code company_id})。返回 null 在这里等于把整棵树交给每一家—— + * 2026-10-06 逐节点复验实测:公司 2 的 admin 读该页得 412 行,其中 394 行是公司 1 的自建类目。

+ * + *

非超管钉在本公司而不是"带别家就返回空":类目树里没有"空树"这个可用视图—— + * 内置节点(哨兵 0)在任何公司视图里都必须在,否则那一家装不上任何自建子级。 + * 请求里带什么都不算,与 {@code readScope} 非超管分支同一口径(tab 不是安全边界)。

+ */ + public Long readCompanyIdOrOwn(AdminUserEntity operator, Long requestedCompanyId) { + if (SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator))) { + return requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null; + } + return companyScope.requireCompanyId(operator); + } + + /** + * 写侧的行级归属闸门要的值:{@code null} = 平台超管不限,其余账号一律是自己那一家。 + * + *

读侧收窄而写侧不收窄,等于"藏起来的行仍然能删"——那是静默删除,不是隔离。 + * 返回值直接交给 service 与行自己的 {@code company_id} 比(不是与 tab 比: + * 内置行归哨兵 0,任何公司账号都不该改得动它)。

+ */ + public Long writeCompanyId(AdminUserEntity operator) { + return SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator)) + ? null + : companyScope.requireCompanyId(operator); + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryController.java index a3ab671a7..ae068b4c0 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryController.java @@ -50,7 +50,7 @@ public class ProductCategoryController { @RequestParam(value = "keyword", required = false) String keyword, @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); - Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId); + Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId); return ApiResponse.success(productCategoryService.list(keyword, scopedCompanyId)); } @@ -63,7 +63,7 @@ public class ProductCategoryController { @RequestParam(value = "page_size", defaultValue = "20") Long pageSize, @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); - Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId); + Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId); return ApiResponse.success(productCategoryService.children(parentId, page, pageSize, scopedCompanyId)); } @@ -76,7 +76,7 @@ public class ProductCategoryController { @RequestParam(value = "page_size", defaultValue = "20") Long pageSize, @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); - Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId); + Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId); return ApiResponse.success(productCategoryService.search(keyword, page, pageSize, scopedCompanyId)); } @@ -87,7 +87,7 @@ public class ProductCategoryController { @RequestParam(value = "keyword", required = false) String keyword, @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); - Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId); + Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId); byte[] bytes = productCategoryService.export(keyword, scopedCompanyId); String filename = "product-categories-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx"; return ResponseEntity.ok() @@ -114,8 +114,10 @@ public class ProductCategoryController { HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody ProductCategorySaveRequest body) { - adminAuthSupport.requireAdminOrInternal(request); - return ApiResponse.success("保存成功", productCategoryService.update(id, body)); + // 写侧闸门与读侧同源:读已经收窄到本公司,写不收窄就是"藏起来的行照样能删"。 + AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); + return ApiResponse.success("保存成功", + productCategoryService.update(id, body, dataReadScope.writeCompanyId(operator))); } @DeleteMapping("/product-category/{id}") @@ -123,8 +125,8 @@ public class ProductCategoryController { public ApiResponse delete( HttpServletRequest request, @PathVariable Long id) { - adminAuthSupport.requireAdminOrInternal(request); - productCategoryService.delete(id); + AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); + productCategoryService.delete(id, dataReadScope.writeCompanyId(operator)); return ApiResponse.success("删除成功", null); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryService.java index 4de97368c..9ff53cb2a 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryService.java @@ -148,12 +148,18 @@ public class ProductCategoryService { return findItem(entity.getId()); } + /** + * @param writableCompanyId 行归属闸门({@code DataReadScope.writeCompanyId} 给): + * {@code null} = 平台超管不限,否则只能动这一家自己的行。 + * 读侧收窄而写侧不收窄="藏起来的行仍然能删",那是静默删除不是隔离。 + */ @Transactional - public ProductCategoryItemVo update(Long id, ProductCategorySaveRequest request) { + public ProductCategoryItemVo update(Long id, ProductCategorySaveRequest request, Long writableCompanyId) { ProductCategoryEntity entity = getById(id); + assertRowWritable(entity, writableCompanyId); String name = normalizeRequired(request.getName(), "类目名称不能为空"); Long parentId = normalizeParentId(request.getParentId()); - // 改行时" Acting 公司"取行自己的归属,不取 tab:内置行归 0、自建行归那一家, + // 改行时"生效公司"取行自己的归属,不取 tab:内置行归 0、自建行归那一家, // 换父级时不能把行挪到可见集外的节点下面(那会让它从原本看得见它的 tab 里消失)。 Long companyId = entity.getCompanyId(); ensureParentVisible(parentId, id, companyId); @@ -168,8 +174,9 @@ public class ProductCategoryService { } @Transactional - public void delete(Long id) { + public void delete(Long id, Long writableCompanyId) { ProductCategoryEntity entity = getById(id); + assertRowWritable(entity, writableCompanyId); Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper() .eq(ProductCategoryEntity::getParentId, entity.getId())); if (childCount != null && childCount > 0) { @@ -178,6 +185,22 @@ public class ProductCategoryService { productCategoryMapper.deleteById(entity.getId()); } + /** + * 行归属闸门。走 {@code assertSameCompany} 而不是在这里比一次:它对本仓所有"按公司写"的闸门 + * 是唯一一份判定,两处各写就会有一处先漂。 + * + *

内置节点(哨兵 0)在这一支里必然被拒——{@code 0 != 任何真实公司 id}, + * 而"公司账号能改/删平台内置类目"正是这一页最容易出事的一刀:改了它, + * 所有公司的类目树与货源归类的候选表同一天跟着变。

+ */ + private void assertRowWritable(ProductCategoryEntity row, Long writableCompanyId) { + if (writableCompanyId == null) { + return; + } + companyScopeSupport.assertSameCompany(writableCompanyId, row.getCompanyId(), + "无权修改该类目:内置类目或别家公司的类目不在本公司的写范围内"); + } + private ProductCategoryItemVo findItem(Long id) { ProductCategoryEntity entity = getById(id); Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper() diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/service/CompanyIdParamGoesThroughReadScopeTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/service/CompanyIdParamGoesThroughReadScopeTest.java index 270765a77..31111b99a 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/common/service/CompanyIdParamGoesThroughReadScopeTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/common/service/CompanyIdParamGoesThroughReadScopeTest.java @@ -112,7 +112,7 @@ import org.junit.jupiter.api.Test; * D 的代价与射程一并交代:非 {@code Long} 型公司参数取不到绑定名,判红并报形状;而"handler 之外的私有 * 收口方法里把公司参数硬写成 {@code null}"这一族 D 看不见——块边界止于该 handler 自己的闭括号 * (第 7 条),{@code AdminImageVideoTaskController.scopeOf} 正是它,那一处是故意传 null 的。 - *
  • 两条正门,一套判据(批次 2/3 新增)。{@code DataReadScope} 现在有两个出口: + *
  • 几条正门,一套判据(批次 2/3 新增;10-06 复验后加第三道)。{@code DataReadScope} 现在有三个出口: * {@code readScope(} 按账号集合给范围(去重库、查询 ASIN、最低价 ASIN、历史、视频), * {@code readCompanyId(} 给"归属已物化成 {@code company_id} 列"的表(品牌库、商品类目—— * 那两张表的 {@code uploader_user_id} 在生产是 0 行非空,按账号筛等于把全部历史从每个公司 tab 里 @@ -214,13 +214,25 @@ class CompanyIdParamGoesThroughReadScopeTest { * 商品类目 {@code biz_product_category} 更是连账号列都没有(V147 才加的 company_id)。 * 这两页的归属是物化列,正门必须按列给。

    * - *

    两条正门是并列的白名单而不是新的自由口径:判据 A/C/D 与 {@code readScope} 逐字共用, - * 只是把"出现过 readScope("换成"出现过两条正门之一"," companyId 进了 readScope 的实参表"换成 - * "进了两条正门之一的实参表"。第三条正门(比如页里自己写 {@code if (companyId != null) ...}) - * 依然红。

    + *

    几条正门是并列的白名单而不是新的自由口径:判据 A/C/D 与 {@code readScope} 逐字共用, + * 只是把"出现过 readScope("换成"出现过任一正门"," companyId 进了 readScope 的实参表"换成 + * "进了任一正门的实参表"。页里自己写 {@code if (companyId != null) ...} 那一族 + * 依然红——名单只加在 {@code DataReadScope} 上,加不在页上。

    */ private static final String READ_COMPANY_ID_CALL = "readCompanyId("; - private static final List SCOPE_DOORS = List.of(READ_SCOPE_CALL, READ_COMPANY_ID_CALL); + /** + * 第三道正门(10-06 复验后补):{@code readCompanyIdOrOwn}。 + * + *

    它补的是 {@code readCompanyId} 在非超管那一支的洞:品牌库的"非超管不筛"靠账号/分组谓词兜底, + * 商品类目既没有账号列也没有分组可见集,返回 null 就是"每一家都读到整棵树"—— + * 2026-10-06 逐节点复验实测公司 2 的 admin 在该页读到 412 行(含公司 1 的 394 个自建类目)。

    + * + *

    入名单的前提是它仍然只是 {@code DataReadScope} 上的一个方法,不是页里自己写的 if: + * 第三条门若开在 controller 里,这一页的判据就没人看守了。

    + */ + private static final String READ_OWN_COMPANY_ID_CALL = "readCompanyIdOrOwn("; + private static final List SCOPE_DOORS = + List.of(READ_SCOPE_CALL, READ_COMPANY_ID_CALL, READ_OWN_COMPANY_ID_CALL); private static final String EXPLICIT_PARAM_NAME = "name = \"company_id\""; private static final String SNAKE_PARAM = "company_id"; private static final String CAMEL_PARAM = "companyId"; @@ -275,7 +287,8 @@ class CompanyIdParamGoesThroughReadScopeTest { * 直接从 {@code Set} 拼会随哈希顺序变 ⇒ 消息里的名字顺序不稳定,而自检断言咬的是整串字面量, * 那就等于一条会自己漂红的用例。 */ - private static final List SCOPE_CALLEE_NAMES = List.of("readScope", "resolveScope", "readCompanyId"); + private static final List SCOPE_CALLEE_NAMES = + List.of("readScope", "resolveScope", "readCompanyId", "readCompanyIdOrOwn"); private static final Set SCOPE_CALLEES = Set.copyOf(SCOPE_CALLEE_NAMES); private static final String SCOPE_CALLEE_LABEL = String.join("/", SCOPE_CALLEE_NAMES); @@ -478,6 +491,39 @@ class CompanyIdParamGoesThroughReadScopeTest { } """; + /** + * 第三道正门({@code readCompanyIdOrOwn})的正探针:形状抄现网 + * {@code ProductCategoryController.list} —— 门给什么是什么,controller 不自己补。 + * C 的两步与 D 都必须在这一形上判绿,否则类目页红在护栏上而不是红在缺陷上。 + */ + private static final String READ_OWN_COMPANY_ID_CAUGHT_PROBE = """ + @GetMapping("/probe") + public String thirdDoor(@RequestParam(name = "company_id", required = false) Long companyId) { + AdminUserEntity user = operator.user(); + Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId); + return String.valueOf(productCategoryService.list(null, scopedCompanyId)); + } + """; + + /** 第三道正门的裸语句探针(C 第 ① 步在该门上的"能红"证据):算完直接丢,等于没筛。 */ + private static final String READ_OWN_COMPANY_ID_DISCARD_PROBE = """ + @GetMapping("/probe") + public String thirdDoorDiscard(@RequestParam(name = "company_id", required = false) Long companyId) { + dataReadScope.readCompanyIdOrOwn(user, companyId); + return "ok"; + } + """; + + /** 第三道正门的负探针(D 在该门上的存在理由):进出口的是 {@code null},tab 恒不动。 */ + private static final String READ_OWN_COMPANY_ID_PASSED_NULL_PROBE = """ + @GetMapping("/probe") + public String thirdDoorNull(@RequestParam(name = "company_id", required = false) Long companyId) { + AdminUserEntity user = operator.user(); + Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null); + return String.valueOf(productCategoryService.list(null, scopedCompanyId)); + } + """; + /** * 断言 C 第 ② 步的嵌套实参探针(形状逐字抄现网:{@code DedupeTotalDataController.page})。 *

    10-05 批次 2/3 实跑 6 记假红全在这一形上——断言 A 要求正门调用写在 handler 块内, @@ -632,6 +678,29 @@ class CompanyIdParamGoesThroughReadScopeTest { .isNotNull() .contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表"); + // 第三道门同样要各自带能红/能绿两向证据:C 与 D 都是对 SCOPE_DOORS 逐条跑的, + // 少一枚探针就等于那道门上的返回值与入参没人看守(类目页正是走这道门的页)。 + assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_CAUGHT_PROBE, "READ_OWN_COMPANY_ID_CAUGHT_PROBE")) + .as("断言 C 自检(第三道门·正样本):Long scopedCompanyId = readCompanyIdOrOwn(user, companyId) " + + "且它进了 service.list(…) 的实参 ⇒ 判红就是护栏假红") + .isNull(); + assertThat(companyIdArgProbeReason( + READ_OWN_COMPANY_ID_CAUGHT_PROBE, "READ_OWN_COMPANY_ID_CAUGHT_PROBE", CAMEL_PARAM)) + .as("断言 D 自检(第三道门·正样本):companyId 真进了 readCompanyIdOrOwn 的实参表 ⇒ 不许红") + .isNull(); + assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_DISCARD_PROBE, "READ_OWN_COMPANY_ID_DISCARD_PROBE")) + .as("断言 C 自检(第三道门·负样本):readCompanyIdOrOwn( 写成裸语句、结果当场丢掉 ⇒ 必须判红") + .isNotNull() + .contains("范围算了但没接住"); + assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_PASSED_NULL_PROBE, "READ_OWN_COMPANY_ID_PASSED_NULL_PROBE")) + .as("断言 D(第三道门)负样本的前提(断言 C):结果接进 scopedCompanyId 又喂给了 service ⇒ C 判它绿") + .isNull(); + assertThat(companyIdArgProbeReason( + READ_OWN_COMPANY_ID_PASSED_NULL_PROBE, "READ_OWN_COMPANY_ID_PASSED_NULL_PROBE", CAMEL_PARAM)) + .as("断言 D 自检(第三道门·负样本):readCompanyIdOrOwn(user, null) ⇒ 必须判红") + .isNotNull() + .contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表"); + // 配对括号取实参表(放宽)的成对证据:两枚正样本必须绿(否则 6 支已接线 handler 假红), // 一枚"嵌套了但没带公司参数"的样本必须照旧红(否则放宽 = 把 D 关掉)。 assertThat(scopeProbeReason(SCOPE_NESTED_ARG_PROBE, "SCOPE_NESTED_ARG_PROBE")) @@ -753,7 +822,8 @@ class CompanyIdParamGoesThroughReadScopeTest { + " 页(改名/换 mapping/换参数形状会让它静默脱离射程,分母不能自造)") .contains(WIRED_PAGE_KEYS.toArray(new String[0])); assertThat(scopeDiscarded) - .as("范围算了但没接住(断言 C):两条正门(readScope( / readCompanyId()的结果要么没赋给变量," + .as("范围算了但没接住(断言 C):" + String.join(" / ", SCOPE_DOORS) + + ")的结果要么没赋给变量," + "要么赋了却没交给任何方法调用") .isEmpty(); diff --git a/backend-java/src/test/java/com/nanri/aiimage/common/service/DataReadScopeTest.java b/backend-java/src/test/java/com/nanri/aiimage/common/service/DataReadScopeTest.java index a77658f2b..0fb9a02b7 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/common/service/DataReadScopeTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/common/service/DataReadScopeTest.java @@ -1,8 +1,10 @@ package com.nanri.aiimage.common.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.security.AdminAuthSupport; @@ -145,4 +147,63 @@ class DataReadScopeTest { assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), 7L)).isNull(); assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), null)).isNull(); } + + // ---- 第三道门 readCompanyIdOrOwn:归属物化列、且可见集不靠账号/分组的表(商品类目)---- + // 与第二道门只差非超管那一支,而那一支正是 10-06 逐节点复验抓到的洞:biz_product_category 连账号列 + // 都没有,非超管返回 null=把整棵树交给每一家(实测公司 2 的 admin 读到 412 行、其中 394 行是公司 1 + // 的自建类目)。这三条若不写,把 `requireCompanyId` 改回 `return null` 不会让任何现有用例变红。 + + @Test + @DisplayName("第三道门:超管仍按 tab 走(tab 是视图开关,不是安全边界)") + void readOwnDoorForSuperAdminFollowsTheTab() { + assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), 2L)).isEqualTo(2L); + assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), null)).isNull(); + assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), 0L)).isNull(); + assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), -3L)).isNull(); + } + + @Test + @DisplayName("第三道门:非超管钉本公司,带别家的 tab 也不越权、也不返回空") + void readOwnDoorPinsNonSuperAdminToItsOwnCompany() { + when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L); + assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), 2L)).isEqualTo(2L); + // 传 7(别家)必须还是 2:类目树没有"空树"这个可用视图,返回空集等于把那一家自己的自建项也删掉。 + assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), 7L)).isEqualTo(2L); + assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), null)).isEqualTo(2L); + } + + /** 「公司超级管理员」在这三道门里都按非超管处理——它不是 super_admin,这一支若漂了就是整家公司越权。 */ + @Test + @DisplayName("第三道门:company_super_admin 按非超管钉本公司,不当站点超管") + void readOwnDoorTreatsCompanySuperAdminAsNonSuperAdmin() { + when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L); + assertThat(dataReadScope.readCompanyIdOrOwn(user(9L, "company_super_admin", 2L), null)).isEqualTo(2L); + assertThat(dataReadScope.readCompanyIdOrOwn(user(9L, "company_super_admin", 2L), 7L)).isEqualTo(2L); + } + + // ---- 写侧闸门 writeCompanyId:读收窄而写不收窄="藏起来的行照样能删" ---- + + @Test + @DisplayName("写闸门:平台超管给 null(不限),不许把超管锁死在他自己那一行 companyId 上") + void writeGateLeavesTheSiteSuperAdminUnrestricted() { + assertThat(dataReadScope.writeCompanyId(user(1L, "super_admin", 1L))).isNull(); + verifyNoInteractions(companyScope); + } + + @Test + @DisplayName("写闸门:非超管给本公司,且完全不看请求里带了什么(无 tab 形参可言)") + void writeGateReturnsTheOperatorsOwnCompany() { + when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L); + assertThat(dataReadScope.writeCompanyId(user(5L, "admin", 2L))).isEqualTo(2L); + assertThat(dataReadScope.writeCompanyId(user(9L, "company_super_admin", 2L))).isEqualTo(2L); + } + + @Test + @DisplayName("写闸门:没有公司归属的账号当场炸,不退化成 null=不限") + void writeGateFailsFastWithoutCompanyMembership() { + when(companyScope.requireCompanyId(any(AdminUserEntity.class))) + .thenThrow(new com.nanri.aiimage.common.exception.BusinessException(403, "当前账号没有所属公司")); + assertThatThrownBy(() -> dataReadScope.writeCompanyId(user(5L, "admin", null))) + .isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class); + } } diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryControllerCompanyScopeTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryControllerCompanyScopeTest.java index a4e22bdc6..f7259d7c1 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryControllerCompanyScopeTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/controller/ProductCategoryControllerCompanyScopeTest.java @@ -47,24 +47,24 @@ class ProductCategoryControllerCompanyScopeTest { } @Test - @DisplayName("列表:tab 的公司 id 交给 readCompanyId,出口给什么 service 就用什么") + @DisplayName("列表:tab 的公司 id 交给 readCompanyIdOrOwn,出口给什么 service 就用什么") void listPassesTheTabValueThroughTheDoor() { HttpServletRequest request = login(); when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user()); - when(dataReadScope.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID); + when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID); controller().list(request, "面霜", COMPANY_ID); - verify(dataReadScope).readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID)); + verify(dataReadScope).readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID)); verify(productCategoryService).list("面霜", COMPANY_ID); } @Test @DisplayName("列表:非超管由出口判成\"不筛\",controller 不许自己补一个公司 id 进去") - void listUsesTheDorsVerdictForNonSuperAdmin() { + void listUsesTheDoorsVerdictForNonSuperAdmin() { HttpServletRequest request = login(); when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user()); - when(dataReadScope.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(null); + when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(null); controller().list(request, "面霜", COMPANY_ID); @@ -76,7 +76,7 @@ class ProductCategoryControllerCompanyScopeTest { void everyReadEndpointGoesThroughTheDoor() { HttpServletRequest request = login(); when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user()); - when(dataReadScope.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID); + when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID); // export 的返回要真喂给 ResponseEntity.contentLength(bytes.length):mock 给 null 会 NPE 在断言之前的装配里。 when(productCategoryService.export("面霜", COMPANY_ID)).thenReturn(new byte[0]); ProductCategoryController controller = controller(); @@ -89,7 +89,7 @@ class ProductCategoryControllerCompanyScopeTest { verify(productCategoryService).search("面霜", 1L, 20L, COMPANY_ID); verify(productCategoryService).export("面霜", COMPANY_ID); verify(dataReadScope, times(3)) - .readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID)); + .readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID)); } /** 写侧口径(一期定案):归属由后端从操作者会话推导,请求体不带 company_id,controller 也不读 tab。 */ @@ -110,6 +110,39 @@ class ProductCategoryControllerCompanyScopeTest { verifyNoInteractions(dataReadScope); } + /** 写侧闸门(10-06 逐节点复验后补):读侧已经收窄,写侧不收窄="藏起来的行照样能删"。 */ + @Test + @DisplayName("更新/删除:把 writeCompanyId 的判定原样交给 service,controller 不自己补公司 id") + void writeEndpointsPassTheRowOwnershipGate() { + HttpServletRequest request = login(); + when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user()); + when(dataReadScope.writeCompanyId(any(AdminUserEntity.class))).thenReturn(COMPANY_ID); + ProductCategorySaveRequest body = new ProductCategorySaveRequest(); + body.setName("面霜改名"); + ProductCategoryController controller = controller(); + + controller.update(request, 300L, body); + controller.delete(request, 300L); + + verify(productCategoryService).update(300L, body, COMPANY_ID); + verify(productCategoryService).delete(300L, COMPANY_ID); + } + + /** 反向钉:闸门给 null(平台超管)时必须原样传 null——顺手补一个公司 id 会把超管锁死在本公司。 */ + @Test + @DisplayName("更新:闸门判超管(null)时把 null 传下去,不补任何公司 id") + void writeGateKeepsTheSuperAdminVerdict() { + HttpServletRequest request = login(); + when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user()); + when(dataReadScope.writeCompanyId(any(AdminUserEntity.class))).thenReturn(null); + ProductCategorySaveRequest body = new ProductCategorySaveRequest(); + body.setName("内置类目改名"); + + controller().update(request, 10L, body); + + verify(productCategoryService).update(10L, body, null); + } + private MockHttpServletRequest login() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("X-Internal-Token", "irrelevant-here"); diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryCompanyScopeTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryCompanyScopeTest.java index bc44f1dab..b172c629a 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryCompanyScopeTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/productcategory/service/ProductCategoryCompanyScopeTest.java @@ -29,9 +29,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; /** @@ -230,7 +232,7 @@ class ProductCategoryCompanyScopeTest { when(productCategoryMapper.selectCount(any())).thenReturn(0L); when(productCategoryMapper.updateById(any(ProductCategoryEntity.class))).thenReturn(1); - service.update(300L, saveRequest("面霜改名", BUILTIN_PARENT_ID)); + service.update(300L, saveRequest("面霜改名", BUILTIN_PARENT_ID), COMPANY_ID); LambdaQueryWrapper sibling = countWrappers().get(0); assertTrue(sibling.getSqlSegment().contains("company_id IN"), sibling.getSqlSegment()); @@ -240,6 +242,111 @@ class ProductCategoryCompanyScopeTest { "把行挪到可见集外的节点下面会让它从原本看得见它的 tab 里消失:" + params); } + // ---- 写侧行归属闸门(10-06 逐节点复验后补)---- + // 读侧已经把这一页收窄到本公司,写侧不收窄="藏起来的行照样能改名/删除",那是静默删除不是隔离。 + // assertSameCompany 自己的判定由 CompanyScopeSupportTest 钉(本仓唯一一份),这里只钉"service 有没有 + // 把这一刀落在正确的两个值上、被拒之后还写不写库"——所以桩按真方法的语义给:只有配对不对才抛。 + + @Test + @DisplayName("更新别家公司的行:闸门 403 且 updateById 一次都不跑") + void updateRejectsARowOwnedByAnotherCompany() { + Long foreignCompanyId = 3L; + when(productCategoryMapper.selectById(300L)).thenReturn(row(300L, null, "别家的根", foreignCompanyId)); + stubSameCompanyJudgment(); + + BusinessException exception = assertThrows(BusinessException.class, + () -> service.update(300L, saveRequest("改名", null), COMPANY_ID)); + + assertEquals(403, exception.getCode()); + verify(productCategoryMapper, never()).updateById(any(ProductCategoryEntity.class)); + // 断言闸门拿到的是行自己的归属而不是 tab 之外的什么值:喂错第二个实参,这一刀形同没落。 + verify(companyScopeSupport).assertSameCompany(eq(COMPANY_ID), eq(foreignCompanyId), any()); + } + + @Test + @DisplayName("更新内置节点(哨兵 0):公司账号一律拒,改了它所有公司的树与货源归类同一天跟着变") + void updateRejectsTheSharedBuiltinRow() { + when(productCategoryMapper.selectById(BUILTIN_PARENT_ID)) + .thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN)); + stubSameCompanyJudgment(); + + BusinessException exception = assertThrows(BusinessException.class, + () -> service.update(BUILTIN_PARENT_ID, saveRequest("护肤品改名", null), COMPANY_ID)); + + assertEquals(403, exception.getCode()); + verify(productCategoryMapper, never()).updateById(any(ProductCategoryEntity.class)); + } + + @Test + @DisplayName("更新:本公司自己的行放行(闸门不该把这一页的正常编辑也拦死)") + void updateAcceptsTheRowsOwnCompany() { + when(productCategoryMapper.selectById(300L)).thenReturn(row(300L, null, "面霜", COMPANY_ID)); + when(productCategoryMapper.selectCount(any())).thenReturn(0L); + when(productCategoryMapper.updateById(any(ProductCategoryEntity.class))).thenReturn(1); + stubSameCompanyJudgment(); + + service.update(300L, saveRequest("面霜改名", null), COMPANY_ID); + + verify(productCategoryMapper).updateById(any(ProductCategoryEntity.class)); + } + + /** 反向钉(多隔离那一向):闸门判 null = 平台超管不限,顺手补一个公司 id 会把超管锁死在本公司。 */ + @Test + @DisplayName("更新:超管口径(null)不调用行归属闸门,内置节点照样能改") + void superAdminUpdateSkipsTheRowGate() { + when(productCategoryMapper.selectById(BUILTIN_PARENT_ID)) + .thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN)); + when(productCategoryMapper.selectCount(any())).thenReturn(0L); + when(productCategoryMapper.updateById(any(ProductCategoryEntity.class))).thenReturn(1); + + service.update(BUILTIN_PARENT_ID, saveRequest("护肤品改名", null), null); + + verify(productCategoryMapper).updateById(any(ProductCategoryEntity.class)); + verifyNoInteractions(companyScopeSupport); + } + + @Test + @DisplayName("删除:闸门在数子级之前,别家的行连「有几个子节点」都不去查") + void deleteRejectsARowOwnedByAnotherCompany() { + Long foreignCompanyId = 3L; + when(productCategoryMapper.selectById(400L)).thenReturn(row(400L, null, "别家的叶子", foreignCompanyId)); + stubSameCompanyJudgment(); + + BusinessException exception = assertThrows(BusinessException.class, + () -> service.delete(400L, COMPANY_ID)); + + assertEquals(403, exception.getCode()); + verify(productCategoryMapper, never()).deleteById(anyLong()); + verify(productCategoryMapper, never()).selectCount(any()); + } + + @Test + @DisplayName("删除:本公司自己的行放行并真删") + void deleteAcceptsTheRowsOwnCompany() { + when(productCategoryMapper.selectById(401L)).thenReturn(row(401L, null, "自建叶子", COMPANY_ID)); + when(productCategoryMapper.selectCount(any())).thenReturn(0L); + stubSameCompanyJudgment(); + + service.delete(401L, COMPANY_ID); + + verify(productCategoryMapper).deleteById(401L); + } + + /** + * 把 {@code assertSameCompany} 按真方法的语义桩上(第一参 ≠ 第二参才抛 403)。 + * 不这么写的话 Mockito 对 void 方法默认"什么都不做",三条拒绝用例会因为错误的理由恒绿。 + */ + private void stubSameCompanyJudgment() { + org.mockito.Mockito.doAnswer(call -> { + Long operatorCompanyId = call.getArgument(0); + Long rowCompanyId = call.getArgument(1); + if (rowCompanyId == null || !rowCompanyId.equals(operatorCompanyId)) { + throw new BusinessException(403, call.getArgument(2, String.class)); + } + return null; + }).when(companyScopeSupport).assertSameCompany(any(), any(), any()); + } + private ProductCategorySaveRequest saveRequest(String name, Long parentId) { ProductCategorySaveRequest request = new ProductCategorySaveRequest(); request.setName(name);