/** * 后端「封装边界」守卫。 * * 目的:把审计出来的边界用可机检的方式固定住 —— 只允许收紧,不允许放松。 * - 路由层不得新增内嵌 SQL(handler 体内的裸 SQL 计数只能 ≤ 基线) * - 通用数据网关的路由必须保持「薄」:不碰连接池、不开事务 * - 绕过 ALS 租户上下文的通道(自建连接池 / raw pool)白名单只能缩小 * - 通用数据网关的「可写表集合」只能缩小(新增可写表必须显式改本文件) * * 收紧后想让本测试变绿:把对应基线数字/白名单条目删掉即可(这就是棘轮)。 * 详见 docs/audit 里的后端边界审计。 */ import { readFileSync, readdirSync, statSync } from 'node:fs'; import path from 'path'; import { describe, expect, it } from 'vitest'; const SRC = path.join(__dirname, '../src'); function walk(dir: string, out: string[] = []): string[] { for (const entry of readdirSync(dir)) { const full = path.join(dir, entry); if (statSync(full).isDirectory()) walk(full, out); else if (entry.endsWith('.ts') && !entry.endsWith('.test.ts')) out.push(full); } return out; } const ALL_FILES = walk(SRC); const rel = (f: string) => path.relative(SRC, f).split(path.sep).join('/'); const ROUTE_FILES = ALL_FILES.filter((f) => rel(f).startsWith('routes/') || rel(f).includes('/routes/')); /** accessPolicy.ts 的四张名单按源码文本解析(保持「只许收紧」的棘轮语义) */ const POLICY_SRC = readFileSync(path.join(SRC, 'services/accessPolicy.ts'), 'utf8'); function readPolicySet(name: string): string[] { const m = POLICY_SRC.match(new RegExp(`const ${name} = new Set\\(\\[([\\s\\S]*?)\\]\\)`)); if (!m) throw new Error(`未找到 ${name} 定义,accessPolicy 结构可能已变更`); return [...m[1].matchAll(/'([a-z_]+)'/g)].map((x) => x[1]); } const SQL_RE = /\b(SELECT\s|INSERT\s+INTO\s|UPDATE\s+\w+\s+SET\s|DELETE\s+FROM\s)/g; const ROUTE_RE = /\b(?:router|app)\.(get|post|put|patch|delete|all)\s*\(/g; /** 找出所有「路由注册 → handler 函数体」的字符区间(花括号配对) */ function handlerRanges(src: string): Array<[number, number]> { const ranges: Array<[number, number]> = []; ROUTE_RE.lastIndex = 0; let m: RegExpExecArray | null; while ((m = ROUTE_RE.exec(src))) { const start = src.indexOf('{', m.index); if (start < 0) continue; let depth = 0; let i = start; for (; i < src.length; i += 1) { if (src[i] === '{') depth += 1; else if (src[i] === '}') { depth -= 1; if (depth === 0) { i += 1; break; } } } ranges.push([start, i]); } return ranges; } /** 统计「落在路由 handler 体内」的 SQL 语句数 */ function countSqlInsideHandlers(src: string): number { const ranges = handlerRanges(src); let n = 0; SQL_RE.lastIndex = 0; let m: RegExpExecArray | null; while ((m = SQL_RE.exec(src))) { if (ranges.some(([a, b]) => m!.index >= a && m!.index < b)) n += 1; } return n; } /** * 路由层 handler 内嵌 SQL 的基线(2026-09-15 审计实测)。 * 只能下调,不得上调;新增文件一律必须为 0。 */ const ROUTE_SQL_BASELINE: Record = { 'routes/auth.ts': 32, 'routes/mobile/mobileDeliveryRoutes.ts': 19, 'routes/mobile/mobilePurchaseRoutes.ts': 9, 'routes/mobile/mobilePurchaserOrderRoutes.ts': 9, 'modules/workflow/routes/preparationRoutes.ts': 8, 'routes/mobile/mobileAdminRoutes.ts': 7, 'routes/mobile/mobileOrderRoutes.ts': 7, 'routes/purchasers.ts': 7, 'modules/workflow/routes/deliveryRoutes.ts': 6, 'routes/supplier/supplierBusinessRoutes.ts': 6, 'modules/workflow/routes/orderRoutes.ts': 5, 'routes/mobile/mobileWarehouseRoutes.ts': 5, 'routes/mobile/mobileInventoryRoutes.ts': 4, 'routes/roles.ts': 4, 'routes/suppliers.ts': 3, 'modules/workflow/routes/financeRoutes.ts': 1, 'routes/accounts.ts': 1, }; describe('后端封装边界:路由层', () => { it('路由层不得新增内嵌 SQL(只能收紧)', () => { const violations: string[] = []; let total = 0; for (const file of ROUTE_FILES) { const key = rel(file); const count = countSqlInsideHandlers(readFileSync(file, 'utf8')); total += count; const baseline = ROUTE_SQL_BASELINE[key]; if (baseline === undefined) { if (count > 0) { violations.push(`${key}: 新增 ${count} 条 handler 内裸 SQL(基线中不存在此文件,应为 0)`); } } else if (count > baseline) { violations.push(`${key}: ${count} 条 > 基线 ${baseline} 条`); } } expect( violations, `路由层裸 SQL 增加。请把 SQL 移入 services/(或确属无法下移时,先在设计文档说明再调整基线):\n${violations.join('\n')}` ).toEqual([]); // 总量棘轮:当前 133 条 expect(total).toBeLessThanOrEqual(133); }); it('通用数据网关的路由必须保持「薄」:不碰连接池、不开事务', () => { const src = readFileSync(path.join(SRC, 'routes/data.ts'), 'utf8'); expect(src).not.toMatch(/pool\s*\./); expect(src).not.toMatch(/\bBEGIN\b/); expect(src).not.toMatch(/client\.query/); // 持久化必须来自网关服务层 expect(src).toContain("from '../services/dataGatewayService'"); }); }); describe('后端封装边界:数据访问通道', () => { it('自建连接池只允许出现在 db.ts 与 setup-db.ts', () => { const offenders = ALL_FILES.filter((f) => /new Pool\(/.test(readFileSync(f, 'utf8'))).map(rel); expect(offenders.filter((f) => f !== 'db.ts' && f !== 'setup-db.ts')).toEqual([]); }); it('getRawPoolQuery 的消费方白名单只能缩小', () => { const ALLOWED = new Set([ 'db.ts', 'modules/kernel/withOrderLock.ts', 'services/auditService.ts', 'services/bidAwardService.ts', 'services/freeCostApprovalConfigService.ts', 'services/notificationService.ts', 'services/notificationStreamService.ts', 'services/skuImageConfigService.ts', 'services/tenantRlsGuard.ts', 'services/tenantSchemaFallback.ts', 'services/tenantScope.ts', 'services/unitDictionaryService.ts', ]); const users = ALL_FILES.filter((f) => /getRawPoolQuery/.test(readFileSync(f, 'utf8'))).map(rel); expect( users.filter((f) => !ALLOWED.has(f)), '新增了绕过 ALS 租户上下文的 raw pool 调用方。若确有必要,请先在设计文档说明理由。' ).toEqual([]); }); it('getRawPoolConnect 的消费方白名单只能缩小', () => { const ALLOWED = new Set([ 'db.ts', 'services/orderManageItemsService.ts', 'services/supplierPreparationStatusService.ts', // 2026-10-15:分拣开关的「角色推断」读 public 的 user_roles/profiles(**都开了 RLS 且策略依赖 // 恒 NULL 的 auth.uid()**),在租户上下文里必被挡成 0 行 ⇒ 开关被误判为「关」(P0,见 // docs/design/20261015-分拣开关角色推断被RLS上下文污染.md)。getRawPoolQuery 绕不过去 // (pg.Pool.query 内部走被 ALS 包装的 pool.connect),故确有必要用 getRawPoolConnect。 'services/pickingConfigService.ts', ]); const users = ALL_FILES.filter((f) => /getRawPoolConnect/.test(readFileSync(f, 'utf8'))).map(rel); expect(users.filter((f) => !ALLOWED.has(f))).toEqual([]); }); }); describe('后端封装边界:通用数据网关的可写表', () => { const readSet = readPolicySet; it('可写表集合只能缩小,不得新增', () => { const allowed = readSet('ALLOWED_TABLES'); const denyWrite = readSet('DENY_WRITE_TABLES'); const writable = allowed.filter((t) => !denyWrite.includes(t)); // 2026-09-15 实测 56 张(含 orders/purchase_orders/skus/inventory/after_sales 等核心业务表)。 // 目标是把这些表逐步移入 DENY_WRITE_TABLES;本断言只禁止新增。 const PINNED = new Set([ 'after_sales', 'alias_recognition_logs', 'allocation_tasks', 'bid_prices', 'branches', 'categories', 'customer_delivery_assignments', 'customer_processing_aliases', 'customer_quote_sheet_customers', 'customer_quote_sheet_items', 'customer_quote_sheets', 'customer_quote_versions', 'customer_recipients', 'customer_sku_aliases', 'customer_sku_remarks', 'customer_skus', 'customers', 'delivery_persons', 'delivery_schedules', 'delivery_signatures', 'delivery_tasks', 'exception_tickets', 'inspection_loss_confirmations', 'inspection_returns', 'inspections', 'inventory', 'inventory_logs', 'market_compare_exclusions', 'market_price_indices', 'market_prices', 'notifications', 'operation_logs', 'order_allocation_batches', 'order_items', 'orders', 'picking_containers', 'picking_items', 'picking_scan_logs', 'picking_tasks', 'processing_logs', 'processing_tasks', 'product_catalog', 'product_substitutions', 'purchase_orders', 'role_definitions', 'role_permissions', 'seasonal_recommendations', 'sign_records', 'sku_suppliers', 'skus', 'smart_classification_rules', 'supplier_categories', 'supplier_preparations', 'supplier_rating_snapshots', 'suppliers', 'system_configs', ]); const added = writable.filter((t) => !PINNED.has(t)); expect( added, `通用数据网关新增了可写表:${added.join(', ')}。写入会绕过领域服务的业务规则与状态机,请勿放开。` ).toEqual([]); }); // 2026-09-23 补:customers 的 delete 此前可经 /api/data 裸删,绕过 // customerDeleteService 的「有历史订单即拒删」与 12 张表级联,留下孤儿行 // (tenant_* schema 由 LIKE ... INCLUDING ALL 克隆,不含外键,DB 侧不会拦)。 // 现由 DENY_DELETE_TABLES 只拦 delete(insert/update 仍走网关,UI 不受影响)。 it('禁止经通用数据网关删除 customers(守卫+级联专用路径不可绕过)', () => { const denyDelete = readSet('DENY_DELETE_TABLES'); expect( denyDelete, 'DENY_DELETE_TABLES 被清空会重新打开 customers 裸删旁路;删除须走 DELETE /customers/:customerCode' ).toContain('customers'); // 名单里的表必须仍然允许经网关 insert/update,否则应改放 DENY_WRITE_TABLES const denyWrite = readSet('DENY_WRITE_TABLES'); const misuse = denyDelete.filter((t) => denyWrite.includes(t)); expect(misuse, `这些表已在 DENY_WRITE_TABLES,应移出 DENY_DELETE_TABLES:${misuse.join(', ')}`).toEqual([]); }); });