- 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 超长修复
248 lines
10 KiB
TypeScript
248 lines
10 KiB
TypeScript
import { Client } from 'pg';
|
||
import request from 'supertest';
|
||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||
import fs from 'node:fs';
|
||
|
||
/**
|
||
* T9 写入口归属(2026-10-19,tester 独立补测):
|
||
* 服务端写库前必须校验 storage key 归属(`assertOwnedStoragePaths`)——
|
||
* · 跨分支 key(新前缀 / 他分支旧 key)⇒ 403,且对应表**行数不变**(不先落库后拦);
|
||
* · 本分支 key ⇒ 200,且行数 **+1**;
|
||
* · 旧 key(无分支前缀)同分支 ⇒ 200(业务表反查在分支 RLS 上下文内)。
|
||
* 覆盖:free-cost 创建、fixed-cost 创建、付款凭证保存、质检报告上传。
|
||
*
|
||
* 真实 PG + 真实 app(in-process supertest);无 DATABASE_URL / 登录不可用则跳过。
|
||
* 全部写入用唯一 marker 并在 finally 清理(仅本地 dev 库)。
|
||
*/
|
||
|
||
type Pg = Client;
|
||
|
||
const DB_URL = (() => {
|
||
try {
|
||
return fs.readFileSync('.env', 'utf8').match(/^DATABASE_URL=(.*)$/m)?.[1]?.trim() || '';
|
||
} catch {
|
||
return '';
|
||
}
|
||
})();
|
||
|
||
const MARK = `T9WO-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
||
const LEGACY_BR001 = `free-cost-invoice/${MARK}-br001.pdf`;
|
||
const LEGACY_BR002 = `free-cost-invoice/${MARK}-br002.pdf`;
|
||
|
||
let app: any;
|
||
let db: Pg;
|
||
let tokenBR001 = '';
|
||
let tokenBR002 = '';
|
||
let skipReason = '';
|
||
|
||
async function count(table: string, where: string, params: unknown[] = []): Promise<number> {
|
||
// tenant_* 是 FORCE RLS:计数必须带分支上下文,否则恒 0(不是实现没落库)
|
||
await db.query('BEGIN');
|
||
try {
|
||
await db.query(`SELECT set_config('app.branch_code', 'BR001', true)`);
|
||
const r = await db.query(`SELECT count(*)::int n FROM tenant_br001.${table} WHERE ${where}`, params);
|
||
return Number(r.rows[0]?.n || 0);
|
||
} finally {
|
||
await db.query('ROLLBACK').catch(() => undefined);
|
||
}
|
||
}
|
||
|
||
async function withBranch<T>(branch: string, fn: () => Promise<T>): Promise<T> {
|
||
await db.query('BEGIN');
|
||
try {
|
||
await db.query(`SELECT set_config('app.branch_code', $1, true)`, [branch]);
|
||
return await fn();
|
||
} finally {
|
||
await db.query('ROLLBACK').catch(() => undefined);
|
||
}
|
||
}
|
||
|
||
async function insertLegacyFreeCostInvoice(branch: 'BR001' | 'BR002', key: string): Promise<void> {
|
||
const schema = `tenant_${branch.toLowerCase()}`;
|
||
await db.query('BEGIN');
|
||
try {
|
||
await db.query(`SELECT set_config('app.branch_code', $1, true)`, [branch]);
|
||
await db.query(
|
||
`INSERT INTO ${schema}.free_cost_invoices (id, branch_code, storage_path, ocr, match_status)
|
||
VALUES (gen_random_uuid(), $1, $2, '{}'::jsonb, 'unmatched')`,
|
||
[branch, key]
|
||
);
|
||
await db.query('COMMIT');
|
||
} catch (e) {
|
||
await db.query('ROLLBACK').catch(() => undefined);
|
||
throw e;
|
||
}
|
||
}
|
||
|
||
async function cleanup(): Promise<void> {
|
||
const tables = ['cost_details', 'fixed_costs', 'free_cost_payment_vouchers', 'free_cost_invoices', 'quality_reports'];
|
||
for (const t of tables) {
|
||
await db.query('BEGIN');
|
||
try {
|
||
await db.query(`SELECT set_config('app.branch_code', 'BR001', true)`);
|
||
if (t === 'free_cost_invoices') {
|
||
await db.query(`SELECT set_config('app.branch_code', 'BR001', true)`);
|
||
await db.query(`DELETE FROM tenant_br001.free_cost_invoices WHERE storage_path = ANY($1::text[])`, [[LEGACY_BR001, LEGACY_BR002]]);
|
||
} else if (t === 'quality_reports') {
|
||
await db.query(`DELETE FROM tenant_br001.quality_reports WHERE file_paths::text LIKE $1`, [`%${MARK}%`]);
|
||
} else {
|
||
await db.query(`DELETE FROM tenant_br001.${t} WHERE ${t === 'cost_details' ? 'reference_id' : 'remark'}::text LIKE $1`, [`%${MARK}%`]);
|
||
}
|
||
await db.query('COMMIT');
|
||
} catch {
|
||
await db.query('ROLLBACK').catch(() => undefined);
|
||
}
|
||
}
|
||
await db.query('BEGIN');
|
||
try {
|
||
await db.query(`SELECT set_config('app.branch_code', 'BR002', true)`);
|
||
await db.query(`DELETE FROM tenant_br002.free_cost_invoices WHERE storage_path = ANY($1::text[])`, [[LEGACY_BR002]]);
|
||
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;
|
||
}
|
||
const idx = await import('../src/index');
|
||
app = idx.app;
|
||
const login = async (username: string) => {
|
||
const r = await request(app).post('/api/auth/token').send({ username, password: '123456' });
|
||
return String(r.body?.access_token || '');
|
||
};
|
||
tokenBR001 = await login('admin');
|
||
tokenBR002 = await login('18381421566');
|
||
if (!tokenBR001 || !tokenBR002) {
|
||
skipReason = '本地登录失败(admin / 18381421566 需 dev 密码 123456)';
|
||
}
|
||
}, 30000);
|
||
|
||
afterAll(async () => {
|
||
if (db && !skipReason) await cleanup().catch(() => undefined);
|
||
if (db) await db.end().catch(() => undefined);
|
||
});
|
||
|
||
const h = (t: string, br: string) => ({ Authorization: `Bearer ${t}`, 'X-Operating-Branch': br });
|
||
|
||
describe('T9 写入口归属:跨分支 403 且不落库 / 本分支 200 且 +1', () => {
|
||
it('free-cost:跨分支新前缀 / BR002 旧 key ⇒ 403 行数不变;本分支新前缀 / BR001 旧 key ⇒ 200 +1', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const where = `branch_code='BR001' AND reference_id LIKE '%${MARK}%'`;
|
||
const base = await count('cost_details', where);
|
||
|
||
const crossNew = await request(app)
|
||
.post('/api/workflow/cost/free-cost')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({ amount: 1, description: `${MARK}-cross-new`, voucher_urls: ['BR002/free-cost/x.jpg'] });
|
||
expect(crossNew.status).toBe(403);
|
||
expect(await count('cost_details', where)).toBe(base);
|
||
|
||
await insertLegacyFreeCostInvoice('BR002', LEGACY_BR002);
|
||
const crossLegacy = await request(app)
|
||
.post('/api/workflow/cost/free-cost')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({ amount: 1, description: `${MARK}-cross-legacy`, voucher_urls: [LEGACY_BR002] });
|
||
expect(crossLegacy.status).toBe(403);
|
||
expect(await count('cost_details', where)).toBe(base);
|
||
|
||
const same = await request(app)
|
||
.post('/api/workflow/cost/free-cost')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({ amount: 1, description: `${MARK}-same`, voucher_urls: ['BR001/free-cost/x.jpg'] });
|
||
expect(same.status).toBe(200);
|
||
expect(await count('cost_details', where)).toBe(base + 1);
|
||
|
||
await insertLegacyFreeCostInvoice('BR001', LEGACY_BR001);
|
||
const sameLegacy = await request(app)
|
||
.post('/api/workflow/cost/free-cost')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({ amount: 1, description: `${MARK}-same-legacy`, voucher_urls: [LEGACY_BR001] });
|
||
expect(sameLegacy.status).toBe(200);
|
||
expect(await count('cost_details', where)).toBe(base + 2);
|
||
}, 30000);
|
||
|
||
it('fixed-cost:跨分支 ⇒ 403 行数不变;本分支 ⇒ 200 +1', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const where = `branch_code='BR001' AND remark LIKE '%${MARK}%'`;
|
||
const base = await count('fixed_costs', where);
|
||
|
||
const cross = await request(app)
|
||
.post('/api/workflow/finance/fixed-costs')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({
|
||
cycle_code: '202610', cost_type: 'other', actual_amount: 1,
|
||
remark: `${MARK}-fixed-cross`, voucher_urls: ['BR002/free-cost/x.jpg'], allocate: false,
|
||
});
|
||
expect(cross.status).toBe(403);
|
||
expect(await count('fixed_costs', where)).toBe(base);
|
||
|
||
const same = await request(app)
|
||
.post('/api/workflow/finance/fixed-costs')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({
|
||
cycle_code: '202610', cost_type: 'other', actual_amount: 1,
|
||
remark: `${MARK}-fixed-same`, voucher_urls: ['BR001/free-cost/x.jpg'], allocate: false,
|
||
});
|
||
expect(same.status).toBe(200);
|
||
expect(await count('fixed_costs', where)).toBe(base + 1);
|
||
}, 30000);
|
||
|
||
it('payment voucher:跨分支 storage_path ⇒ 403 行数不变;本分支 ⇒ 200 +1', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const where = `branch_code='BR001' AND storage_path LIKE '%${MARK}%'`;
|
||
const base = await count('free_cost_payment_vouchers', where);
|
||
|
||
const cross = await request(app)
|
||
.post('/api/workflow/cost/free-cost/payment-vouchers')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({ items: [{ path: `BR002/free-cost-payment/${MARK}-cross.pdf`, ignore: true }] });
|
||
expect(cross.status).toBe(403);
|
||
expect(await count('free_cost_payment_vouchers', where)).toBe(base);
|
||
|
||
const same = await request(app)
|
||
.post('/api/workflow/cost/free-cost/payment-vouchers')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({ items: [{ path: `BR001/free-cost-payment/${MARK}-same.pdf`, ignore: true }] });
|
||
expect(same.status).toBe(200);
|
||
expect(await count('free_cost_payment_vouchers', where)).toBe(base + 1);
|
||
}, 30000);
|
||
|
||
it('quality reports:跨分支 file_paths ⇒ 403 行数不变', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const where = `branch_code='BR001' AND file_paths::text LIKE '%${MARK}%'`;
|
||
const base = await count('quality_reports', where);
|
||
|
||
const cross = await request(app)
|
||
.post('/api/workflow/quality-reports/library')
|
||
.set(h(tokenBR001, 'BR001'))
|
||
.send({ report_date: '2026-10-19', files: [`BR002/quality-reports/${MARK}.pdf`] });
|
||
expect(cross.status).toBe(403);
|
||
expect(await count('quality_reports', where)).toBe(base);
|
||
}, 30000);
|
||
|
||
it('BR002 token 写入 BR001 前缀同样 403(反向校验)', async (ctx) => {
|
||
if (skipReason) return ctx.skip();
|
||
const where = `branch_code='BR001' AND reference_id LIKE '%${MARK}%'`;
|
||
const base = await count('cost_details', where);
|
||
const cross = await request(app)
|
||
.post('/api/workflow/cost/free-cost')
|
||
.set(h(tokenBR002, 'BR002'))
|
||
.send({ amount: 1, description: `${MARK}-br002`, voucher_urls: ['BR001/free-cost/x.jpg'] });
|
||
expect(cross.status).toBe(403);
|
||
expect(await count('cost_details', where)).toBe(base);
|
||
}, 30000);
|
||
});
|