import { describe, expect, it } from 'vitest'; /** * T9 P2(2026-10-19 红队复攻):旧 key(无 `/` 前缀)的归属反查必须在分支 RLS 上下文里执行, * 否则 FORCE RLS 让反查恒 0 ⇒ 本分支旧对象也被 403。真库验证: * · 本分支旧 key(业务表引用)⇒ 可签; * · 他分支同一旧 key ⇒ 403; * · 新 key 前缀:本分支 ⇒ true、跨分支/无 branchCode ⇒ false。 */ type PgClient = { connect: () => Promise; end: () => Promise; query: (sql: string, params?: unknown[]) => Promise<{ rows: Array>; rowCount?: number }>; }; async function loadPgClient(): Promise { const { loadEnv } = await import('../src/env'); loadEnv(); if (!process.env.DATABASE_URL) return null; const pg = (await import('pg')).default as unknown as { Client: new (cfg: { connectionString: string }) => PgClient; }; const client = new pg.Client({ connectionString: process.env.DATABASE_URL }); try { await client.connect(); } catch { return null; } return client; } describe('T9 P2:旧 key 归属反查(真库 + 分支 RLS)', () => { it('本分支旧 key 200、他分支 403、新 key 前缀同/跨分支判定', async (ctx) => { const client = await loadPgClient(); if (!client) { ctx.skip(); return; } const key = `free-cost-invoice/legacy-${Date.now()}-${Math.random().toString(16).slice(2)}.pdf`; try { // FORCE RLS:写入也需分支上下文 await client.query(`SELECT set_config('app.branch_code', 'BR001', false)`); await client.query( `INSERT INTO tenant_br001.free_cost_invoices (id, branch_code, storage_path, ocr, match_status) VALUES (gen_random_uuid(), 'BR001', $1, '{}'::jsonb, 'unmatched')`, [key] ); const { canAccessPrivateObject } = await import('../src/routes/storage'); // 旧 key:业务表反查(必须带分支 RLS 上下文) expect(await canAccessPrivateObject({ branchCode: 'BR001' }, 'invoices', key)).toBe(true); expect(await canAccessPrivateObject({ branchCode: 'BR002' }, 'invoices', key)).toBe(false); // 新 key:前缀判定 expect(await canAccessPrivateObject({ branchCode: 'BR001' }, 'invoices', 'BR001/free-cost-invoice/a.pdf')).toBe(true); expect(await canAccessPrivateObject({ branchCode: 'BR001' }, 'invoices', 'BR002/free-cost-invoice/a.pdf')).toBe(false); // 无 branchCode ⇒ fail-closed expect(await canAccessPrivateObject({ branchCode: null }, 'invoices', key)).toBe(false); } finally { await client.query(`DELETE FROM tenant_br001.free_cost_invoices WHERE storage_path = $1`, [key]).catch(() => undefined); await client.end(); } }); });