test(公司tab): 把两条「筛空」日志分支钉进用例,并订正 company_id 口径
baf8baef 给密钥管理与用量统计接了公司 tab,但"筛空早退"那两支日志一直没人看守:
主管的文案写的是「主管名下无子账户」,可这条分支真正的成因几乎只可能是 company_id
越界(主管的 base 恒含本人,UserDataScopeSupport:55/:78)——排障时会把人往错的方向指。
现在两支分别带 companyScope 宽度,并各钉一条 ListAppender 用例互不放过:
超管只许吐「公司或分组筛后」,主管只许吐「交集为空(多为越界 company_id)」。
分母 UserApiSecretServiceTest 50 例、UserSecretUsageServiceTest 12 例,Failures/Errors 均 0。
同批订正三处会漂的口径:两个 api 模块的注释原写「company_id=0 会让后端 requireCompanyId
直接抛」,实际 DataReadScope.readScope 第一行把 <=0 归一成「没选公司」,0 与缺失等价;
company-tab-wiring 的取值口注释去掉行号(api 文件一改就漂);两支接口的 OpenAPI 描述
补上「company_id 只收窄不放大、跨公司查看仅超管」。
docs/plans/19-company-tab.md 记一条评审未修项(Task 9 I-1):同一页里
POST /user-secrets/{userId}/check 与 DELETE /{userId} 一期就没有归属闸门,本轮把读接进
公司 tab 后它成了唯一还开着的越权写点,补校验是会 403 的行为变更 ⇒ 单独一张工单。
This commit is contained in:
@@ -44,8 +44,8 @@ export async function fetchUserSecretUsage(params: UserSecretUsageQuery): Promis
|
||||
if (params.endDate) query.endDate = params.endDate
|
||||
if (params.keyword) query.keyword = params.keyword
|
||||
if (params.groupId) query.group_id = params.groupId
|
||||
// 用 `!= null` 而不是上面那几行的 truthy 写法:company_id=0 会让后端 requireCompanyId 直接抛,
|
||||
// 宁可让参数缺失时它不出现,也别把 0 悄悄当没传。
|
||||
// 用 `!= null` 而不是上面几行的 truthy 写法:这一项类型是 `number | null`(null = 没选公司)。
|
||||
// 后端把 company_id<=0 归一成「没选公司」(DataReadScope.readScope 第一行),0 与缺失等价,按类型判即可。
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
const { data } = await http.get('/api/admin/user-secret-usage', { params: query })
|
||||
return unwrap<AdminUserSecretUsagePage>(data)
|
||||
|
||||
@@ -68,8 +68,8 @@ export async function fetchUserSecretList(params: UserSecretQuery): Promise<Admi
|
||||
if (params.keyword) query.keyword = params.keyword
|
||||
if (params.checkStatus) query.checkStatus = params.checkStatus
|
||||
if (params.groupId) query.group_id = params.groupId
|
||||
// 用 `!= null` 而不是上面那几行的 truthy 写法:company_id=0 会让后端 requireCompanyId 直接抛,
|
||||
// 宁可让参数缺失时它不出现,也别把 0 悄悄当没传。
|
||||
// 用 `!= null` 而不是上面几行的 truthy 写法:这一项类型是 `number | null`(null = 没选公司)。
|
||||
// 后端把 company_id<=0 归一成「没选公司」(DataReadScope.readScope 第一行),0 与缺失等价,按类型判即可。
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
const { data } = await http.get('/api/admin/user-secrets', { params: query })
|
||||
return unwrap<AdminUserSecretPage>(data)
|
||||
|
||||
@@ -53,7 +53,7 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
|
||||
admin_user_secret_usage: [
|
||||
{
|
||||
file: 'src/api/user-secret-usage.ts',
|
||||
// fetchUserSecretUsage(params: UserSecretUsageQuery):唯一入参对象是 params(:45 那一行的形状)。
|
||||
// fetchUserSecretUsage(params: UserSecretUsageQuery):唯一入参对象是 params(形参表即形状来源,不写行号——api 文件一改就漂)。
|
||||
shape: /company_id\s*=\s*params\.companyId\b/,
|
||||
note: 'query 由本函数自己从零构造,companyId 只能取自 params;api 模块不碰 Pinia store(node --test 直接 import 会抛 no active pinia)',
|
||||
},
|
||||
@@ -61,7 +61,7 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
|
||||
admin_user_secrets: [
|
||||
{
|
||||
file: 'src/api/user-secrets.ts',
|
||||
// fetchUserSecretList(params: UserSecretQuery):唯一入参对象是 params(:71 那一行的形状)。
|
||||
// fetchUserSecretList(params: UserSecretQuery):唯一入参对象是 params(同上,不写行号)。
|
||||
shape: /company_id\s*=\s*params\.companyId\b/,
|
||||
note: '同上:值由 UserSecretsPage.vue 传 companyTab.requestCompanyId,api 里不读任何归一化/构造出来的中间对象',
|
||||
},
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ public class AdminUserApiSecretController {
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询用户密钥", description = "一行一用户;keyword 匹配用户名,checkStatus 按行级状态筛选。主管只能看自己带的分组成员,超管看全量并可按分组筛选。")
|
||||
@Operation(summary = "分页查询用户密钥", description = "一行一用户;keyword 匹配用户名,checkStatus 按行级状态筛选。主管只能看自己带的分组成员,超管看全量并可按分组筛选。company_id 只收窄可见集、不放大,跨公司查看仅超管。")
|
||||
public ApiResponse<AdminUserSecretPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "关键字:用户名") @RequestParam(required = false) String keyword,
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ public class AdminUserSecretUsageController {
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询密钥用量",
|
||||
description = "一行一用户,返回三类调用次数与所选范围汇总;日期为空表示不限。")
|
||||
description = "一行一用户,返回三类调用次数与所选范围汇总;日期为空表示不限。company_id 只收窄可见集、不放大,跨公司查看仅超管。")
|
||||
public ApiResponse<AdminUserSecretUsagePageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "起始日期(含),格式 yyyy-MM-dd")
|
||||
|
||||
+14
-4
@@ -314,8 +314,11 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
* 后台分页:一行一用户,聚合货源查询密钥/外观专利密钥/代理设置三个字段列,并计算行级状态。
|
||||
* 先按关键字圈定用户,再全量聚合、行级状态筛选、按最近更新时间倒序后内存分页
|
||||
* (当前规模为用户数×3,内存聚合成本可控;量级上来后可改为 GROUP BY 下推)。
|
||||
*
|
||||
* <p>可见集合:超管看全量、可按分组与公司筛选;主管(admin)只看自己带的「数据权限分组」成员,
|
||||
* 公司 tab 只**收窄**这条维度,绝不放大主管已看到的集合(全局约束 2)。两条维度取交集是刻意的:
|
||||
* 一个非本公司的成员即使挂在该分组下也不该出现。</p>
|
||||
*/
|
||||
/** 后台分页查询:主管(admin)只看自己带的「数据权限分组」成员;超管看全量、可按分组与公司筛选。 */
|
||||
public AdminUserSecretPageVo adminPage(AdminUserEntity operator, AdminUserSecretQuery query,
|
||||
ReadScope companyScope) {
|
||||
AdminUserSecretQuery safeQuery = query == null ? new AdminUserSecretQuery() : query;
|
||||
@@ -331,11 +334,16 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
// 空集必须早退:交给下面的 in(...) 会渲染成 IN () → SQL 语法错 → 500。
|
||||
// 两条日志分开,排障时看得出是「筛空」(范围交集为空)还是「查空」(库里没记录)。
|
||||
if (scopedUserIds != null && scopedUserIds.isEmpty()) {
|
||||
// 两条都带 companyScope 的宽度:主管的 base 恒含本人(UserDataScopeSupport:55/:78),
|
||||
// 所以"筛空"在现实里几乎只可能出在公司那一维,日志要答得出是哪一维、范围有多宽。
|
||||
String companyScopeSize = companyScope.isUnfiltered() ? "不筛"
|
||||
: String.valueOf(companyScope.userIds().size());
|
||||
if (superAdmin) {
|
||||
log.info("[user-secret] 后台密钥列表:公司或分组筛后无匹配用户,返回空 operatorId={} groupId={}",
|
||||
operator.getId(), requestedGroupId);
|
||||
log.info("[user-secret] 后台密钥列表:公司或分组筛后无匹配用户,返回空 operatorId={} groupId={} companyScope={}",
|
||||
operator.getId(), requestedGroupId, companyScopeSize);
|
||||
} else {
|
||||
log.info("[user-secret] 后台密钥列表:主管名下无子账户,返回空 operatorId={}", operator.getId());
|
||||
log.info("[user-secret] 后台密钥列表:主管可见集与公司范围交集为空(多为越界 company_id),返回空 operatorId={} companyScope={}",
|
||||
operator.getId(), companyScopeSize);
|
||||
}
|
||||
return emptyPageWithGroups(page, pageSize, groupOptions(operator, superAdmin));
|
||||
}
|
||||
@@ -407,6 +415,8 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
* <p>{@code null} = 不筛(超管既没选公司也没选分组,今天的行为);<b>空集由调用方早退</b>,
|
||||
* 不许交给 {@code LambdaQueryWrapper.in(...)}。交集只在 {@link ReadScope#userIdsOr(java.util.List)}
|
||||
* 这一处发生——service 里不许再写第二个判公司的 if。
|
||||
* <p>非超管这支会再解一次 base:{@code DataReadScope} 出口里已经交过同样的集合,重复求交是幂等的
|
||||
* ({@link ReadScope#userIdsOr}),留着是为了让 service 不依赖出口的内部 ⇒ <b>勿把它当成第二次判公司</b>。
|
||||
*/
|
||||
List<Long> scopedUserIds(AdminUserEntity operator, Long requestedGroupId, ReadScope companyScope) {
|
||||
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
|
||||
|
||||
+12
-4
@@ -88,7 +88,8 @@ public class UserSecretUsageService {
|
||||
|
||||
/**
|
||||
* 后台分页:一行一用户,按日期范围聚合三模块调用次数并计算合计。
|
||||
* 隔离规则同密钥列表:主管只看自己带的「数据权限分组」成员,超管看全量并可按分组筛选;
|
||||
* 隔离规则同密钥列表:超管看全量、可按分组与公司筛选,主管只看自己带的「数据权限分组」成员,
|
||||
* 公司 tab 只**收窄**这条维度、绝不放大主管已看到的集合;
|
||||
* 先全量聚合、再按合计次数倒序内存分页(当前规模可控,量级上来后可改 GROUP BY 下推)。
|
||||
*/
|
||||
public AdminUserSecretUsagePageVo adminPage(AdminUserEntity operator, AdminUserSecretUsageQuery query,
|
||||
@@ -105,11 +106,16 @@ public class UserSecretUsageService {
|
||||
// 空集必须早退:交给下面的 in(...) 会渲染成 IN () → SQL 语法错 → 500。
|
||||
// 两条日志分开,排障时看得出是「筛空」(范围交集为空)还是「查空」(库里没记录)。
|
||||
if (scopedUserIds != null && scopedUserIds.isEmpty()) {
|
||||
// 两条都带 companyScope 的宽度:主管的 base 恒含本人(UserDataScopeSupport:55/:78),
|
||||
// 所以"筛空"在现实里几乎只可能出在公司那一维,日志要答得出是哪一维、范围有多宽。
|
||||
String companyScopeSize = companyScope.isUnfiltered() ? "不筛"
|
||||
: String.valueOf(companyScope.userIds().size());
|
||||
if (superAdmin) {
|
||||
log.info("[user-secret-usage] 用量统计:公司或分组筛后无匹配用户,返回空 operatorId={} groupId={}",
|
||||
operator.getId(), requestedGroupId);
|
||||
log.info("[user-secret-usage] 用量统计:公司或分组筛后无匹配用户,返回空 operatorId={} groupId={} companyScope={}",
|
||||
operator.getId(), requestedGroupId, companyScopeSize);
|
||||
} else {
|
||||
log.info("[user-secret-usage] 用量统计:主管名下无子账户,返回空 operatorId={}", operator.getId());
|
||||
log.info("[user-secret-usage] 用量统计:主管可见集与公司范围交集为空(多为越界 company_id),返回空 operatorId={} companyScope={}",
|
||||
operator.getId(), companyScopeSize);
|
||||
}
|
||||
return emptyPage(page, pageSize, groupOptions(operator, superAdmin));
|
||||
}
|
||||
@@ -214,6 +220,8 @@ public class UserSecretUsageService {
|
||||
* 用量统计的可见用户集:组长锁定 ∩ 超管 group_id ∩ 公司 tab(与密钥列表同形)。
|
||||
* <p>{@code null} = 不筛(超管既没选公司也没选分组);<b>空集由调用方早退</b>,不许交给
|
||||
* {@code LambdaQueryWrapper.in(...)}。交集只在 {@link ReadScope#userIdsOr(java.util.List)} 这一处发生。
|
||||
* <p>非超管这支会再解一次 base:{@code DataReadScope} 出口里已经交过同样的集合,重复求交是幂等的
|
||||
* ({@link ReadScope#userIdsOr}),留着是为了让 service 不依赖出口的内部 ⇒ <b>勿把它当成第二次判公司</b>。
|
||||
*/
|
||||
List<Long> scopedUserIds(AdminUserEntity operator, Long requestedGroupId, ReadScope companyScope) {
|
||||
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
|
||||
|
||||
+122
@@ -1,5 +1,9 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
@@ -23,13 +27,17 @@ import com.nanri.aiimage.modules.usersecret.model.entity.UserApiSecretEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -68,6 +76,8 @@ class UserApiSecretServiceTest {
|
||||
/** 巡检测试用:记录 updateById 写入的 userId → checkStatus 快照。 */
|
||||
private final Map<Long, String> inspectionWrites = new LinkedHashMap<>();
|
||||
private ValueOperations<String, String> valueOps;
|
||||
/** 早退那两条「筛空」日志按角色分开,断言必须挂在 logback 事件上,而不是包内布尔。 */
|
||||
private ListAppender<ILoggingEvent> logEvents;
|
||||
|
||||
private UserApiSecretService newService() {
|
||||
when(crypto.encrypt(anyString())).thenAnswer(inv -> "enc:" + inv.getArgument(0, String.class));
|
||||
@@ -666,9 +676,121 @@ class UserApiSecretServiceTest {
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(88L)).thenReturn(List.of(1L, 2L, 88L));
|
||||
assertThat(service.scopedUserIds(operator, null, ReadScope.users(List.of(2L, 88L))))
|
||||
.containsExactlyInAnyOrder(2L, 88L);
|
||||
// 没选公司 ≠ 放开范围:unfiltered 只表示「不额外按公司筛」,主管仍受分组锁定。
|
||||
assertThat(service.scopedUserIds(operator, null, ReadScope.unfiltered()))
|
||||
.containsExactlyInAnyOrder(1L, 2L, 88L);
|
||||
assertThat(service.scopedUserIds(operator, null, ReadScope.users(List.of()))).isEmpty();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void attachLogAppender() {
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(UserApiSecretService.class);
|
||||
logEvents = new ListAppender<>();
|
||||
logEvents.setContext(logger.getLoggerContext());
|
||||
logEvents.start();
|
||||
logger.addAppender(logEvents);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void detachLogAppender() {
|
||||
((Logger) LoggerFactory.getLogger(UserApiSecretService.class)).detachAppender(logEvents);
|
||||
logEvents.stop();
|
||||
}
|
||||
|
||||
/** 只取 INFO 级、已插值的消息;level 单独断言,避免 warn/error 混进来也能过。 */
|
||||
private List<String> infoMessages() {
|
||||
List<String> messages = new ArrayList<>();
|
||||
for (ILoggingEvent event : logEvents.list) {
|
||||
if (event.getLevel() == Level.INFO) {
|
||||
messages.add(event.getFormattedMessage());
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("超管筛空那条日志:排障要分得清「筛空」还是「查空」,挂错角色等于把排障带偏")
|
||||
void superAdminEmptyByFilterLogsFilterMessageNotLeaderMessage() {
|
||||
UserApiSecretService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(any())).thenReturn("super_admin");
|
||||
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(99L));
|
||||
|
||||
AdminUserSecretQuery query = new AdminUserSecretQuery();
|
||||
query.setGroupId(7L);
|
||||
assertThat(service.adminPage(operator, query, ReadScope.users(List.of(11L))).getItems()).isEmpty();
|
||||
|
||||
assertThat(infoMessages()).anyMatch(m -> m.contains("公司或分组筛后无匹配用户"));
|
||||
assertThat(infoMessages()).noneMatch(m -> m.contains("主管可见集与公司范围交集为空"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("主管无子账户那条走另一支日志:不许和超管的「筛空」混成一条")
|
||||
void leaderWithoutChildrenLogsLeaderMessage() {
|
||||
UserApiSecretService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(88L)).thenReturn(List.of());
|
||||
|
||||
assertThat(service.adminPage(operator, new AdminUserSecretQuery(),
|
||||
ReadScope.users(List.of(11L))).getItems()).isEmpty();
|
||||
|
||||
assertThat(infoMessages()).anyMatch(m -> m.contains("主管可见集与公司范围交集为空"));
|
||||
assertThat(infoMessages()).noneMatch(m -> m.contains("公司或分组筛后无匹配用户"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("算出的范围必须真的下推成 SQL 的 user_id IN:只算不推 = tab 是装饰品,3722 支一支不红")
|
||||
void scopedIdsArePushedIntoTheUserIdInClause() {
|
||||
UserApiSecretService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(any())).thenReturn("super_admin");
|
||||
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(12L, 13L));
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
UserApiSecretEntity.class);
|
||||
|
||||
AdminUserSecretQuery query = new AdminUserSecretQuery();
|
||||
query.setGroupId(7L);
|
||||
// 公司成员集只有 12 ⇒ 分组集 {12,13} 与它取交集后,SQL 里只该出现 12。
|
||||
service.adminPage(operator, query, ReadScope.users(List.of(12L)));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserApiSecretEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper).selectList(captor.capture());
|
||||
LambdaQueryWrapper<UserApiSecretEntity> wrapper = captor.getValue();
|
||||
wrapper.getSqlSegment();
|
||||
assertThat(wrapper.getSqlSegment()).contains("user_id");
|
||||
assertThat(wrapper.getSqlSegment()).contains("IN");
|
||||
assertThat(wrapper.getParamNameValuePairs().values()).contains(12L);
|
||||
assertThat(wrapper.getParamNameValuePairs().values()).doesNotContain(13L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("不传公司=不筛:另一侧的变异「把 null 也当成筛」必须当场红")
|
||||
void missingCompanyLeavesTheQueryUnfiltered() {
|
||||
UserApiSecretService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(any())).thenReturn("super_admin");
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
UserApiSecretEntity.class);
|
||||
|
||||
service.adminPage(operator, new AdminUserSecretQuery(), ReadScope.unfiltered());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserApiSecretEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper).selectList(captor.capture());
|
||||
LambdaQueryWrapper<UserApiSecretEntity> wrapper = captor.getValue();
|
||||
wrapper.getSqlSegment();
|
||||
// 不筛 = wrapper 里没有 user_id 条件,也没有任何账号 id 参数(反向错是静默少行)。
|
||||
assertThat(wrapper.getParamNameValuePairs()).isEmpty();
|
||||
assertThat(wrapper.getSqlSegment()).doesNotContain("user_id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminClearByUserDeletesAllRowsOfUser() {
|
||||
UserApiSecretService service = newService();
|
||||
|
||||
+123
-1
@@ -1,5 +1,13 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.ReadScope;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
@@ -10,10 +18,15 @@ import com.nanri.aiimage.modules.shopkey.model.dto.UserGroupRef;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserSecretUsageMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretUsageQuery;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserSecretUsageEntity;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -31,6 +44,8 @@ class UserSecretUsageServiceTest {
|
||||
private final AdminAuthSupport adminAuthSupport = mock(AdminAuthSupport.class);
|
||||
private final ShopManageGroupMapper adminGroupMapper = mock(ShopManageGroupMapper.class);
|
||||
private final UserDataScopeSupport userDataScopeSupport = mock(UserDataScopeSupport.class);
|
||||
/** 早退那两条「筛空」日志按角色分开,断言必须挂在 logback 事件上,而不是包内布尔。 */
|
||||
private ListAppender<ILoggingEvent> logEvents;
|
||||
|
||||
private UserSecretUsageService newService() {
|
||||
// 默认按主管(admin)判定;超管用例里单独改打桩。
|
||||
@@ -205,7 +220,6 @@ class UserSecretUsageServiceTest {
|
||||
assertThat(service.scopedUserIds(operator, 7L, ReadScope.users(List.of(11L, 12L, 13L))))
|
||||
.containsExactlyInAnyOrder(12L, 13L);
|
||||
|
||||
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(99L));
|
||||
AdminUserSecretUsageQuery query = new AdminUserSecretUsageQuery();
|
||||
query.setGroupId(7L);
|
||||
var page = service.adminPage(operator, query, ReadScope.users(List.of(11L)));
|
||||
@@ -227,4 +241,112 @@ class UserSecretUsageServiceTest {
|
||||
.containsExactlyInAnyOrder(1L, 2L, 88L);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void attachLogAppender() {
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(UserSecretUsageService.class);
|
||||
logEvents = new ListAppender<>();
|
||||
logEvents.setContext(logger.getLoggerContext());
|
||||
logEvents.start();
|
||||
logger.addAppender(logEvents);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void detachLogAppender() {
|
||||
((Logger) LoggerFactory.getLogger(UserSecretUsageService.class)).detachAppender(logEvents);
|
||||
logEvents.stop();
|
||||
}
|
||||
|
||||
/** 只取 INFO 级、已插值的消息:早退那两条日志按角色分开,断言必须挂在 logback 事件上。 */
|
||||
private List<String> infoMessages() {
|
||||
List<String> messages = new ArrayList<>();
|
||||
for (ILoggingEvent event : logEvents.list) {
|
||||
if (event.getLevel() == Level.INFO) {
|
||||
messages.add(event.getFormattedMessage());
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("超管筛空与主管无子账户是两条日志:排障要分得清「筛空」还是「查空」,挂错角色等于把排障带偏")
|
||||
void superAdminEmptyByFilterLogsFilterMessageNotLeaderMessage() {
|
||||
UserSecretUsageService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(any())).thenReturn("super_admin");
|
||||
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(99L));
|
||||
|
||||
AdminUserSecretUsageQuery query = new AdminUserSecretUsageQuery();
|
||||
query.setGroupId(7L);
|
||||
assertThat(service.adminPage(operator, query, ReadScope.users(List.of(11L))).getItems()).isEmpty();
|
||||
|
||||
assertThat(infoMessages()).anyMatch(m -> m.contains("公司或分组筛后无匹配用户"));
|
||||
assertThat(infoMessages()).noneMatch(m -> m.contains("主管可见集与公司范围交集为空"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("主管无子账户那条走另一支日志:不许和超管的「筛空」混成一条")
|
||||
void leaderWithoutChildrenLogsLeaderMessage() {
|
||||
UserSecretUsageService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(88L)).thenReturn(List.of());
|
||||
|
||||
assertThat(service.adminPage(operator, new AdminUserSecretUsageQuery(),
|
||||
ReadScope.users(List.of(11L))).getItems()).isEmpty();
|
||||
|
||||
assertThat(infoMessages()).anyMatch(m -> m.contains("主管可见集与公司范围交集为空"));
|
||||
assertThat(infoMessages()).noneMatch(m -> m.contains("公司或分组筛后无匹配用户"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("算出的范围必须真的下推成 SQL 的 user_id IN:只算不推 = tab 是装饰品,全量绿不能算过")
|
||||
void scopedIdsArePushedIntoTheUserIdInClause() {
|
||||
UserSecretUsageService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(any())).thenReturn("super_admin");
|
||||
when(adminGroupMapper.selectUserIdsByGroupId(7L)).thenReturn(List.of(12L, 13L));
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
UserSecretUsageEntity.class);
|
||||
|
||||
AdminUserSecretUsageQuery query = new AdminUserSecretUsageQuery();
|
||||
query.setGroupId(7L);
|
||||
// 公司成员集只有 12 ⇒ 分组集 {12,13} 与它取交集后,SQL 里只该出现 12。
|
||||
service.adminPage(operator, query, ReadScope.users(List.of(12L)));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserSecretUsageEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(usageMapper).selectList(captor.capture());
|
||||
LambdaQueryWrapper<UserSecretUsageEntity> wrapper = captor.getValue();
|
||||
wrapper.getSqlSegment();
|
||||
assertThat(wrapper.getSqlSegment()).contains("user_id");
|
||||
assertThat(wrapper.getSqlSegment()).contains("IN");
|
||||
assertThat(wrapper.getParamNameValuePairs().values()).contains(12L);
|
||||
assertThat(wrapper.getParamNameValuePairs().values()).doesNotContain(13L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("不传公司=不筛:反向变异「把 null 也当成筛」会让整页变成空白,必须当场红")
|
||||
void missingCompanyLeavesTheQueryUnfiltered() {
|
||||
UserSecretUsageService service = newService();
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(any())).thenReturn("super_admin");
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
UserSecretUsageEntity.class);
|
||||
|
||||
service.adminPage(operator, new AdminUserSecretUsageQuery(), ReadScope.unfiltered());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserSecretUsageEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(usageMapper).selectList(captor.capture());
|
||||
LambdaQueryWrapper<UserSecretUsageEntity> wrapper = captor.getValue();
|
||||
wrapper.getSqlSegment();
|
||||
assertThat(wrapper.getParamNameValuePairs()).isEmpty();
|
||||
assertThat(wrapper.getSqlSegment()).doesNotContain("user_id");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2671,6 +2671,7 @@ git commit -m "docs(公司tab): 批次 0-1 出厂记录 + 批次 2/3 前置闸
|
||||
- **写请求体一律不收 `company_id`**(spec §6.2):三个页的写入口本轮一个参数都不加。⚠️ 但"归属由后端从操作者推导"这半句**只对建号成立**:店铺的 `created_by_id` 今天来自**请求体**(`ShopManageService.java:86` 读 `request.getCreatedById()`)⇒ 店铺归属由"负责人"决定、与 tab 无关(Task 11 Step 4 与 spec §6.3 都已按这条订正)。
|
||||
- **不改 `created_by_id` 的可写性**:不给它加"必须是操作者同公司成员"的校验。那是会 403 现有调用方的行为变更,且超管不在别家的成员集里 ⇒ 加了反而让超管没法把店铺挂到别家名下(今天能做)。
|
||||
- **不补 `/credential?shopName=`(`getCredentialByShopName`)的归属校验**:一期就有的跨公司读点,调用方含内部令牌与客户端登录用户,那里推不出"操作者公司"。本轮只补 `/{id}/credential`(理由见 Task 11 Step 3(d) 那条 ⚠️ 与附A)。要修它是单独一张工单。
|
||||
- **不补密钥管理页那两支按 id 的写出口的归属闸门**:`POST /api/admin/user-secrets/{userId}/check` 与 `DELETE /{userId}`(`AdminUserApiSecretController:72-89`)把 `requireAdmin(request)` 的返回值直接丢掉,service 侧 `adminCheckByUser(userId)` / `adminClearByUser(userId)` 不收操作者 —— 一期就没有闸门。本轮把那页的**读**接进公司 tab 之后,它成了同一页里唯一还开着的越权写点(别家管理员可一键清空任意 userId 的密钥,`check` 还会真打 LLM 与代理配额)。补它 = 给写侧加一条会 403 的校验,属未批的行为变更 ⇒ 单独一张工单。(Task 9 评审 I-1,2026-10-05 记)
|
||||
- **不重写 `listAccessibleGroupIds` / `listAccessible`**:非超管的分组可见口径不动(spec §13)。⇒ 本计划对非超管的跨公司保证,只在**真正经过 `DataReadScope` 的那几支列表**上成立,是**部分强度**(与二期 §9.4 同词)。验收时别把它说成"非超管已按公司锁死"。
|
||||
- 不做"tab 值进 URL / 可分享链接带公司上下文"(spec §12 第 4 条)。
|
||||
- 不碰二期的 V145 迁移文件(已在 `b7873209` 提交,本计划不改它、不替它决定上线时机——上线时机是 Task 13 Step 2 那条要用户拍板的显式决定)。
|
||||
|
||||
Reference in New Issue
Block a user