From 41dbcad1accdbacc71a0a574ae935a6f36c2f9a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com> Date: Mon, 5 Oct 2026 16:25:24 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=85=AC=E5=8F=B8tab):=20=E5=BA=97?= =?UTF-8?q?=E9=93=BA=E7=AE=A1=E7=90=86=E4=B8=8E=E6=95=B0=E6=8D=AE=E6=9D=83?= =?UTF-8?q?=E9=99=90=E5=88=86=E7=BB=84=E6=8C=89=E6=88=90=E5=91=98=E9=9B=86?= =?UTF-8?q?=E7=AD=9B,=20=E5=87=AD=E6=8D=AE=E6=8C=89=20id=20=E8=A1=A5?= =?UTF-8?q?=E8=AF=BB=E9=97=B8=E9=97=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Task 11: ShopManageController.page / listGroups 接 DataReadScope.readScope, 把 company_id 算出的成员集当参数传给 service(controller 层收口, service 手上 只有 operatorId+布尔); ShopManageGroupService.list 增加 companyMemberIds 腿。 凭据 getCredentialById 的闸门用与 page() 同形的尺子(created_by_id IN creators OR group_id IN groups),不是账号集合 —— 后者表达不了分组那一腿, 会把列表看得见 的行读凭据时 403 掉, 那是把正当访问静默删掉。 新增 testutil/SourceScan 供源码扫描式护栏取文(找不到方法必须抛, 不许返回空串恒绿)。 前端两页接 tab: companyId 取 companyTab.requestCompanyId, 并 watch activeId 重载; G1 登记表给 admin_shop_manage 钉两条发送点(白名单 builder 故意不收 companyId)。 写侧入口一律不收 company_id, 由 ShopManageServiceTest 逐方法反向钉住。 --- .../src/pages/account/GroupsPage.vue | 9 +- .../src/pages/account/shop-group-api.ts | 4 +- .../src/pages/shop/ShopManagePage.vue | 10 +- admin-frontend-vue/src/pages/shop/shop-dto.ts | 4 + .../src/pages/shop/shop-manage-api.ts | 12 +- .../tests/company-tab-wiring.test.ts | 21 ++- .../controller/ShopManageController.java | 42 ++--- .../service/ShopManageGroupService.java | 27 +++- .../shopkey/service/ShopManageService.java | 27 +++- .../ShopManageCredentialAuthTest.java | 4 +- .../service/ShopManageServiceTest.java | 94 ++++++++++++ .../nanri/aiimage/testutil/SourceScan.java | 144 ++++++++++++++++++ 12 files changed, 362 insertions(+), 36 deletions(-) create mode 100644 backend-java/src/test/java/com/nanri/aiimage/testutil/SourceScan.java diff --git a/admin-frontend-vue/src/pages/account/GroupsPage.vue b/admin-frontend-vue/src/pages/account/GroupsPage.vue index 5ceab4b61..d8f859ab5 100644 --- a/admin-frontend-vue/src/pages/account/GroupsPage.vue +++ b/admin-frontend-vue/src/pages/account/GroupsPage.vue @@ -2,9 +2,10 @@ import { formatDateTime } from '@/utils/datetime' /** 分组管理页 · 像素复刻旧版 admin.html panel-group-manage(自绘:顶部数据权限分组摘要 chips + 分组列表表格 + 新建分组;全量无分页同旧版)。 * script 逻辑沿用现有 Vue 实现;编辑器保留现有组件。 */ -import { computed, onMounted, ref } from 'vue' +import { computed, onMounted, ref, watch } from 'vue' import { ElMessage } from 'element-plus' import { useAdminSessionStore } from '@/stores/admin-session' +import { useCompanyTabStore } from '@/stores/company-tab' import { openAdminConfirm } from '@/components/admin-confirm' import { deleteShopGroup, fetchShopGroups } from './shop-group-api' import type { ShopGroupItem } from './shop-group-model' @@ -12,6 +13,7 @@ import GroupEditorDialog from './GroupEditorDialog.vue' import OldPagination from '@/components/OldPagination.vue' const session = useAdminSessionStore() +const companyTab = useCompanyTabStore() const loading = ref(false) const rows = ref([]) const editorVisible = ref(false) @@ -46,7 +48,7 @@ function canEditOf(group: ShopGroupItem): boolean { async function loadGroups() { loading.value = true try { - rows.value = await fetchShopGroups() + rows.value = await fetchShopGroups(companyTab.requestCompanyId) } catch (error) { ElMessage.error(error instanceof Error ? error.message : '数据权限分组加载失败') } finally { @@ -54,6 +56,9 @@ async function loadGroups() { } } +// 切公司 = 重新取数(G1 的 pageFiles 断言盯着这一条)。 +watch(() => companyTab.activeId, () => void loadGroups()) + function openCreate() { editingGroup.value = null editorVisible.value = true diff --git a/admin-frontend-vue/src/pages/account/shop-group-api.ts b/admin-frontend-vue/src/pages/account/shop-group-api.ts index a6eb79ab7..379f4b693 100644 --- a/admin-frontend-vue/src/pages/account/shop-group-api.ts +++ b/admin-frontend-vue/src/pages/account/shop-group-api.ts @@ -11,8 +11,8 @@ import { export const SHOP_GROUPS_ENDPOINT = '/api/admin/shop-manages/groups' -export async function fetchShopGroups(): Promise { - const { data } = await http.get(SHOP_GROUPS_ENDPOINT) +export async function fetchShopGroups(companyId?: number | null): Promise { + const { data } = await http.get(SHOP_GROUPS_ENDPOINT, { params: { company_id: companyId } }) return parseShopGroupList(data) } diff --git a/admin-frontend-vue/src/pages/shop/ShopManagePage.vue b/admin-frontend-vue/src/pages/shop/ShopManagePage.vue index 5faec1ec0..b872d7cf3 100644 --- a/admin-frontend-vue/src/pages/shop/ShopManagePage.vue +++ b/admin-frontend-vue/src/pages/shop/ShopManagePage.vue @@ -2,9 +2,10 @@ import { formatDateTime } from '@/utils/datetime' /** 店铺管理页 · 像素复刻旧版 admin.html panel-shop-manage(自绘:面板头+新增店铺、筛选、密码列 ******+眼睛实时读明文、旧式表格/分页、原生 confirm 删除)。 * script 逻辑沿用现有 Vue 实现(凭证明文 dialog/编辑弹窗/分组筛选)。 */ -import { computed, onMounted, reactive, ref } from 'vue' +import { computed, onMounted, reactive, ref, watch } from 'vue' import { ElMessage } from 'element-plus' import { useAdminSessionStore } from '@/stores/admin-session' +import { useCompanyTabStore } from '@/stores/company-tab' import { deleteShopManage, fetchShopCredential, @@ -18,6 +19,7 @@ import type { ShopCredential, ShopGroupOption, ShopSummary } from './shop-dto.ts import OldPagination from '@/components/OldPagination.vue' const session = useAdminSessionStore() +const companyTab = useCompanyTabStore() /** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */ const isSuperAdmin = computed(() => session.isSuperAdmin) const loading = ref(false) @@ -75,7 +77,7 @@ async function togglePassword(row: ShopSummary) { async function loadGroups() { try { - groups.value = await fetchShopManageGroups() + groups.value = await fetchShopManageGroups(companyTab.requestCompanyId) } catch (error) { ElMessage.error(error instanceof Error ? error.message : '分组加载失败') } @@ -89,6 +91,7 @@ async function load() { pageSize: pageSize.value, groupId: filter.groupId, shopName: filter.shopName.trim() || undefined, + companyId: companyTab.requestCompanyId, }) rows.value = result.items total.value = result.total @@ -100,6 +103,9 @@ async function load() { } } +// 切公司 = 重新取数:列表与分组下拉共用这一个 watch(少一个 = 那半边的 tab 是装饰品)。 +watch(() => companyTab.activeId, () => { void loadGroups(); void load() }) + function apply() { page.value = 1 load() diff --git a/admin-frontend-vue/src/pages/shop/shop-dto.ts b/admin-frontend-vue/src/pages/shop/shop-dto.ts index a9618e781..21998509a 100644 --- a/admin-frontend-vue/src/pages/shop/shop-dto.ts +++ b/admin-frontend-vue/src/pages/shop/shop-dto.ts @@ -93,6 +93,8 @@ export interface ShopManageListParams { pageSize: number groupId?: number | null shopName?: string + /** 公司 tab 的值;normalizeShopListParams 不点名它,只有 api 层能从原始 params 读到。 */ + companyId?: number | null } export interface ShopKeyPageQuery { @@ -105,6 +107,8 @@ export interface ShopManagePageQuery { pageSize: number groupId?: number shopName?: string + /** 下划线形:与后端 @RequestParam(name = "company_id") 逐字对齐。 */ + company_id?: number } function finiteInt(value: unknown): number | null { diff --git a/admin-frontend-vue/src/pages/shop/shop-manage-api.ts b/admin-frontend-vue/src/pages/shop/shop-manage-api.ts index e5758ec06..7395dbcca 100644 --- a/admin-frontend-vue/src/pages/shop/shop-manage-api.ts +++ b/admin-frontend-vue/src/pages/shop/shop-manage-api.ts @@ -24,15 +24,21 @@ export const SHOP_MANAGE_ENDPOINT = '/api/admin/shop-manages' export async function fetchShopManageList(params: Partial = {}): Promise { const normalized = normalizeShopListParams(params) - const { data } = await http.get(SHOP_MANAGE_ENDPOINT, { params: toShopManagePageQuery(normalized) }) + // normalizeShopListParams 与 toShopManagePageQuery 都是白名单构造(不点名 companyId), + // 所以公司值只能从原始 params 读:写成 normalized.companyId 是 TS 绿、运行时恒 undefined。 + const query = toShopManagePageQuery(normalized) + if (params.companyId != null) query.company_id = params.companyId + const { data } = await http.get(SHOP_MANAGE_ENDPOINT, { params: query }) return parseShopManagePage(data) } export const SHOP_MANAGE_GROUPS_ENDPOINT = '/api/admin/shop-manages/groups' /** 加载店铺分组下拉选项(超级管理员取全部,普通管理员由后端限定可访问分组)。 */ -export async function fetchShopManageGroups(): Promise { - const { data } = await http.get(SHOP_MANAGE_GROUPS_ENDPOINT) +/** 分组下拉:打的是与分组管理页同一个 GET /groups,所以它也必须跟着公司 tab 收窄, + * 否则店铺列表窄了、下拉里还选得到别家的组。 */ +export async function fetchShopManageGroups(companyId?: number | null): Promise { + const { data } = await http.get(SHOP_MANAGE_GROUPS_ENDPOINT, { params: { company_id: companyId } }) return parseShopManageGroups(data) } diff --git a/admin-frontend-vue/tests/company-tab-wiring.test.ts b/admin-frontend-vue/tests/company-tab-wiring.test.ts index 83bdde25e..92178e8d7 100644 --- a/admin-frontend-vue/tests/company-tab-wiring.test.ts +++ b/admin-frontend-vue/tests/company-tab-wiring.test.ts @@ -70,10 +70,27 @@ const COMPANY_ID_SOURCE_PINS: Readonly> { file: 'src/api/device-logs.ts', shape: null, note: 'Task 12 未接线(已在缺口清单里)' }, ], admin_group_manage: [ - { file: 'src/pages/account/shop-group-api.ts', shape: null, note: 'Task 11 未接线(已在缺口清单里)' }, + { + file: 'src/pages/account/shop-group-api.ts', + // fetchShopGroups(companyId?: number | null):唯一发送口,右侧必须是它自己的形参。 + shape: /company_id\s*:\s*companyId\b/, + note: 'null 由 axios 跳过 ⇒ 非超管不发 company_id,后端按会话裁剪', + }, ], admin_shop_manage: [ - { file: 'src/pages/shop/shop-manage-api.ts', shape: null, note: 'Task 11 未接线(已在缺口清单里)' }, + { + file: 'src/pages/shop/shop-manage-api.ts', + // fetchShopManageList(params):toShopManagePageQuery 是白名单构造 ⇒ 公司值只许从原始 params 读。 + shape: /company_id\s*=\s*params\.companyId\b/, + note: '写成 normalized.companyId 会 TS 绿、运行时恒 undefined(Task 8 复评 I-2 那个洞)', + }, + { + file: 'src/pages/shop/shop-manage-api.ts', + // 第二个发送口 fetchShopManageGroups(companyId):同一个 GET /groups,与分组管理页共用这一形。 + // 两条各管一处取值口,不许合成一条 alternation —— 那等于把判据放松回「文件里出现过就行」。 + shape: /company_id\s*:\s*companyId\b/, + note: '列表窄了而下拉不窄 = 两页口径对不上,且下拉能选到别家的组', + }, ], } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java index e2b675581..ecfb6ebb2 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java @@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.controller; import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.model.entity.AdminUserEntity; +import com.nanri.aiimage.common.service.DataReadScope; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest; @@ -35,6 +36,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import java.util.List; + @Slf4j @RestController @RequiredArgsConstructor @@ -45,6 +48,7 @@ public class ShopManageController { private final ShopManageService shopManageService; private final ShopManageGroupService shopManageGroupService; private final AdminAuthSupport adminAuthSupport; + private final DataReadScope dataReadScope; /** 解析当前操作者(JWT 或内部令牌通道),数据范围一律以该身份为准,不信任调用方传入的 operatorId/superAdmin。 */ private AdminUserEntity requireOperator(HttpServletRequest request) { @@ -56,7 +60,8 @@ public class ShopManageController { } @GetMapping - @Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选") + @Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选;" + + "company_id 只收窄可见集、不放大,跨公司查看仅超管") @ApiResponses({ @io.swagger.v3.oas.annotations.responses.ApiResponse( responseCode = "200", @@ -68,15 +73,16 @@ public class ShopManageController { @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page, @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, @Parameter(description = "分组 ID") @RequestParam(required = false) Long groupId, - @Parameter(description = "店铺名称") @RequestParam(required = false) String shopName) { + @Parameter(description = "店铺名称") @RequestParam(required = false) String shopName, + @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { AdminUserEntity operator = requireOperator(request); - return ApiResponse.success(shopManageService.page( - page, - pageSize, - groupId, - shopName, - operator.getId(), - isSuper(operator))); + Long operatorId = operator.getId(); + boolean superAdmin = isSuper(operator); + // 公司 tab 只对超管收窄:非超管的可见集里含「靠分组可见」的行,而分组行没有账号列可推公司, + // 给它叠 created_by_id IN (成员) 会把那批行从每一个 tab 里静默删掉(不报错、不 403)。 + List memberIds = superAdmin ? dataReadScope.readScope(operator, companyId).userIdsOr(null) : null; + ShopManagePageVo vo = shopManageService.page(page, pageSize, groupId, shopName, operatorId, superAdmin, memberIds); + return ApiResponse.success(vo); } @PostMapping @@ -111,15 +117,19 @@ public class ShopManageController { } @GetMapping("/groups") - @Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部") + @Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部;" + + "company_id 只收窄可见集、不放大,跨公司查看仅超管") public ApiResponse> listGroups( HttpServletRequest request, - @Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById) { + @Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById, + @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { AdminUserEntity operator = requireOperator(request); if (isSuper(operator)) { - return ApiResponse.success(shopManageGroupService.list(createdById)); + List memberIds = dataReadScope.readScope(operator, companyId).userIdsOr(null); + return ApiResponse.success(shopManageGroupService.list(createdById, memberIds)); } - return ApiResponse.success(shopManageGroupService.listAccessible(operator.getId(), false)); + Long operatorId = operator.getId(); + return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false)); } @PostMapping("/groups") @@ -175,10 +185,8 @@ public class ShopManageController { public ApiResponse adminCredential( HttpServletRequest request, @Parameter(description = "店铺主键 ID") @PathVariable Long id) { - requireOperator(request); - // 2026-09 修复:此前忽略路径 id、改用请求参数 shop_name 查询, - // 会出现「路径声明的店铺」与「实际读取凭据的店铺」不一致 - return ApiResponse.success(shopManageService.getCredentialById(id)); + AdminUserEntity operator = requireOperator(request); + return ApiResponse.success(shopManageService.getCredentialById(id, operator.getId(), isSuper(operator))); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java index 6d627f3fd..6b01114e1 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java @@ -45,14 +45,31 @@ public class ShopManageGroupService { private final AdminUserMapper adminUserMapper; public List list() { - return list(null); + return list(null, null); } public List list(Long createdById) { - return toVoList(groupMapper.selectList(new LambdaQueryWrapper() - .eq(createdById != null && createdById > 0, ShopManageGroupEntity::getCreatedById, createdById) - .or(createdById != null && createdById > 0, wrapper -> wrapper.eq(ShopManageGroupEntity::getUserId, createdById)) - .orderByAsc(ShopManageGroupEntity::getId))); + return list(createdById, null); + } + + public List list(Long createdById, List companyMemberIds) { + LambdaQueryWrapper qw = new LambdaQueryWrapper() + .orderByAsc(ShopManageGroupEntity::getId); + if (createdById != null && createdById > 0) { + // 这两条原本是平铺的 .eq(...).or(...):MP 的 normal 段按顺序拼 AND/OR,MySQL 里 AND 优先, + // 外面再叠一条公司条件时 created_by_id = ? 那半边会整块逃出筛选(多放行、不报错)⇒ 必须收进 and()。 + qw.and(w -> w.eq(ShopManageGroupEntity::getCreatedById, createdById) + .or(x -> x.eq(ShopManageGroupEntity::getUserId, createdById))); + } + if (companyMemberIds != null) { + if (companyMemberIds.isEmpty()) { + qw.eq(ShopManageGroupEntity::getId, -1L); + } else { + // 公司条件同样自成一组(G2 护栏钉的是 AND (…) 这个形状;平铺 IN 与它在语义上等价)。 + qw.and(w -> w.in(ShopManageGroupEntity::getCreatedById, companyMemberIds)); + } + } + return toVoList(groupMapper.selectList(qw)); } public List listAccessible(Long operatorId, boolean superAdmin) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java index 5f11aad85..dbcca9ff9 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java @@ -28,7 +28,8 @@ public class ShopManageService { private final ShopCredentialCryptoService shopCredentialCryptoService; private final ZiniaoShopIndexRefreshTrigger ziniaoShopIndexRefreshTrigger; - public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId, boolean superAdmin) { + public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId, + boolean superAdmin, List companyMemberIds) { long safePage = Math.max(page, 1); long safePageSize = Math.min(Math.max(pageSize, 1), 100); String safeShopName = shopName == null ? "" : shopName.trim(); @@ -60,6 +61,16 @@ public class ShopManageService { } } + // companyMemberIds 由 controller 算好传进来(service 手上只有 operatorId + 一个布尔, + // 而 readScope 要 AdminUserEntity)。null = 不筛,与"超管没选公司"的今天逐字一致。 + if (companyMemberIds != null) { + if (companyMemberIds.isEmpty()) { + query.eq(ShopManageEntity::getId, -1L); + } else { + query.in(ShopManageEntity::getCreatedById, companyMemberIds); + } + } + Long total = shopManageMapper.selectCount(query); List rows = shopManageMapper .selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)); @@ -152,7 +163,7 @@ public class ShopManageService { *

管理端 {@code GET /{id}/credential} 此前忽略路径里的 id、改用 shop_name 查询—— * 路径声明的对象与实际读取的对象可能不一致(同名的第一条被读写,审计日志却记成另一个 id)。 */ - public ShopManageCredentialVo getCredentialById(Long id) { + public ShopManageCredentialVo getCredentialById(Long id, Long operatorId, boolean superAdmin) { if (id == null || id <= 0) { throw new BusinessException("店铺 ID 不合法"); } @@ -160,6 +171,18 @@ public class ShopManageService { if (entity == null) { throw new BusinessException("店铺不存在"); } + // 尺子必须与 page() 那一条同形:created_by_id IN creators OR group_id IN groups。 + // 账号集合表达不了分组那一腿(店铺建在我可访问的分组里、创建人却不在我的账号集), + // 拿它当闸门会把列表看得见的行读凭据时 403 掉——那是把正当访问静默删掉。 + if (!superAdmin) { + Set creators = shopManageGroupService.listAccessibleCreatorUserIds(operatorId, false); + Set groups = shopManageGroupService.listAccessibleGroupIds(operatorId, false); + boolean visible = (entity.getCreatedById() != null && creators.contains(entity.getCreatedById())) + || (entity.getGroupId() != null && groups.contains(entity.getGroupId())); + if (!visible) { + throw new BusinessException(403, "无权查看该店铺的凭据"); + } + } return toCredentialVo(entity); } diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageCredentialAuthTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageCredentialAuthTest.java index 9659effbd..2bea9d110 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageCredentialAuthTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageCredentialAuthTest.java @@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.controller; import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.model.entity.AdminUserEntity; +import com.nanri.aiimage.common.service.DataReadScope; import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo; import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService; @@ -30,10 +31,11 @@ class ShopManageCredentialAuthTest { private final ShopManageService shopManageService = mock(ShopManageService.class); private final ShopManageGroupService shopManageGroupService = mock(ShopManageGroupService.class); private final AdminAuthSupport adminAuthSupport = mock(AdminAuthSupport.class); + private final DataReadScope dataReadScope = mock(DataReadScope.class); private final HttpServletRequest request = mock(HttpServletRequest.class); private ShopManageController newController() { - return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport); + return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport, dataReadScope); } @Test diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/service/ShopManageServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/service/ShopManageServiceTest.java index 6e6850b66..cce862652 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/service/ShopManageServiceTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/shopkey/service/ShopManageServiceTest.java @@ -1,19 +1,35 @@ package com.nanri.aiimage.modules.shopkey.service; +import com.baomidou.mybatisplus.core.MybatisConfiguration; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity; import com.nanri.aiimage.common.security.ShopCredentialCryptoService; import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper; import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity; +import com.nanri.aiimage.testutil.SourceScan; +import org.apache.ibatis.builder.MapperBuilderAssistant; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.util.List; +import java.util.Set; + +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 static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @@ -29,6 +45,15 @@ class ShopManageServiceTest { @InjectMocks private ShopManageService service; + /** getSqlSegment() 解析 lambda 靠 TableInfo 缓存,单测没有 Spring 容器去建它,不初始化就抛 "can not find lambda cache"。 */ + @BeforeEach + void initTableInfo() { + TableInfoHelper.initTableInfo( + new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageEntity.class); + TableInfoHelper.initTableInfo( + new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageGroupEntity.class); + } + @Test void requireShopByNameReturnsManagedShop() { ShopManageEntity entity = new ShopManageEntity(); @@ -47,4 +72,73 @@ class ShopManageServiceTest { assertEquals("后台店铺管理中未找到店铺:缺失店铺,请先添加店铺信息", exception.getMessage()); } + + @Test + @DisplayName("读:超管选了公司 ⇒ created_by_id 落进成员集;非超管不叠这一条") + void superAdminPageNarrowsToCompanyMembers() { + when(shopManageMapper.selectCount(any())).thenReturn(1L); + when(shopManageMapper.selectList(any())).thenReturn(List.of()); + + service.page(1L, 15L, null, null, 1L, true, List.of(11L, 12L)); + + ArgumentCaptor> captor = + ArgumentCaptor.forClass(LambdaQueryWrapper.class); + verify(shopManageMapper).selectCount(captor.capture()); + // 值在 paramNameValuePairs 里,segment 里只有 MPGENVAL 占位 ⇒ 结构从 segment 读、值从 pairs 读。 + assertThat(captor.getValue().getSqlSegment()).contains("created_by_id").contains("IN ("); + assertThat(captor.getValue().getParamNameValuePairs().values()).contains(11L, 12L); + } + + @Test + @DisplayName("凭据:非超管读「创建人不认识、分组也不认识」的行 ⇒ 403(§6.1 列表筛了按 id 照读)") + void credentialByIdRejectsRowOutsideBothVisibleSets() { + when(shopManageMapper.selectById(77L)).thenReturn(shop(77L, 999L, 7L)); + when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L, 12L)); + when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of()); + + assertThatThrownBy(() -> service.getCredentialById(77L, 2L, false)) + .isInstanceOf(BusinessException.class) + .hasFieldOrPropertyWithValue("code", 403); + } + + @Test + @DisplayName("凭据:店铺建在可访问分组里、创建人却不在我的账号集 ⇒ 必须 200(闸门用列表那把尺子,不是账号集合)") + void credentialByIdKeepsGroupVisibleRowsReadable() { + when(shopManageMapper.selectById(78L)).thenReturn(shop(78L, 999L, 5L)); + when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L)); + when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of(5L)); + + // 这一支是防误伤的正样本:把它删掉,下一轮"改成按账号集合卡"就没有任何尺子看得见。 + assertThatCode(() -> service.getCredentialById(78L, 2L, false)).doesNotThrowAnyException(); + } + + @Test + @DisplayName("凭据:超管不查可见集(今天不筛、tab 也不是安全边界;短路写了就红在 NPE 上)") + void credentialByIdStaysUnfilteredForSuperAdmin() { + when(shopManageMapper.selectById(79L)).thenReturn(shop(79L, 999L, 7L)); + + assertThatCode(() -> service.getCredentialById(79L, 1L, true)).doesNotThrowAnyException(); + } + + private static ShopManageEntity shop(long id, Long createdById, Long groupId) { + ShopManageEntity entity = new ShopManageEntity(); + entity.setId(id); + entity.setCreatedById(createdById); + entity.setGroupId(groupId); + return entity; + } + + @Test + @DisplayName("写:店铺与分组的写入口一律不收 company_id——归属不从界面注入(§6.2,未批的界面暴露)") + void writeEntryPointsCarryNoCompanyId() { + String text = SourceScan.sourceText("ShopManageController.java"); + // 必须逐方法体判:page 这个读入口这轮就要加 company_id,全文 doesNotContain 会被自己弄红。 + for (String writer : List.of("create", "update", "delete", "createGroup", "updateGroup", "deleteGroup")) { + assertThat(SourceScan.methodBody(text, writer)) + .as("写入口「" + writer + "」一旦出现 company_id,等于把公司维度端回界面(未批)") + .doesNotContain("company_id") + .doesNotContain("companyId"); + } + assertThat(SourceScan.methodBody(text, "page")).contains("company_id"); + } } diff --git a/backend-java/src/test/java/com/nanri/aiimage/testutil/SourceScan.java b/backend-java/src/test/java/com/nanri/aiimage/testutil/SourceScan.java new file mode 100644 index 000000000..9c8e3d040 --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/testutil/SourceScan.java @@ -0,0 +1,144 @@ +package com.nanri.aiimage.testutil; + +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.stream.Collectors; +import java.util.stream.Stream; + +/** 源码扫描式护栏的取文助手。路径解析照抄 {@code common/security/InternalTokenSingleOutletTest} 的 + * moduleRoot()/mainSources() 两支——surefire 的 cwd 是模块目录,从仓库根或 IDE 跑时要退到 backend-java/, + * 定位不到必须 fail 而不是静默跳过(静默跳过 = 整支护栏恒绿)。 */ +public final class SourceScan { + + private SourceScan() { + } + + /** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的全文字符串。 + * ⚠️ 返回 String,与 InternalTokenSingleOutletTest 里那个返回 Path 的私有 {@code sourceOf} 不是一回事, + * 别指望复用它的——那个是 private。 */ + public static String sourceText(String fileName) { + return mainSources().stream() + .filter(p -> p.getFileName().toString().equals(fileName)) + .findFirst() + .map(SourceScan::read) + .orElseThrow(() -> new IllegalStateException( + "src/main/java 下找不到 " + fileName + " —— 文件改名/挪目录了,护栏要红在这里")); + } + + /** 大括号配平切出「某个方法」的源码:从它的签名行往前一直含到注解,到方法收尾的 `}` 为止。 + * + *

两条它必须自己防住的坑,都写在用例里过:

+ *
    + *
  • 名字必须是完整词:{@code delete} 是 {@code deleteGroup} 的前缀。用 {@code indexOf(name)} + * 会先撞上那个更长的方法 ⇒ "切出来的是隔壁",而断言仍然绿。所以下面用 {@code (? + *
  • 找不到必须抛,不许返回空串:返回 "" 的话 {@code doesNotContain("company_id")} 恒真, + * 反向钉会因为方法被改名而悄悄失效(memory「字符串断言必须排他、解析断言必须可匹配」)。 + * 配套要求:每个用它的反向钉都要带一条"该做的确实做了"的取样自检。
  • + *
+ */ + public static String methodBody(String source, String methodName) { + var matcher = java.util.regex.Pattern + .compile("(? 0; ) { + char c = source.charAt(i); + if (c == '{' || c == '}' || c == ';') { + boundary = i + 1; + break; + } + } + String head = source.substring(boundary, nameStart); + int firstMeaningful = head.length(); + for (String raw : head.split("\n", -1)) { + if (!raw.isBlank()) { + firstMeaningful = head.indexOf(raw.stripLeading()); + break; + } + } + return boundary + firstMeaningful; + } + + private static int nextBrace(String source, int from) { + for (int i = from; i < source.length(); i++) { + if (source.charAt(i) == '{') { + return i; + } + if (source.charAt(i) == ';') { + return -1; // 抽象方法/接口声明,不是我们要切的东西 + } + } + return -1; + } + + /** 朴素配平:源码里的 `{` 与 `}` 若出现在字符串字面量里会算错。本仓库 controller 没有这种写法, + * 但这条限制必须写在脸上——将来有人往方法体里塞一段带花括号的字符串,这个助手会悄悄切短。 */ + 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 == '}') { + if (--depth == 0) { + return i; + } + } + } + return -1; + } + + private static List mainSources() { + Path root = moduleRoot().resolve("src/main/java"); + try (Stream walk = Files.walk(root)) { + return walk.filter(Files::isRegularFile) + .filter(p -> p.getFileName().toString().endsWith(".java")) + .collect(Collectors.toList()); + } catch (IOException e) { + // 定位不到必须抛,不许静默返回空表:返回空 ⇒ sourceText 那支护栏扫不到任何文件而恒绿。 + throw new IllegalStateException("遍历 " + root + " 失败: " + e.getMessage(), e); + } + } + + private static Path moduleRoot() { + Path here = Path.of("").toAbsolutePath(); + if (Files.isDirectory(here.resolve("src/main/java"))) { + return here; + } + Path nested = here.resolve("backend-java"); + if (Files.isDirectory(nested.resolve("src/main/java"))) { + return nested; + } + throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")"); + } + + private static String read(Path file) { + try { + return Files.readString(file, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("读取失败: " + file, e); + } + } +}