- 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 超长修复
234 lines
9.7 KiB
TypeScript
234 lines
9.7 KiB
TypeScript
import { Client } from 'pg';
|
||
import request from 'supertest';
|
||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* T9F(2026-10-19,tester 独立补测):
|
||
* F1 通用数据网关禁写「存储对象 key」列(inspection_photos/photo_url/…/file_paths);
|
||
* F2 finalize 源对象为 `archive/*` ⇒ 403(任何归档都不能作为待归档源被读/复制/删);
|
||
* F3 验收照片删除/移动端删图:DB 行含 `archive/BR002/...` ⇒ 跳过删除(源对象保留);
|
||
* F4 付款凭证抽取读前归属校验:跨分支 `BR002/free-cost-payment/x` ⇒ 403。
|
||
*
|
||
* 真实 app + 真实 DB(in-process),storageProvider 在需要处 mock 以断言「未被调用」。
|
||
*/
|
||
|
||
const H = vi.hoisted(() => ({
|
||
getObject: vi.fn(async () => ({ buffer: Buffer.from('img'), contentType: 'image/jpeg' })),
|
||
putObject: vi.fn(async () => undefined),
|
||
deleteObject: vi.fn(async () => undefined),
|
||
exists: vi.fn(async () => true),
|
||
}));
|
||
|
||
vi.mock('../src/services/storageProvider', () => ({
|
||
getStorageProvider: () => ({
|
||
getObject: (...a: unknown[]) => H.getObject(...a),
|
||
putObject: (...a: unknown[]) => H.putObject(...a),
|
||
deleteObject: (...a: unknown[]) => H.deleteObject(...a),
|
||
exists: (...a: unknown[]) => H.exists(...a),
|
||
}),
|
||
}));
|
||
|
||
const DB_URL = (() => {
|
||
try {
|
||
return fs.readFileSync('.env', 'utf8').match(/^DATABASE_URL=(.*)$/m)?.[1]?.trim() || '';
|
||
} catch {
|
||
return '';
|
||
}
|
||
})();
|
||
|
||
let app: any;
|
||
let db: Client;
|
||
let tokenAdmin = '';
|
||
let tokenSuper = '';
|
||
let skipReason = '';
|
||
const fixtureIds: string[] = [];
|
||
|
||
async function login(username: string): Promise<string> {
|
||
const r = await request(app).post('/api/auth/token').send({ username, password: '123456' });
|
||
return String(r.body?.access_token || '');
|
||
}
|
||
|
||
async function insertInspection(photos: string[], inspected: boolean): Promise<string> {
|
||
await db.query('BEGIN');
|
||
try {
|
||
await db.query(`SELECT set_config('app.branch_code', 'BR001', true)`);
|
||
const r = await db.query(
|
||
`INSERT INTO tenant_br001.inspections (branch_code, inspection_photos, inspection_time, compliance_status)
|
||
VALUES ('BR001', $1::text[], $2, 10) RETURNING id::text AS id`,
|
||
[photos, inspected ? new Date().toISOString() : null]
|
||
);
|
||
const id = String(r.rows[0].id);
|
||
await db.query('COMMIT');
|
||
fixtureIds.push(id);
|
||
return id;
|
||
} catch (e) {
|
||
await db.query('ROLLBACK').catch(() => undefined);
|
||
throw e;
|
||
}
|
||
}
|
||
|
||
async function cleanup(): Promise<void> {
|
||
if (!db || !fixtureIds.length) return;
|
||
await db.query('BEGIN');
|
||
try {
|
||
await db.query(`SELECT set_config('app.branch_code', 'BR001', true)`);
|
||
await db.query(`DELETE FROM tenant_br001.inspections WHERE id = ANY($1::uuid[])`, [fixtureIds]);
|
||
await db.query('COMMIT');
|
||
} catch {
|
||
await db.query('ROLLBACK').catch(() => undefined);
|
||
}
|
||
}
|
||
|
||
beforeAll(async () => {
|
||
if (!DB_URL) {
|
||
skipReason = 'DATABASE_URL 未配置';
|
||
return;
|
||
}
|
||
const { loadEnv } = await import('../src/env');
|
||
loadEnv();
|
||
db = new Client({ connectionString: DB_URL });
|
||
try {
|
||
await db.connect();
|
||
} catch (e) {
|
||
skipReason = `DB 连接失败:${(e as Error).message}`;
|
||
return;
|
||
}
|
||
app = (await import('../src/index')).app;
|
||
tokenAdmin = await login('admin');
|
||
tokenSuper = await login('superadmin');
|
||
if (!tokenAdmin || !tokenSuper) skipReason = '登录失败(需本地 dev 密码 123456)';
|
||
}, 30000);
|
||
|
||
afterAll(async () => {
|
||
await cleanup().catch(() => undefined);
|
||
if (db) await db.end().catch(() => undefined);
|
||
});
|
||
|
||
const h = (t: string, br = 'BR001') => ({ Authorization: `Bearer ${t}`, 'X-Operating-Branch': br });
|
||
|
||
describe('T9F-1:/api/data 禁写存储 key 列(insert/update,含 super_admin)', () => {
|
||
const cases: Array<{ table: string; action: 'update' | 'insert'; payload: Record<string, unknown>; label: string }> = [
|
||
{ table: 'inspections', action: 'update', payload: { inspection_photos: ['archive/BR002/2026-10.tar.gz'] }, label: 'inspection_photos' },
|
||
{ table: 'picking_items', action: 'update', payload: { outbound_photos: ['BR002/x.jpg'] }, label: 'outbound_photos' },
|
||
{ table: 'picking_items', action: 'insert', payload: { outbound_photos: ['BR002/x.jpg'] }, label: 'outbound_photos(insert)' },
|
||
{ table: 'delivery_signatures', action: 'update', payload: { photo_url: 'BR002/x.jpg' }, label: 'photo_url' },
|
||
{ table: 'invoices', action: 'update', payload: { invoice_url: 'BR002/supplier-invoices/a.pdf' }, label: 'invoice_url' },
|
||
{ table: 'cost_details', action: 'update', payload: { voucher_urls: ['BR002/free-cost/x.jpg'] }, label: 'voucher_urls' },
|
||
];
|
||
|
||
for (const c of cases) {
|
||
it(`${c.label}:admin update/insert ⇒ 403`, async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const res = await request(app)
|
||
.post('/api/data/query')
|
||
.set(h(tokenAdmin))
|
||
.send({
|
||
table: c.table,
|
||
action: c.action,
|
||
...(c.action === 'update'
|
||
? { updateData: c.payload, filters: [{ column: 'id', operator: 'eq', value: '00000000-0000-0000-0000-000000000000' }] }
|
||
: { insertData: { branch_code: 'BR001', ...c.payload } }),
|
||
});
|
||
expect(res.status).toBe(403);
|
||
expect(JSON.stringify(res.body)).toMatch(/不允许通过数据接口写入/);
|
||
}, 30000);
|
||
}
|
||
|
||
it('super_admin 同样被拒(必须走业务接口)', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const res = await request(app)
|
||
.post('/api/data/query')
|
||
.set(h(tokenSuper))
|
||
.send({
|
||
table: 'inspections',
|
||
action: 'update',
|
||
updateData: { inspection_photos: ['archive/BR002/x.jpg'] },
|
||
filters: [{ column: 'id', operator: 'eq', value: '00000000-0000-0000-0000-000000000000' }],
|
||
});
|
||
expect(res.status).toBe(403);
|
||
}, 30000);
|
||
|
||
it('对照:非敏感列 update 不被该守卫拦截(返回 200/无该错误)', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const res = await request(app)
|
||
.post('/api/data/query')
|
||
.set(h(tokenAdmin))
|
||
.send({
|
||
table: 'inspections',
|
||
action: 'update',
|
||
updateData: { compliance_status: 10 },
|
||
filters: [{ column: 'id', operator: 'eq', value: '00000000-0000-0000-0000-000000000000' }],
|
||
});
|
||
expect(res.status).not.toBe(403);
|
||
}, 30000);
|
||
});
|
||
|
||
describe('T9F-2:finalize 拒绝 archive 源对象', () => {
|
||
it('archive/BR001 作为 finalize 源 ⇒ 403,且不读/不写/不删', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
H.getObject.mockClear(); H.putObject.mockClear(); H.deleteObject.mockClear();
|
||
const { finalizeInspectionPhotosToResultFolder } = await import('../src/services/storageUploadService');
|
||
await expect(
|
||
finalizeInspectionPhotosToResultFolder({
|
||
bucket: 'inspection-photos', qualityRating: '合格', productName: '土豆', skuCode: 'SKU1',
|
||
photos: ['archive/BR001/2026-10.tar.gz'], ctx: { branchCode: 'BR001' },
|
||
} as never)
|
||
).rejects.toMatchObject({ status: 403 });
|
||
expect(H.getObject).not.toHaveBeenCalled();
|
||
expect(H.putObject).not.toHaveBeenCalled();
|
||
expect(H.deleteObject).not.toHaveBeenCalled();
|
||
}, 30000);
|
||
});
|
||
|
||
describe('T9F-3:验收照片删除遇到 archive / 他分支 ⇒ 跳过删除(源对象保留)', () => {
|
||
it('DB 行含 archive/BR002/... ⇒ 不调用 deleteObject,归档源保留', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const id = await insertInspection(['archive/BR002/2026-10.tar.gz'], true);
|
||
H.deleteObject.mockClear();
|
||
const { clearInspectionReviewPhotos } = await import('../src/services/inspectionReviewService');
|
||
const { runWithTenantDbContext } = await import('../src/services/tenantDbContext');
|
||
const result = await runWithTenantDbContext('BR001', () => clearInspectionReviewPhotos({ id, branchCode: 'BR001' }));
|
||
expect(result.cleared).toBeGreaterThanOrEqual(0);
|
||
expect(H.deleteObject).not.toHaveBeenCalledWith('inspection-photos', 'archive/BR002/2026-10.tar.gz');
|
||
}, 30000);
|
||
|
||
it('DB 行含他分支非 archive key ⇒ 断言失败、同样不删除(源对象保留)', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const id = await insertInspection(['BR002/tmp/a.jpg'], true);
|
||
H.deleteObject.mockClear();
|
||
const { clearInspectionReviewPhotos } = await import('../src/services/inspectionReviewService');
|
||
const { runWithTenantDbContext } = await import('../src/services/tenantDbContext');
|
||
await runWithTenantDbContext('BR001', () => clearInspectionReviewPhotos({ id, branchCode: 'BR001' }));
|
||
expect(H.deleteObject).not.toHaveBeenCalled();
|
||
}, 30000);
|
||
|
||
it('移动端删图路由源码契约:archive 检查先于 deleteObject,且删除前 assert 归属', () => {
|
||
const src = fs.readFileSync(
|
||
path.join(__dirname, '../src/routes/mobile/mobileWarehouseRoutes.ts'),
|
||
'utf8'
|
||
);
|
||
const archiveAt = src.indexOf("removed.startsWith('archive/')");
|
||
const deleteAt = src.indexOf("deleteObject('inspection-photos', removed)");
|
||
const assertAt = src.indexOf('assertStorageKeyOwned', archiveAt > 0 ? archiveAt : 0);
|
||
expect(archiveAt).toBeGreaterThan(-1);
|
||
expect(deleteAt).toBeGreaterThan(archiveAt);
|
||
expect(assertAt).toBeGreaterThan(archiveAt);
|
||
expect(assertAt).toBeLessThan(deleteAt);
|
||
});
|
||
});
|
||
|
||
describe('T9F-4:付款凭证抽取读前归属校验', () => {
|
||
it('跨分支 BR002/free-cost-payment/x ⇒ 403', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
H.getObject.mockClear();
|
||
const res = await request(app)
|
||
.post('/api/workflow/cost/free-cost/payment-vouchers/extract')
|
||
.set(h(tokenAdmin))
|
||
.send({ paths: ['BR002/free-cost-payment/x.pdf'] });
|
||
expect(res.status).toBe(403);
|
||
expect(H.getObject).not.toHaveBeenCalled();
|
||
}, 30000);
|
||
});
|