- 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 超长修复
157 lines
6.0 KiB
TypeScript
157 lines
6.0 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';
|
||
|
||
/**
|
||
* SEC-4 绕过修复(B-01,2026-10-19 红队复攻):通用数据网关不得写全局授权表。
|
||
*
|
||
* 漏洞:`/api/roles` 已只允许 super_admin,但任意分公司 admin 仍可 POST `/api/data/query`
|
||
* 对 `role_permissions`(以及 `role_definitions`)insert/update/delete —— 实测 HTTP 200 + 真实
|
||
* 写 SQL,等于绕过 SEC-4,甚至可给 super_admin 写权限。
|
||
*
|
||
* 修复:两张表加入 `DENY_WRITE_TABLES`(所有账号、含 super_admin,一律走 `/api/roles`),
|
||
* 并从 `ADMIN_WRITE_TABLES` 移除;读取(前端 useAuth 的 select)不受影响。
|
||
*/
|
||
|
||
const H = vi.hoisted(() => ({
|
||
ctx: null as Record<string, unknown> | null,
|
||
query: vi.fn(),
|
||
sqlLog: [] as string[],
|
||
}));
|
||
|
||
vi.mock('../src/middleware/auth', () => ({
|
||
authMiddleware: (req: { userId?: string; tokenScope?: string }, _res: unknown, next: () => void) => {
|
||
req.userId = String((H.ctx as { userId?: string })?.userId || 'user-1');
|
||
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,
|
||
};
|
||
});
|
||
|
||
vi.mock('../src/db', () => {
|
||
const query = (...args: unknown[]) => {
|
||
const text = typeof args[0] === 'string' ? String(args[0]) : String((args[0] as { text?: string })?.text || '');
|
||
H.sqlLog.push(text);
|
||
return H.query(...args);
|
||
};
|
||
return {
|
||
pool: { query, connect: vi.fn(async () => ({ query, release: () => undefined })) },
|
||
query,
|
||
getRawPoolQuery: () => query,
|
||
getRawPoolConnect: () => vi.fn(),
|
||
applyBranchRlsToClient: async () => undefined,
|
||
isRlsRoleAvailable: async () => false,
|
||
allowRlsFailOpen: () => true,
|
||
warmRlsRoleCache: async () => undefined,
|
||
};
|
||
});
|
||
|
||
const { default: dataRoutes } = await import('../src/routes/data');
|
||
|
||
const app = express();
|
||
app.use(express.json());
|
||
app.use('/api/data', dataRoutes);
|
||
|
||
const ADMIN_CTX = {
|
||
userId: 'admin-user',
|
||
roles: ['admin'],
|
||
permissions: ['role_manage', 'user_manage'],
|
||
branchCode: 'BR002',
|
||
supplierCode: null,
|
||
purchaserCode: null,
|
||
isSuperAdmin: false,
|
||
isBranchAdmin: true,
|
||
isInternalStaff: true,
|
||
isSupplierAccount: false,
|
||
};
|
||
const SUPER_CTX = { ...ADMIN_CTX, userId: 'super-user', roles: ['super_admin'], isSuperAdmin: true, isBranchAdmin: false };
|
||
|
||
function writeSqlLog(): string[] {
|
||
return H.sqlLog.filter((sql) =>
|
||
/(INSERT|UPDATE|DELETE)[\s\S]{0,120}(role_permissions|role_definitions)/i.test(sql)
|
||
);
|
||
}
|
||
|
||
beforeEach(() => {
|
||
H.ctx = ADMIN_CTX;
|
||
H.query.mockReset();
|
||
H.sqlLog = [];
|
||
H.query.mockResolvedValue({ rows: [], rowCount: 0, fields: [] });
|
||
});
|
||
|
||
describe('B-01:网关写全局授权表一律 403', () => {
|
||
const WRITE_CASES: Array<{ table: string; action: 'insert' | 'update' | 'delete' }> = [
|
||
{ table: 'role_permissions', action: 'insert' },
|
||
{ table: 'role_permissions', action: 'update' },
|
||
{ table: 'role_permissions', action: 'delete' },
|
||
{ table: 'role_definitions', action: 'insert' },
|
||
{ table: 'role_definitions', action: 'update' },
|
||
{ table: 'role_definitions', action: 'delete' },
|
||
];
|
||
|
||
for (const one of WRITE_CASES) {
|
||
it(`admin ${one.action} ${one.table} ⇒ 403 且零写 SQL`, async () => {
|
||
const body: Record<string, unknown> = { table: one.table, action: one.action };
|
||
if (one.action === 'insert') body.insertData = { role: 'super_admin', permission_id: 'p1' };
|
||
if (one.action === 'update') body.updateData = { permission_id: 'p1' };
|
||
if (one.action === 'delete') body.filters = [{ column: 'role', op: 'eq', value: 'operator' }];
|
||
|
||
const res = await request(app).post('/api/data/query').send(body);
|
||
expect(res.status).toBe(403);
|
||
expect(JSON.stringify(res.body)).toContain('不允许通过数据接口写入');
|
||
expect(writeSqlLog()).toEqual([]);
|
||
});
|
||
}
|
||
|
||
it('super_admin 经网关写同样被 deny(应走 /api/roles,保留审计与事务)', async () => {
|
||
H.ctx = SUPER_CTX;
|
||
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(writeSqlLog()).toEqual([]);
|
||
});
|
||
|
||
it('读取不受影响:admin select role_permissions 仍 200(前端 useAuth 只读)', async () => {
|
||
const res = await request(app)
|
||
.post('/api/data/query')
|
||
.send({ table: 'role_permissions', action: 'select', select: '*', limit: 10 });
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.error).toBeFalsy();
|
||
expect(H.sqlLog.some((sql) => /FROM role_permissions/i.test(sql))).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe('B-01:策略源码契约(deny 覆盖两张表,ADMIN_WRITE 不再含 role_permissions)', () => {
|
||
const source = readFileSync(path.join(__dirname, '../src/services/accessPolicy.ts'), 'utf8');
|
||
const denyBlock = source.slice(source.indexOf('const DENY_WRITE_TABLES'), source.indexOf('const DENY_DELETE_TABLES'));
|
||
const adminBlock = source.slice(
|
||
source.indexOf('const ADMIN_WRITE_TABLES'),
|
||
source.indexOf('/**', source.indexOf('const ADMIN_WRITE_TABLES'))
|
||
);
|
||
|
||
it('DENY_WRITE_TABLES 含 role_permissions + role_definitions', () => {
|
||
expect(denyBlock).toContain("'role_permissions'");
|
||
expect(denyBlock).toContain("'role_definitions'");
|
||
});
|
||
|
||
it('ADMIN_WRITE_TABLES 不再含 role_permissions', () => {
|
||
expect(adminBlock).not.toContain("'role_permissions'");
|
||
});
|
||
|
||
it('前端 useAuth 只对 role_permissions 做 select(无写调用)', () => {
|
||
const ui = readFileSync(path.join(__dirname, '../../src/hooks/useAuth.tsx'), 'utf8');
|
||
expect(ui).toContain('role_permissions');
|
||
expect(ui).not.toMatch(/from\(['"]role_permissions['"]\)\s*\.(insert|update|delete|upsert)/);
|
||
});
|
||
});
|