Files
SupplierSystem/server/tests/userRoleAssignmentGuard.test.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

60 lines
3.0 KiB
TypeScript

/**
* 用户角色授予守卫 —— 防止「零角色账号」再次产生,并锁住 roles 的可选语义。
*
* 起因(2026-09-16 账号 × 角色权限 × 分公司 梳理):
* 生产有 9 个「零角色账号」—— 能登录、但没有任何权限、没有任何可进页面。
* 根因是 POST /api/auth/admin/users 建号时 `for (const role of roles)` 没有最小角色校验,
* 而 normalizeRoles 对非法/空输入静默返回 [];PUT 那边则把「未传 roles」与「传空 roles」
* 都折成 [],导致「只改姓名/密码」也会被当成无角色(超管账号还会因此撞 400)。
*
* 本测试以源码契约方式锁住修复后的语义(仓库既有的 webPurchaseListOwnScope.test.ts 同风格)。
*/
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
const REPO_ROOT = path.join(__dirname, '../..');
const AUTH_SRC = readFileSync(path.join(REPO_ROOT, 'server/src/routes/auth.ts'), 'utf8');
const WEB_USER_MGMT = readFileSync(
path.join(REPO_ROOT, 'src/pages/system/UserManagement.tsx'),
'utf8'
);
describe('用户角色授予守卫', () => {
it('存在共用校验:建号/改号必须至少一个角色', () => {
expect(AUTH_SRC).toContain('function assertHasRole(');
// 客户门户(customer)已于 2026-09-17 彻底下线,不再有「零角色例外」
});
it('建号(POST /admin/users)必须校验角色非空', () => {
const post = AUTH_SRC.slice(
AUTH_SRC.indexOf("router.post('/admin/users'"),
AUTH_SRC.indexOf("router.post('/admin/branches'")
);
expect(post).toContain('assertHasRole(');
// 校验必须先于建号
expect(post.indexOf('assertHasRole(')).toBeLessThan(
post.indexOf('await createAuthUser(')
);
});
it('改号(PUT /admin/users/:id)区分「未传 roles」与「传空 roles」', () => {
const put = AUTH_SRC.slice(AUTH_SRC.indexOf("router.put('/admin/users/:id'"));
// 显式判定是否传了 roles
expect(put).toContain('Array.isArray(req.body?.roles)');
expect(put).toContain('rolesProvided');
// 未传时必须以库中现有角色为准(否则超管账号会被下面的分公司校验误判成 400)
expect(put).toMatch(/rolesProvided[\s\S]{0,200}SELECT role::text AS role FROM public\.user_roles/);
// 只在显式传入时才重设角色 —— 不得再退回 `roles.length > 0` 的旧写法
expect(put).toMatch(/if \(rolesProvided\) \{\s*await client\.query\(`DELETE FROM public\.user_roles/);
expect(put).not.toMatch(/if \(roles\.length > 0\) \{\s*await client\.query\(`DELETE FROM public\.user_roles/);
// 显式传空角色时同样走共用校验
expect(put).toMatch(/if \(rolesProvided\) \{\s*assertHasRole\(/);
});
it('变更后必须使该用户租户上下文缓存失效(角色/分公司/绑定都可能变)', () => {
const put = AUTH_SRC.slice(AUTH_SRC.indexOf("router.put('/admin/users/:id'"));
expect(put).toContain('invalidateTenantContextCache(userId)');
});
});