Compare commits
2 Commits
d2977a308c
...
a372560818
| Author | SHA1 | Date | |
|---|---|---|---|
| a372560818 | |||
| 0f3fd3e0ec |
@@ -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 里不读任何归一化/构造出来的中间对象',
|
||||
},
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import test, { type TestContext } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
|
||||
/**
|
||||
* 到期续费提醒的端到端用例(V146,2026-10-05 需求)。
|
||||
*
|
||||
* 验的是弹窗唯一的判据来源——`/api/admin/current-user` 的 `daysToExpire`,以及
|
||||
* 到期后登录被拦这条出口;弹窗本身是纯前端渲染,由 tests/expiry-notice.test.ts 钉。
|
||||
*
|
||||
* 生命周期:建号(临期) → 登录取 current-user 断言 <5 → 续费到 10 天 → 断言 ≥5
|
||||
* → 手工置为过去时间 → 登录应被拒 → 删号清理。
|
||||
* 只在带**后台角色**凭据时跑(AIIMAGE_LIVE_USER/PASS):角色不足会带诊断跳过,
|
||||
* 因为"缺凭据"和"功能坏了"混成一条红,下一轮就没人信这支了。
|
||||
* 创建的账号带 acc_expiry_live_ 前缀、当场删除,口令每次随机生成且不落盘。
|
||||
*/
|
||||
|
||||
const BASE = process.env.AIIMAGE_LIVE_BASE || 'http://127.0.0.1:18080'
|
||||
const USER = process.env.AIIMAGE_LIVE_USER || ''
|
||||
const PASS = process.env.AIIMAGE_LIVE_PASS || ''
|
||||
const HAS_CREDS = Boolean(USER && PASS)
|
||||
/** 临时号的口令:随机、只在本次进程内存里,绝不写进仓库(写死一个弱口令=在产线留后门)。 */
|
||||
const ADMIN_PASS = randomBytes(18).toString('base64url')
|
||||
|
||||
function authHeader(token: string): Record<string, string> {
|
||||
return { Authorization: `Bearer ${token}` }
|
||||
}
|
||||
|
||||
async function login(username: string, password: string, deviceId: string) {
|
||||
const res = await fetch(`${BASE}/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password, deviceId }),
|
||||
})
|
||||
const body = (await res.json()) as {
|
||||
success?: boolean
|
||||
code?: number
|
||||
message?: string
|
||||
data?: { token?: string; role?: string }
|
||||
}
|
||||
return { res, body }
|
||||
}
|
||||
|
||||
/** yyyy-MM-dd HH:mm,与后端 CREATED_AT_FORMATTER/expiresAt 入参同形。 */
|
||||
function fmt(dt: Date): string {
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${dt.getFullYear()}-${p(dt.getMonth() + 1)}-${p(dt.getDate())} ${p(dt.getHours())}:${p(dt.getMinutes())}`
|
||||
}
|
||||
|
||||
function daysFromNow(days: number): string {
|
||||
return fmt(new Date(Date.now() + days * 86_400_000))
|
||||
}
|
||||
|
||||
type Operator = { token: string; role: string }
|
||||
let operatorCache: Operator | null = null
|
||||
|
||||
async function operator(): Promise<Operator> {
|
||||
if (operatorCache) return operatorCache
|
||||
const { res, body } = await login(USER, PASS, 'claude-expiry-live-operator')
|
||||
assert.equal(body.success, true, `操作账号登录应成功: ${body.message || res.status}`)
|
||||
const token = body.data?.token
|
||||
assert.ok(token, '登录应下发 token')
|
||||
operatorCache = { token: token as string, role: String(body.data?.role || '') }
|
||||
return operatorCache
|
||||
}
|
||||
|
||||
/**
|
||||
* 角色闸门:普通账号(role=normal)拿不到 /api/admin/*,那类 403 是权限不是缺陷。
|
||||
* 返回 null 表示"本用例在缺后台凭据的环境里跑不了",调用方必须立刻 return——
|
||||
* t.skip() 之后 body 仍会继续执行,留着断言就会把环境问题报成功能红。
|
||||
*/
|
||||
async function requireRole(t: TestContext, need: string[]): Promise<Operator | null> {
|
||||
const op = await operator()
|
||||
if (!need.includes(op.role)) {
|
||||
t.skip(`凭据角色=${op.role || '<空>'},本用例需要 ${need.join('/')};缺后台凭据不等于功能坏了`)
|
||||
return null
|
||||
}
|
||||
return op
|
||||
}
|
||||
|
||||
test('test_expiry_live_super_admin_has_no_notice', { skip: !HAS_CREDS }, async (t) => {
|
||||
// 超管自身不设到期 ⇒ daysToExpire 为 null ⇒ 弹窗不该出现(需求只针对"快过期的管理员")。
|
||||
const op = await requireRole(t, ['super_admin'])
|
||||
if (!op) return
|
||||
const res = await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(op.token) })
|
||||
const body = (await res.json()) as { success?: boolean; data?: Record<string, unknown> }
|
||||
assert.equal(body.success, true)
|
||||
assert.ok(body.data && 'daysToExpire' in body.data, 'current-user 必须带 daysToExpire 字段(弹窗的数据源)')
|
||||
assert.equal(body.data?.daysToExpire, null, `超管不该有到期天数: ${JSON.stringify(body.data?.daysToExpire)}`)
|
||||
})
|
||||
|
||||
test('test_expiry_live_notice_then_renew_then_expire', { skip: !HAS_CREDS }, async (t) => {
|
||||
const op = await requireRole(t, ['super_admin'])
|
||||
if (!op) return
|
||||
const token = op.token
|
||||
const username = `acc_expiry_live_${Date.now()}`
|
||||
let createdId: number | null = null
|
||||
try {
|
||||
// 1) 建一个"剩余不足 5 天"的管理员(临期 +2 天)
|
||||
const create = await fetch(`${BASE}/api/admin/user`, {
|
||||
method: 'POST',
|
||||
headers: { ...authHeader(token), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password: ADMIN_PASS, role: 'admin', expiresAt: daysFromNow(2) }),
|
||||
})
|
||||
const created = (await create.json()) as { success?: boolean; message?: string; data?: number }
|
||||
assert.equal(created.success, true, `建号应成功: ${created.message || create.status}`)
|
||||
createdId = created.data as number
|
||||
assert.equal(typeof createdId, 'number')
|
||||
|
||||
// 2) 以该账号登录取 current-user:daysToExpire 必须落进弹窗触发区间 [0,5)
|
||||
const near = await login(username, ADMIN_PASS, 'claude-expiry-live-self')
|
||||
assert.equal(near.body.success, true, `临期账号此刻仍可登录: ${near.body.message || ''}`)
|
||||
const nearToken = near.body.data?.token as string
|
||||
const cu = (await (await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(nearToken) })).json()) as {
|
||||
data?: { daysToExpire?: number | null; expiresAt?: string | null }
|
||||
}
|
||||
assert.equal(typeof cu.data?.daysToExpire, 'number', `临期应给出天数: ${JSON.stringify(cu.data)}`)
|
||||
assert.ok((cu.data?.daysToExpire as number) >= 0 && (cu.data?.daysToExpire as number) < 5,
|
||||
`daysToExpire 应落在弹窗触发区间 [0,5),实际 ${cu.data?.daysToExpire}`)
|
||||
|
||||
// 3) 续费到 10 天 ⇒ 超过阈值,弹窗消失(需求:"直到续费超过5天才消失")
|
||||
const renew = await fetch(`${BASE}/api/admin/user/${createdId}`, {
|
||||
method: 'PUT',
|
||||
headers: { ...authHeader(token), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ expiresAt: daysFromNow(10) }),
|
||||
})
|
||||
const renewed = (await renew.json()) as { success?: boolean; message?: string }
|
||||
assert.equal(renewed.success, true, `续费应成功: ${renewed.message || renew.status}`)
|
||||
const cu2 = (await (await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(nearToken) })).json()) as {
|
||||
data?: { daysToExpire?: number | null }
|
||||
}
|
||||
assert.ok(typeof cu2.data?.daysToExpire === 'number' && (cu2.data?.daysToExpire as number) >= 5,
|
||||
`续费后应 ≥5 天(弹窗不再出现),实际 ${cu2.data?.daysToExpire}`)
|
||||
|
||||
// 4) 置为过去时间 = 手工停用 ⇒ 登录被拦、给出续费文案(403 走响应体 biz code)
|
||||
const expire = await fetch(`${BASE}/api/admin/user/${createdId}`, {
|
||||
method: 'PUT',
|
||||
headers: { ...authHeader(token), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ expiresAt: fmt(new Date(Date.now() - 86_400_000)) }),
|
||||
})
|
||||
assert.equal(((await expire.json()) as { success?: boolean }).success, true, '置为过去时间应成功')
|
||||
const blocked = await login(username, ADMIN_PASS, 'claude-expiry-live-blocked')
|
||||
assert.notEqual(blocked.body.success, true, '已过期账号不该登录成功')
|
||||
assert.equal(blocked.body.code, 403, `到期拦截应是 403,实际 code=${blocked.body.code}`)
|
||||
assert.ok(/续费|过期/.test(blocked.body.message || ''), `文案应指向续费,实际 "${blocked.body.message}"`)
|
||||
|
||||
// 5) 老会话也要被拦(每请求鉴权走 401,前端按下线处理)
|
||||
const stale = await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(nearToken) })
|
||||
const staleBody = (await stale.json()) as { success?: boolean; code?: number }
|
||||
assert.notEqual(staleBody.success, true, '过期账号的既有会话不该继续可用')
|
||||
assert.equal(staleBody.code, 401, `会话拦截应是 401,实际 code=${staleBody.code}`)
|
||||
} finally {
|
||||
if (createdId !== null) {
|
||||
const del = await fetch(`${BASE}/api/admin/user/${createdId}`, {
|
||||
method: 'DELETE',
|
||||
headers: authHeader(token),
|
||||
})
|
||||
const gone = (await del.json()) as { success?: boolean; message?: string }
|
||||
assert.equal(gone.success, true, `清理账号应成功: ${gone.message || del.status}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
+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