- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14) - T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9) - T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4) - T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8) - T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15) - T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8) - T7 前后端测试与 lint 门禁清零 - T8 应付卡片按关联订单日(口径 A) - T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
239 lines
9.9 KiB
TypeScript
239 lines
9.9 KiB
TypeScript
import express from 'express';
|
||
import request from 'supertest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* T3 Addendum · B-01 独立复测(2026-10-19,tester;task-3 rev6)。
|
||
*
|
||
* 攻破面:`/api/roles` 已限 super_admin,但通用数据网关 `/api/data/query|batch` 仍可写
|
||
* `role_permissions` / `role_definitions` ⇒ 分公司 admin 可直接写全局授权表(垂直提权)。
|
||
* 修复:两张表进 `DENY_WRITE_TABLES`(所有人、含 super_admin 一律 403,写只能走 `/api/roles`)。
|
||
*
|
||
* 本文件独立于 dev 的 `dataGatewayRoleTablesDeny.test.ts`,重点补它没覆盖的:
|
||
* a) **`/api/data/batch` 不能绕过**(单条 + 混合批);b) super_admin 经 query/batch 同样 403,
|
||
* 而 `/api/roles` 仍 200/201;c) admin select 仍 200 + 前端 useAuth 只 select。
|
||
*/
|
||
|
||
const H = vi.hoisted(() => ({
|
||
ctx: null as Record<string, unknown> | null,
|
||
currentUserId: 'admin-user',
|
||
poolQuery: vi.fn(),
|
||
poolConnect: vi.fn(),
|
||
sqlLog: [] as string[],
|
||
clientSql: [] as string[],
|
||
createRole: vi.fn(),
|
||
listRoles: vi.fn(),
|
||
deleteRole: vi.fn(),
|
||
}));
|
||
|
||
vi.mock('../src/middleware/auth', () => ({
|
||
authMiddleware: (req: { userId?: string; tokenScope?: string }, _res: unknown, next: () => void) => {
|
||
req.userId = H.currentUserId;
|
||
req.tokenScope = 'web';
|
||
next();
|
||
},
|
||
}));
|
||
|
||
vi.mock('../src/services/tenantScope', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/tenantScope')>();
|
||
return { ...actual, loadTenantContext: async () => H.ctx, invalidateTenantContextCache: () => undefined };
|
||
});
|
||
|
||
vi.mock('../src/db', () => {
|
||
const log = (args: unknown[]) => {
|
||
const text = typeof args[0] === 'string' ? String(args[0]) : String((args[0] as { text?: string })?.text || '');
|
||
H.sqlLog.push(text);
|
||
return text;
|
||
};
|
||
const poolQuery = (...args: unknown[]) => {
|
||
log(args);
|
||
return H.poolQuery(...args);
|
||
};
|
||
const clientQuery = (...args: unknown[]) => {
|
||
log(args);
|
||
H.clientSql.push(String(args[0]));
|
||
return H.poolQuery(...args);
|
||
};
|
||
return {
|
||
pool: { query: poolQuery, connect: (...args: unknown[]) => H.poolConnect(...args) },
|
||
query: poolQuery,
|
||
getRawPoolQuery: () => poolQuery,
|
||
getRawPoolConnect: () => vi.fn(),
|
||
applyBranchRlsToClient: async () => undefined,
|
||
isRlsRoleAvailable: async () => false,
|
||
allowRlsFailOpen: () => true,
|
||
warmRlsRoleCache: async () => undefined,
|
||
};
|
||
});
|
||
|
||
vi.mock('../src/services/roleDefinitionService', () => ({
|
||
createRoleDefinition: (...args: unknown[]) => H.createRole(...args),
|
||
deleteRoleDefinition: (...args: unknown[]) => H.deleteRole(...args),
|
||
listRoleDefinitions: (...args: unknown[]) => H.listRoles(...args),
|
||
}));
|
||
|
||
vi.mock('../src/services/permissionCatalogService', () => ({
|
||
listPermissions: async () => [],
|
||
}));
|
||
|
||
const { default: dataRoutes } = await import('../src/routes/data');
|
||
const { default: rolesRoutes } = await import('../src/routes/roles');
|
||
|
||
const app = express();
|
||
app.use(express.json());
|
||
app.use('/api/data', dataRoutes);
|
||
app.use('/api/roles', rolesRoutes);
|
||
|
||
const ADMIN = {
|
||
userId: 'admin-b01',
|
||
roles: ['admin'],
|
||
permissions: ['role_manage', 'user_manage'],
|
||
branchCode: 'BR002',
|
||
supplierCode: null,
|
||
purchaserCode: null,
|
||
isSuperAdmin: false,
|
||
isBranchAdmin: true,
|
||
isInternalStaff: true,
|
||
isSupplierAccount: false,
|
||
};
|
||
const SUPER = {
|
||
...ADMIN,
|
||
userId: 'super-b01',
|
||
roles: ['super_admin'],
|
||
isSuperAdmin: true,
|
||
isBranchAdmin: false,
|
||
};
|
||
|
||
const ROLES_BY_USER: Record<string, string[]> = { 'admin-b01': ['admin'], 'super-b01': ['super_admin'] };
|
||
|
||
function roleTableWrites(sqls: string[]): string[] {
|
||
return sqls.filter((sql) => /(INSERT|UPDATE|DELETE)[\s\S]{0,160}(role_permissions|role_definitions)/i.test(sql));
|
||
}
|
||
|
||
beforeEach(() => {
|
||
H.ctx = ADMIN;
|
||
H.currentUserId = 'admin-b01';
|
||
H.poolQuery.mockReset();
|
||
H.poolConnect.mockReset();
|
||
H.createRole.mockReset();
|
||
H.listRoles.mockReset();
|
||
H.deleteRole.mockReset();
|
||
H.sqlLog = [];
|
||
H.clientSql = [];
|
||
H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM user_roles WHERE user_id = $1')) {
|
||
const roles = ROLES_BY_USER[String(params[0])] || [];
|
||
return { rows: roles.map((role) => ({ role })), rowCount: roles.length, fields: [] };
|
||
}
|
||
return { rows: [], rowCount: 0, fields: [] };
|
||
});
|
||
H.poolConnect.mockImplementation(async () => ({
|
||
query: async (sql: string) => {
|
||
H.clientSql.push(String(sql));
|
||
return { rows: [], rowCount: 0, fields: [] };
|
||
},
|
||
release: () => undefined,
|
||
}));
|
||
H.createRole.mockResolvedValue({ role_code: 'custom_role', role_name: '自定义' });
|
||
H.listRoles.mockResolvedValue([{ role_code: 'operator', role_name: '操作员' }]);
|
||
H.deleteRole.mockResolvedValue(undefined);
|
||
});
|
||
|
||
describe('B-01a:admin 经 /api/data/batch 写全局授权表 ⇒ 403 且零写/零连接', () => {
|
||
const CASES: Array<{ table: string; action: 'insert' | 'update' | 'delete'; op: Record<string, unknown> }> = [
|
||
{ table: 'role_permissions', action: 'insert', op: { table: 'role_permissions', action: 'insert', insertData: { role: 'super_admin', permission_id: 'p1' } } },
|
||
{ table: 'role_permissions', action: 'update', op: { table: 'role_permissions', action: 'update', updateData: { permission_id: 'p2' }, filters: [{ column: 'role', op: 'eq', value: 'operator' }] } },
|
||
{ table: 'role_permissions', action: 'delete', op: { table: 'role_permissions', action: 'delete', filters: [{ column: 'role', op: 'eq', value: 'operator' }] } },
|
||
{ table: 'role_definitions', action: 'insert', op: { table: 'role_definitions', action: 'insert', insertData: { role_code: 'evil', role_name: 'evil' } } },
|
||
{ table: 'role_definitions', action: 'update', op: { table: 'role_definitions', action: 'update', updateData: { role_name: 'x' }, filters: [{ column: 'role_code', op: 'eq', value: 'operator' }] } },
|
||
{ table: 'role_definitions', action: 'delete', op: { table: 'role_definitions', action: 'delete', filters: [{ column: 'role_code', op: 'eq', value: 'operator' }] } },
|
||
];
|
||
|
||
for (const one of CASES) {
|
||
it(`admin batch ${one.action} ${one.table} ⇒ 403`, async () => {
|
||
const res = await request(app).post('/api/data/batch').send({ operations: [one.op] });
|
||
expect(res.status).toBe(403);
|
||
expect(String(res.body?.error?.code)).toBe('forbidden');
|
||
expect(H.poolConnect, 'batch 策略必须在取连接之前拒绝').not.toHaveBeenCalled();
|
||
expect(H.clientSql).toEqual([]);
|
||
expect(roleTableWrites(H.sqlLog)).toEqual([]);
|
||
});
|
||
}
|
||
|
||
it('混合批(先合法表、后全局授权表)⇒ 整批 403,合法操作也不得先落库', async () => {
|
||
const res = await request(app)
|
||
.post('/api/data/batch')
|
||
.send({
|
||
operations: [
|
||
{ table: 'notifications', action: 'update', updateData: { is_read: true }, filters: [{ column: 'id', op: 'eq', value: 'n-1' }] },
|
||
{ table: 'role_permissions', action: 'insert', insertData: { role: 'super_admin', permission_id: 'p1' } },
|
||
],
|
||
});
|
||
expect(res.status).toBe(403);
|
||
expect(H.poolConnect).not.toHaveBeenCalled();
|
||
expect(H.clientSql).toEqual([]);
|
||
expect(roleTableWrites(H.sqlLog)).toEqual([]);
|
||
});
|
||
});
|
||
|
||
describe('B-01b:super_admin 经网关同样 403,但 /api/roles 仍可用', () => {
|
||
beforeEach(() => {
|
||
H.ctx = SUPER;
|
||
H.currentUserId = 'super-b01';
|
||
});
|
||
|
||
it('super_admin /api/data/query insert role_permissions ⇒ 403 + 零写 SQL', async () => {
|
||
const res = await request(app)
|
||
.post('/api/data/query')
|
||
.send({ table: 'role_permissions', action: 'insert', insertData: { role: 'operator', permission_id: 'p1' } });
|
||
expect(res.status).toBe(403);
|
||
expect(String(res.body?.error?.code)).toBe('forbidden');
|
||
expect(roleTableWrites(H.sqlLog)).toEqual([]);
|
||
});
|
||
|
||
it('super_admin /api/data/batch 写 role_definitions ⇒ 403 + 零连接/零写', async () => {
|
||
const res = await request(app)
|
||
.post('/api/data/batch')
|
||
.send({ operations: [{ table: 'role_definitions', action: 'delete', filters: [{ column: 'role_code', op: 'eq', value: 'operator' }] }] });
|
||
expect(res.status).toBe(403);
|
||
expect(H.poolConnect).not.toHaveBeenCalled();
|
||
expect(roleTableWrites(H.sqlLog)).toEqual([]);
|
||
});
|
||
|
||
it('走 /api/roles:GET 200、POST 201(super_admin 正常路径保留)', async () => {
|
||
const get = await request(app).get('/api/roles');
|
||
expect(get.status).toBe(200);
|
||
expect(H.listRoles).toHaveBeenCalled();
|
||
|
||
const post = await request(app).post('/api/roles').send({ role_code: 'custom_role', role_name: '自定义' });
|
||
expect(post.status).toBe(201);
|
||
expect(H.createRole).toHaveBeenCalledWith('custom_role', '自定义');
|
||
});
|
||
});
|
||
|
||
describe('B-01c:读不回归 + 前端只读', () => {
|
||
it('admin select role_permissions 经 /api/data/query 仍 200,且确实发出 SELECT', async () => {
|
||
const res = await request(app)
|
||
.post('/api/data/query')
|
||
.send({ table: 'role_permissions', action: 'select', select: 'role,permission_id', limit: 50 });
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.error).toBeFalsy();
|
||
expect(H.sqlLog.some((sql) => /SELECT[\s\S]*FROM role_permissions/i.test(sql))).toBe(true);
|
||
expect(roleTableWrites(H.sqlLog)).toEqual([]);
|
||
});
|
||
|
||
it('前端 useAuth 只对 role_permissions 做 select(无 insert/update/delete/upsert)', () => {
|
||
const src = readFileSync(path.join(__dirname, '../../src/hooks/useAuth.tsx'), 'utf8');
|
||
const fromRole = src.indexOf(".from('role_permissions')");
|
||
expect(fromRole).toBeGreaterThan(-1);
|
||
const tail = src.slice(fromRole, fromRole + 260);
|
||
expect(tail).toContain('.select(');
|
||
expect(tail).toContain(".in('role'");
|
||
expect(src).not.toMatch(/from\(['"]role_permissions['"]\)\s*\.(insert|update|delete|upsert)/);
|
||
expect(src).not.toMatch(/\.(insert|update|delete|upsert)\(\s*\)\s*[\s\S]{0,40}role_permissions/);
|
||
});
|
||
});
|