开发者 2026-10-15:「分拣开关默认都是开启的,先修复 p0」。
确定性复现(同一函数、同一库、同一分公司,只有调用上下文不同;清缓存后各测两次):
· ALS 外 ⇒ {enabled:true, source:'inferred'}(连接角色 supplier = owner,绕过 RLS)
· ALS 内 ⇒ {enabled:false, source:'inferred'}(连接角色 canteen_app_rls)
真值应为 true:public.user_roles 里 BR002 有 picker + delivery,role_permissions 也授了
picking_manage(owner 视角:user_roles 11 行 / role_permissions×{picker,delivery} 2 行)。
且全库**没有任何 picking_workflow_enabled 配置行**(public/br001/br002/br003/template 都只有
picking_task_mode)⇒ 每个分公司都落在「角色推断」这条路上,全部受影响。
根因三层:
① 推断读的四张表(user_roles/profiles/role_permissions/permissions)都在 public 且都开了 RLS;
② 策略 profiles_self_select = USING(id = auth.uid()) / user_roles_self_select = USING(user_id = auth.uid()),
而 auth.uid() 在本部署是桩、canteen_app_rls 下恒 NULL ⇒ 非 owner 读到 0 行;
③ 读法用了 ALS 感知的 pool.query ⇒ 租户上下文里走的是已被 SET LOCAL ROLE canteen_app_rls 的请求级连接。
叠加 30s 按分公司键的缓存,先到的上下文会污染另一个 30 秒。
改法:推断改走 getRawPoolConnect() 的**独立 owner 连接**(finally 归还),roleHasPermission 同类一并改。
⚠️ getRawPoolQuery 绕不过去(实测同一 pg_backend_pid + canteen_app_rls):pg.Pool.query 内部会调
this.connect(),而 pool.connect 已被 ALS 包装。机制实证(ALS 内同时打印两条连接):
租户连接 canteen_app_rls pid …160 / owner 连接 supplier pid …161,user_roles = 11 行。
落地踩到的两个坑(已写进代码/设计文):
· 惰性解析:首版在模块顶层求值 getRawPoolConnect(),而既有 20 个测试文件对 ../src/db 是**部分 mock**
(vi.mock 对不存在的导出**抛错**而非 undefined)⇒ 那些文件 import 即崩(44 failed)。现改为函数内惰性
解析 + try/catch,取不到才退回(仅测试环境会走到,生产恒有该导出)。
· 白名单守卫:routeLayerBoundary 的「getRawPoolConnect 消费方白名单只能缩小」按该断言自身的指示
显式加条目并写明理由(指向设计文),而不是绕过检查器。
改前 → 改后(真跑):ALS 内 {enabled:false} → {enabled:true};ALS 内外交替 4 次全部 true(确定性)。
它同时是两个 P0 的触发条件(开关为关 ⇒ 订单走 !pickingEnabled 分支):
· 「订单到 90 却零出库流水、库存分文未扣」(评审 A §3.2)
· 「多行单整单抵扣只抵第一行」(评审 B §5)
本提交只拔触发条件,不改这两条路径本身(next)。
测试:新增 pickingWorkflowInferenceOwnerConn.test.ts(6 例;mock 出「租户连接被 RLS 挡成 0 行 /
owner 连接看得到真值」两种情况)。真跑反向验证:把 ownerQuery 换回 pool.query ⇒ 该文件 3 例转红。
验证:server tsc 0 error;vitest 25 failed / 3005 passed(444 文件)——失败文件数与基线 25 相同、
无新增失败(3005 = 原 2999 + 新增 6);设计门禁 8 通过 / 1 红(check-ai-cost) / 1 未执行,与改动前同基线。
设计:docs/design/20261015-分拣开关角色推断被RLS上下文污染.md
231 lines
10 KiB
TypeScript
231 lines
10 KiB
TypeScript
/**
|
||
* 后端「封装边界」守卫。
|
||
*
|
||
* 目的:把审计出来的边界用可机检的方式固定住 —— 只允许收紧,不允许放松。
|
||
* - 路由层不得新增内嵌 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<string, number> = {
|
||
'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([]);
|
||
});
|
||
});
|