import { randomUUID } from 'node:crypto'; import { describe, expect, it, vi } from 'vitest'; /** * T9 P1(2026-10-19)写入口对象归属:**先断言、后落库**。 * * 覆盖(真实本地库,事务/行数证据): * ① 公用 `assertOwnedStoragePaths`:逐项 403、混合列表整批失败、外链/data: 跳过; * ② 其他成本 `cost_details.voucher_url`(createFreeCostEntry); * ③ 固定成本 `fixed_costs.voucher_urls`(create + update); * ④ 付款凭证 `free_cost_payment_vouchers.storage_path`; * ⑤ 成本发票 `free_cost_invoices.storage_path`; * ⑥ 质检报告 `quality_reports.file_paths` / `inventory_batch_reports.file_paths`; * ⑦ 发票 `invoices.invoice_url`(客户/供应商写服务)。 * * 判据统一为:跨分支新 key / 跨分支旧 key ⇒ 403 **且表行数不变**; * 本分支新 key / 本分支旧 key(旧 key 先在业务表里存在)⇒ 200 **且行数 +1**。 */ const H = vi.hoisted(() => ({ getObject: vi.fn(async () => ({ buffer: Buffer.from('%PDF-1.4'), contentType: 'application/pdf', })), putObject: vi.fn(async () => undefined), })); vi.mock('../src/services/storageProvider', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, getStorageProvider: () => ({ getObject: H.getObject, putObject: H.putObject, exists: vi.fn(async () => false), deleteObject: vi.fn(async () => undefined), getReadRedirectUrl: vi.fn(async () => null), }), }; }); // OCR 不联外网:没有运行配置时服务端会走空元数据(与生产降级路径一致) vi.mock('../src/services/llmService', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, hasRuntimeConfig: vi.fn(async () => false), callWithImage: vi.fn(async () => null), callWithFile: vi.fn(async () => null), callWithText: vi.fn(async () => null), }; }); import { pool } from '../src/db'; import { runWithTenantDbContext } from '../src/services/tenantDbContext'; import { assertOwnedStoragePaths } from '../src/services/storageObjectOwnership'; import { createFreeCostEntry } from '../src/services/freeCostService'; import { createFixedCost, updateFixedCostVouchers } from '../src/services/fixedCostService'; import { saveFreeCostPaymentVouchers } from '../src/services/freeCostPaymentVoucherService'; import { saveFreeCostInvoice } from '../src/services/freeCostInvoiceService'; import { createInventoryBatchReports } from '../src/services/inventoryBatchReportService'; import { uploadLibraryQualityReport } from '../src/services/qualityReportService'; import { insertCustomerInvoice } from '../src/services/customerInvoiceWriteService'; import { insertSupplierInvoice } from '../src/services/supplierInvoiceWriteService'; const BR1 = 'BR001'; const BR2 = 'BR002'; let seq = 0; function uniq(tag: string): string { seq += 1; return `t9e-${tag}-${Date.now()}-${seq}-${Math.random().toString(16).slice(2, 8)}`; } async function hasDb(): Promise { try { const client = await pool.connect(); client.release(); return true; } catch { return false; } } function inBranch(branchCode: string, fn: () => Promise): Promise { return runWithTenantDbContext(branchCode, fn); } async function countIn(branchCode: string, sql: string, params: unknown[]): Promise { return inBranch(branchCode, async () => { const result = await pool.query<{ n: number }>(sql, params); return Number(result.rows[0]?.n) || 0; }); } async function seedLegacyPath(branchCode: string, path: string): Promise { await inBranch(branchCode, () => pool.query( `INSERT INTO free_cost_invoices (branch_code, inputter_id, storage_path, ocr, match_status) VALUES ($1, NULL, $2, '{}'::jsonb, 'unmatched')`, [branchCode, path] ) ); } async function deleteForbiddenWriteTest( branchCode: string, statements: Array<[string, unknown[]]> ): Promise { await inBranch(branchCode, async () => { for (const [sql, params] of statements) await pool.query(sql, params); }); } /** * 旧 key 的归属反查要另借一条连接(`runWithBranchRls`)。全量并行跑时若瞬时借不到连接, * 现有实现 fail-closed ⇒ 403(**写入尚未发生**,可安全重试);连续 3 次 403 仍判回归。 */ async function expectLegacyWriteOk(run: () => Promise): Promise { let last: unknown; for (let attempt = 0; attempt < 3; attempt += 1) { try { return await run(); } catch (error: any) { last = error; if (error?.status !== 403) throw error; await new Promise((resolve) => setTimeout(resolve, 80)); } } throw last; } describe('T9 写入口:公用批量归属断言', () => { it('本分支 key 通过;混合列表任一跨分支 key ⇒ 403;空值/外链/data: 跳过', async () => { await expect( assertOwnedStoragePaths({ branchCode: BR1 }, 'invoices', [ `BR001/free-cost/${uniq('a')}.jpg`, `BR001/free-cost/${uniq('b')}.jpg`, ]) ).resolves.toHaveLength(2); await expect( assertOwnedStoragePaths({ branchCode: BR1 }, 'invoices', [ `BR001/free-cost/${uniq('ok')}.jpg`, `BR002/free-cost/${uniq('bad')}.jpg`, ]) ).rejects.toMatchObject({ status: 403, code: 'forbidden' }); await expect( assertOwnedStoragePaths({ branchCode: BR1 }, 'invoices', [ '', ' ', 'https://example.com/a.pdf', 'data:image/png;base64,AAAA', ]) ).resolves.toEqual([]); await expect( assertOwnedStoragePaths({ branchCode: null }, 'invoices', [`BR001/x.jpg`]) ).rejects.toMatchObject({ status: 403 }); }); }); describe('T9 写入口:其他成本 voucher_url(createFreeCostEntry)', () => { it('跨分支新/旧 key ⇒ 403 且行数不变;本分支新/旧 key ⇒ 200 且 +1', async (ctx) => { if (!(await hasDb())) { ctx.skip(); return; } const marker = uniq('freecost'); const countSql = `SELECT count(*)::int AS n FROM cost_details WHERE reference_type = 'free_cost' AND reference_id = $1`; const newSame = `BR001/free-cost/${uniq('new')}.jpg`; const newOther = `BR002/free-cost/${uniq('new')}.jpg`; const legacySame = `free-cost/legacy-${uniq('same')}.jpg`; const legacyOther = `free-cost/legacy-${uniq('other')}.jpg`; const create = (voucherUrls: string[]) => inBranch(BR1, () => createFreeCostEntry({ cycleCode: '', amount: 1, description: marker, branchCode: BR1, inputterId: null, voucherUrls, ownerCtx: { branchCode: BR1 }, }) ); try { await seedLegacyPath(BR2, legacyOther); await seedLegacyPath(BR1, legacySame); await expect(create([newOther])).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [marker])).toBe(0); await expect(create([legacyOther])).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [marker])).toBe(0); await expect(create([newSame])).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [marker])).toBe(1); await expect(expectLegacyWriteOk(() => create([legacySame]))).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [marker])).toBe(2); } finally { await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM operation_logs WHERE target_id IN (SELECT id::text FROM cost_details WHERE reference_id = $1)`, [marker]], [`DELETE FROM cost_details WHERE reference_type = 'free_cost' AND reference_id = $1`, [marker]], [`DELETE FROM free_cost_invoices WHERE storage_path = $1`, [legacySame]], ]); await deleteForbiddenWriteTest(BR2, [ [`DELETE FROM free_cost_invoices WHERE storage_path = $1`, [legacyOther]], ]); } }); }); describe('T9 写入口:固定成本 voucher_urls(create + update)', () => { it('跨分支新/旧 key ⇒ 403 行数不变;本分支新/旧 key ⇒ 200 且 +1;UPDATE 失败原值不变', async (ctx) => { if (!(await hasDb())) { ctx.skip(); return; } const marker = uniq('fixed'); const countSql = `SELECT count(*)::int AS n FROM fixed_costs WHERE remark = $1`; const newSame = `BR001/free-cost/${uniq('new')}.jpg`; const newOther = `BR002/free-cost/${uniq('new')}.jpg`; const legacySame = `free-cost/legacy-${uniq('same')}.jpg`; const legacyOther = `free-cost/legacy-${uniq('other')}.jpg`; const create = (voucherUrls: string[]) => inBranch(BR1, () => createFixedCost({ cycleCode: '202610', costType: 'other', budgetAmount: 1, actualAmount: 1, remark: marker, voucherUrls, branchCode: BR1, allocate: false, ownerCtx: { branchCode: BR1 }, }) ); try { await seedLegacyPath(BR2, legacyOther); await seedLegacyPath(BR1, legacySame); await expect(create([newOther])).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [marker])).toBe(0); await expect(create([legacyOther])).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [marker])).toBe(0); const created = await create([newSame]); expect(await countIn(BR1, countSql, [marker])).toBe(1); const id = String(created.fixedCost.id); // UPDATE 跨分支:403,原 voucher_urls 不变 await expect( inBranch(BR1, () => updateFixedCostVouchers(id, [newOther], { branchCode: BR1 } as never)) ).rejects.toMatchObject({ status: 403 }); const afterReject = await inBranch(BR1, async () => { const row = await pool.query(`SELECT voucher_urls FROM fixed_costs WHERE id = $1`, [id]); return row.rows[0]?.voucher_urls as string[] | null; }); expect(afterReject).toEqual([newSame]); // UPDATE 本分支旧 key:200(旧 key 已在本分支业务表引用) await expect( inBranch(BR1, () => expectLegacyWriteOk(() => updateFixedCostVouchers(id, [legacySame], { branchCode: BR1 } as never) ) ) ).resolves.toBeTruthy(); // 本分支旧 key 的 create:200 且行数 +1 await expect(expectLegacyWriteOk(() => create([legacySame]))).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [marker])).toBe(2); } finally { await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM fixed_costs WHERE remark = $1`, [marker]], [`DELETE FROM free_cost_invoices WHERE storage_path = $1`, [legacySame]], ]); await deleteForbiddenWriteTest(BR2, [ [`DELETE FROM free_cost_invoices WHERE storage_path = $1`, [legacyOther]], ]); } }); }); describe('T9 写入口:付款凭证 storage_path', () => { it('跨分支新/旧 key ⇒ 403 且行数不变;本分支新/旧 key ⇒ 200 且 +1', async (ctx) => { if (!(await hasDb())) { ctx.skip(); return; } const marker = uniq('pay'); const countSql = `SELECT count(*)::int AS n FROM free_cost_payment_vouchers WHERE storage_path = $1`; const newSame = `BR001/free-cost-payment/${uniq('new')}.jpg`; const newOther = `BR002/free-cost-payment/${uniq('new')}.jpg`; const legacySame = `free-cost-payment/legacy-${uniq('same')}.jpg`; const legacyOther = `free-cost-payment/legacy-${uniq('other')}.jpg`; const save = (path: string) => inBranch(BR1, () => saveFreeCostPaymentVouchers({ items: [{ path }], ctx: { branchCode: BR1 } as never, branchCode: BR1, uploaderId: randomUUID(), }) ); try { await seedLegacyPath(BR2, legacyOther); await seedLegacyPath(BR1, legacySame); await expect(save(newOther)).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [newOther])).toBe(0); await expect(save(legacyOther)).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [legacyOther])).toBe(0); await expect(save(newSame)).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [newSame])).toBe(1); await expect(expectLegacyWriteOk(() => save(legacySame))).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [legacySame])).toBe(1); } finally { await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM free_cost_payment_vouchers WHERE storage_path = $1`, [newSame]], [`DELETE FROM free_cost_payment_vouchers WHERE storage_path = $1`, [legacySame]], [`DELETE FROM free_cost_invoices WHERE storage_path = $1`, [legacySame]], ]); await deleteForbiddenWriteTest(BR2, [ [`DELETE FROM free_cost_invoices WHERE storage_path = $1`, [legacyOther]], ]); } }); }); describe('T9 写入口:成本发票 storage_path', () => { it('跨分支新 key ⇒ 403 且行数不变;本分支新 key ⇒ 200 且 +1', async (ctx) => { if (!(await hasDb())) { ctx.skip(); return; } const newSame = `BR001/free-cost-invoice/${uniq('new')}.jpg`; const newOther = `BR002/free-cost-invoice/${uniq('new')}.jpg`; const countSql = `SELECT count(*)::int AS n FROM free_cost_invoices WHERE storage_path = $1`; const save = (invoicePath: string) => inBranch(BR1, () => saveFreeCostInvoice({ invoicePath, costDetailIds: [], ctx: { branchCode: BR1 } as never, inputterId: randomUUID(), branchCode: BR1, }) ); try { await expect(save(newOther)).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [newOther])).toBe(0); await expect(save(newSame)).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [newSame])).toBe(1); } finally { await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM free_cost_invoices WHERE storage_path = $1`, [newSame]], ]); } }); }); describe('T9 写入口:质检报告 file_paths', () => { it('批次报告:跨分支新/旧 key ⇒ 403 行数不变;本分支新/旧 key ⇒ 200 且 +1', async (ctx) => { if (!(await hasDb())) { ctx.skip(); return; } const marker = uniq('batch'); const countSql = `SELECT count(*)::int AS n FROM inventory_batch_reports WHERE report_no LIKE $1`; const newSame = `BR001/${uniq('new')}.pdf`; const newOther = `BR002/${uniq('new')}.pdf`; // T9F-1b:旧 key 反查只认已知上传命名空间;批次报告历史 key 用 free-cost/(safeStorageFileName 允许的旧命名空间)。 // 不能再拿裸文件名(legacy-*.pdf)当“旧 key”,否则应被 403。 const legacySame = `free-cost/legacy-${uniq('same')}.pdf`; const legacyOther = `free-cost/legacy-${uniq('other')}.pdf`; // 未知命名空间:即便本分支业务表里“有引用”,也不得被 legacy LIKE 反查洗白(T9F-1b)。 const legacyUnknown = `legacy-${uniq('unknown')}.pdf`; const create = (path: string, reportNo: string) => inBranch(BR1, () => createInventoryBatchReports({ files: [path], branchCode: BR1, uploadedBy: null, reportNo, }) ); try { await inBranch(BR2, () => pool.query( `INSERT INTO inventory_batch_reports (branch_code, report_no, report_type, file_paths, source_party, status) VALUES ($1, NULL, 'batch', ARRAY[$2]::text[], 'warehouse', 10)`, [BR2, legacyOther] ) ); await inBranch(BR1, () => pool.query( `INSERT INTO inventory_batch_reports (branch_code, report_no, report_type, file_paths, source_party, status) VALUES ($1, NULL, 'batch', ARRAY[$2]::text[], 'warehouse', 10)`, [BR1, legacySame] ) ); // 同一分支里先落一行“裸文件名”引用:没有已知上传前缀 ⇒ 反查必须拒绝 await inBranch(BR1, () => pool.query( `INSERT INTO inventory_batch_reports (branch_code, report_no, report_type, file_paths, source_party, status) VALUES ($1, NULL, 'batch', ARRAY[$2]::text[], 'warehouse', 10)`, [BR1, legacyUnknown] ) ); await expect(create(newOther, `${marker}-new`)).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [`${marker}%`])).toBe(0); await expect(create(legacyOther, `${marker}-legacy`)).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [`${marker}%`])).toBe(0); await expect(create(legacyUnknown, `${marker}-unknown`)).rejects.toMatchObject({ status: 403 }); expect(await countIn(BR1, countSql, [`${marker}%`])).toBe(0); await expect(create(newSame, `${marker}-new`)).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [`${marker}%`])).toBe(1); await expect(create(legacySame, `${marker}-legacy`)).resolves.toBeTruthy(); expect(await countIn(BR1, countSql, [`${marker}%`])).toBe(2); } finally { await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM operation_logs WHERE target_id IN (SELECT id::text FROM inventory_batch_reports WHERE report_no LIKE $1)`, [`${marker}%`]], [`DELETE FROM inventory_batch_reports WHERE report_no LIKE $1`, [`${marker}%`]], ]); await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM inventory_batch_reports WHERE $1 = ANY(file_paths)`, [legacySame]], [`DELETE FROM inventory_batch_reports WHERE $1 = ANY(file_paths)`, [legacyUnknown]], [`DELETE FROM inventory_batch_reports WHERE $1 = ANY(file_paths)`, [newSame]], ]); await deleteForbiddenWriteTest(BR2, [ [`DELETE FROM inventory_batch_reports WHERE $1 = ANY(file_paths)`, [legacyOther]], ]); } }); it('报告库 data URL 上传:服务端 mint 的 file_paths 带本分支前缀(可写前置断言)', async (ctx) => { if (!(await hasDb())) { ctx.skip(); return; } const supplierCode = uniq('supplier'); const dataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='; try { const saved = await inBranch(BR1, () => uploadLibraryQualityReport({ supplierCode, files: [dataUrl], branchCode: BR1, }) ); expect(saved.file_paths.length).toBe(1); expect(saved.file_paths[0].startsWith(`${BR1}/`)).toBe(true); expect( await countIn(BR1, `SELECT count(*)::int AS n FROM quality_reports WHERE supplier_code = $1`, [ supplierCode, ]) ).toBe(1); } finally { await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM quality_reports WHERE supplier_code = $1`, [supplierCode]], ]); } }); }); describe('T9 写入口:发票 invoice_url', () => { it('客户/供应商发票:跨分支 key ⇒ 403 且行数不变;本分支 key ⇒ 200 且 +1', async (ctx) => { if (!(await hasDb())) { ctx.skip(); return; } const customerNo = uniq('cust'); const supplierNo = uniq('supp'); const customerOtherUrl = `BR002/supplier-invoices/${uniq('x')}.pdf`; const customerSameUrl = `BR001/supplier-invoices/${uniq('ok')}.pdf`; const supplierOtherUrl = `BR002/supplier-invoices/${uniq('x')}.pdf`; const supplierSameUrl = `BR001/supplier-invoices/${uniq('ok')}.pdf`; const ctx1 = { branchCode: BR1, isSuperAdmin: false } as never; try { await expect( inBranch(BR1, () => insertCustomerInvoice( { invoice_no: customerNo, customer_code: 'T9E', amount: 1, branch_code: BR1, invoice_url: customerOtherUrl, } as never, ctx1 ) ) ).rejects.toMatchObject({ status: 403 }); expect( await countIn(BR1, `SELECT count(*)::int AS n FROM invoices WHERE invoice_no = $1`, [customerNo]) ).toBe(0); await expect( inBranch(BR1, () => insertCustomerInvoice( { invoice_no: customerNo, customer_code: 'T9E', amount: 1, branch_code: BR1, invoice_url: customerSameUrl, } as never, ctx1 ) ) ).resolves.toBeTruthy(); expect( await countIn(BR1, `SELECT count(*)::int AS n FROM invoices WHERE invoice_no = $1`, [customerNo]) ).toBe(1); await expect( inBranch(BR1, () => insertSupplierInvoice( { invoice_no: supplierNo, supplier_code: 'T9E', amount: 1, branch_code: BR1, invoice_url: supplierOtherUrl, } as never, ctx1 ) ) ).rejects.toMatchObject({ status: 403 }); expect( await countIn(BR1, `SELECT count(*)::int AS n FROM invoices WHERE invoice_no = $1`, [supplierNo]) ).toBe(0); await expect( inBranch(BR1, () => insertSupplierInvoice( { invoice_no: supplierNo, supplier_code: 'T9E', amount: 1, branch_code: BR1, invoice_url: supplierSameUrl, } as never, ctx1 ) ) ).resolves.toBeTruthy(); expect( await countIn(BR1, `SELECT count(*)::int AS n FROM invoices WHERE invoice_no = $1`, [supplierNo]) ).toBe(1); } finally { await deleteForbiddenWriteTest(BR1, [ [`DELETE FROM invoices WHERE invoice_no = $1`, [customerNo]], [`DELETE FROM invoices WHERE invoice_no = $1`, [supplierNo]], ]); } }); });