Files
SupplierSystem/server/src/services/accessPolicy.ts
T
Ubuntu 5fa2bbfd55
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- 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 超长修复
2026-10-19 16:16:51 +08:00

510 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { QuerySpec } from './queryExecutor';
import type { TenantContext } from './tenantScope';
/** 通用数据接口允许访问的表(白名单外一律拒绝) */
const ALLOWED_TABLES = new Set([
'after_sales',
'alias_recognition_logs',
'allocation_tasks',
'bid_prices',
'branches',
'categories',
'cost_adjustments',
'cost_details',
'customer_delivery_assignments',
'customer_quote_versions',
'customer_quote_sheets',
'customer_quote_sheet_items',
'customer_quote_sheet_customers',
'customer_sku_aliases',
'customer_processing_aliases',
'customer_sku_remarks',
'customer_skus',
'customer_statements',
'statement_lines',
'statement_disputes',
'customers',
'delivery_person_users',
'delivery_persons',
'delivery_tasks',
'exception_tickets',
'fixed_costs',
'inspections',
'inspection_loss_confirmations',
'inspection_returns',
'inventory',
'inventory_logs',
'invoices',
'notifications',
'operation_logs',
'order_items',
'order_item_returns',
'order_item_fulfillments',
'orders',
'picking_items',
'picking_tasks',
'picking_containers',
'picking_scan_logs',
'permissions',
'processing_logs',
'processing_tasks',
'product_catalog',
'profiles',
'purchase_orders',
'purchaser_users',
'role_permissions',
'role_definitions',
'sign_records',
'sku_suppliers',
'skus',
'smart_classification_rules',
'supplier_categories',
'supplier_preparations',
'supplier_statements',
'supplier_rating_snapshots',
'product_substitutions',
'delivery_signatures',
'customer_recipients',
'market_prices',
'market_compare_exclusions',
'market_price_indices',
'seasonal_recommendations',
'order_allocation_batches',
'delivery_schedules',
'supplier_users',
'suppliers',
'system_configs',
'user_roles',
]);
/** 任何账号都不允许通过通用数据接口写入(必须走专用受控路由,如 /api/auth、/api/suppliers) */
const DENY_WRITE_TABLES = new Set([
'user_roles',
'permissions',
/**
* 全局授权表(SEC-4,2026-10-19):`role_permissions` / `role_definitions` 是 **public**
* 平台表(无 branch_code)。旧实现只把角色写端点收归 super_admin,却仍允许 admin 经通用网关
* `/api/data/query` 对这两张表 insert/update/delete(实测 HTTP 200 + 真实写 SQL),
* 等于绕过 `/api/roles` 的 super_admin 限制,甚至可给 super_admin 写权限。
* ⇒ 网关一律 deny(super_admin 也必须走 `/api/roles`);读取不受影响(前端 useAuth 只 select)。
* 放在这里(而不是 ADMIN_WRITE_TABLES)才能同时拦住超管绕过审计的裸写。
*/
'role_permissions',
'role_definitions',
'profiles',
'supplier_users',
'purchaser_users',
'delivery_person_users',
// 履约关联只读:写入须走订单/分配/备货 workflow
'order_item_fulfillments',
// 财务:写入须走 /api/workflow/finance|cost/*
'customer_statements',
'supplier_statements',
'statement_lines',
'statement_disputes',
'statement_payments',
'invoices',
'cost_adjustments',
'cost_details',
'fixed_costs',
'after_sale_returns',
'order_item_returns',
// 库存台账(2026-10-14 多 agent 审计 P0-1 收口):写入必须走受控路由
// (验收 / 独立入库 / 自采入库 / 库存调整 / 出库);**网关裸写会绕过**
// 「备注必填 + 双日志 + FIFO/预留保护」,且真库已出现「有库存、零流水」批次(3 批 37.50,无法追溯)。
// 读取不受影响:库存查询与库存流水页签照旧(前端对这两张表只有 SELECT)。
'inventory',
'inventory_logs',
]);
/**
* 任何账号都不允许通过通用数据接口「删除」的表:删除必须走带守卫 + 级联的专用路由
* (customers → DELETE /customers/:customerCode;order_items → 订单明细保存链路)。
*
* 独立于 DENY_WRITE_TABLES:本名单只拦 delete,不影响 insert/update(客户新增/编辑/
* 批量导入仍走数据网关)。放在 isSuperAdmin 短路之前判定,超管同样被拦。
*
* ⚠️ `orders` **有意不在本名单**:网关执行层对 `orders` 的 delete 已特判到
* `deleteOrderWithDependencies`(带守卫与级联),拦在这里会把它一起挡掉
* (`tests/accessPolicy.customerDelete.test.ts` 钉住了这条)。
* 主系统分配单的"不许删"守卫加在那两个执行入口里(`moveOrderToTrash` /
* `deleteOrderWithDependencies`),见 services/mainSystemStockout 与 orderDeleteService。
*
* `order_items` 于 2026-10-10 并入:网关对它是**裸 DELETE**(绕过履约清理),
* 而开发者口径要求"主系统分配过来的商品不能删",删明细只能走订单明细保存链路。
*/
const DENY_DELETE_TABLES = new Set(['customers', 'order_items']);
/** 仅管理员(super_admin/admin)可写;`role_permissions` 已移入 DENY_WRITE_TABLES(SEC-4 收口) */
const ADMIN_WRITE_TABLES = new Set(['branches', 'system_configs']);
/**
* 非内部员工(finance/warehouse/delivery/supplier 等受限角色)写表所需权限码。
* 空数组表示任何已登录账号都可写(如日志、消息已读状态)。
* 未列出的表对受限角色拒绝写入。
*/
const WRITE_PERMISSIONS: Record<string, string[]> = {
// 改头/明细需 order_edit(或录单/建单等);order_manage 仅菜单访问,不隐含写
orders: [
'order_edit',
'order_create',
'order_entry',
'order_status_update',
'order_delete',
'allocation_manage',
],
order_items: [
'order_edit',
'order_create',
'order_entry',
'order_status_update',
'allocation_manage',
],
// 只读白名单见 READ;此处占位避免受限角色误写(实际已被 DENY_WRITE 拦截)
order_item_fulfillments: [
'order_edit',
'order_manage',
'order_create',
'order_entry',
'purchase_manage',
'preparation_manage',
'allocation_manage',
],
picking_tasks: ['picking_manage', 'delivery_manage', 'order_manage', 'order_status_update', 'processing_manage'],
picking_items: ['picking_manage', 'delivery_manage', 'order_manage', 'order_status_update', 'processing_manage'],
bid_prices: ['bid_manage', 'order_manage'],
allocation_tasks: ['allocation_manage', 'order_manage'],
customers: ['customer_manage', 'order_entry'],
customer_skus: ['customer_manage', 'alias_manage', 'order_entry', 'order_manage'],
customer_quote_versions: ['customer_manage', 'bid_manage', 'order_entry', 'order_manage'],
customer_quote_sheets: ['customer_manage', 'bid_manage', 'order_entry', 'order_manage'],
customer_quote_sheet_items: ['customer_manage', 'bid_manage', 'order_entry', 'order_manage'],
customer_quote_sheet_customers: ['customer_manage', 'bid_manage', 'order_entry', 'order_manage'],
customer_sku_aliases: ['customer_manage', 'alias_manage', 'order_entry', 'order_manage'],
customer_processing_aliases: ['customer_manage', 'alias_manage', 'order_entry', 'order_manage'],
customer_sku_remarks: ['customer_manage', 'alias_manage', 'order_entry', 'order_manage'],
skus: ['sku_manage', 'product_manage', 'order_entry', 'order_manage', 'supplier_supply_manage', 'customer_manage', 'bid_manage'],
categories: [
'category_manage',
'product_manage',
'order_entry',
'order_manage',
'picking_manage',
'delivery_manage',
'purchase_manage',
'preparation_manage',
'allocation_manage',
'inspection_manage',
'cost_manage',
'customer_manage',
],
product_catalog: [
'category_manage',
'sku_manage',
'product_manage',
'order_entry',
'order_manage',
'picking_manage',
'delivery_manage',
'purchase_manage',
'preparation_manage',
'allocation_manage',
'inspection_manage',
'cost_manage',
'customer_manage',
],
smart_classification_rules: ['category_manage', 'product_manage'],
suppliers: ['supplier_manage', 'supplier_supply_manage', 'allocation_manage', 'preparation_manage'],
supplier_categories: ['supplier_manage', 'category_manage'],
sku_suppliers: ['supplier_manage', 'allocation_manage', 'supplier_supply_manage'],
supplier_preparations: ['preparation_manage', 'allocation_manage', 'order_manage'],
purchase_orders: ['purchase_manage', 'preparation_manage', 'allocation_manage', 'order_manage', 'supplier_supply_manage'],
// purchase_manage:采购完成入库时写库存
inventory: ['inventory_manage', 'purchase_manage'],
inventory_logs: ['inventory_manage', 'purchase_manage'],
// preparation_manage:供应商备货完成时自动生成验收单;order_*:订单详情推进全流程
inspections: ['inspection_manage', 'processing_manage', 'inventory_manage', 'preparation_manage', 'order_manage', 'order_status_update'],
inspection_returns: ['inspection_manage', 'processing_manage', 'inventory_manage'],
inspection_loss_confirmations: ['inspection_manage', 'processing_manage', 'inventory_manage'],
processing_logs: ['processing_manage', 'inspection_manage'],
processing_tasks: ['processing_manage', 'inspection_manage', 'inventory_manage'],
delivery_tasks: ['delivery_manage', 'order_manage', 'order_status_update'],
customer_delivery_assignments: ['delivery_manage', 'delivery_person_manage'],
delivery_persons: ['delivery_person_manage', 'delivery_manage'],
sign_records: ['delivery_manage', 'order_manage', 'order_status_update'],
after_sales: ['aftersales_manage'],
exception_tickets: ['exception_manage'],
invoices: ['invoice_manage', 'finance_manage'],
cost_details: ['cost_manage', 'finance_manage', 'inspection_manage', 'inventory_manage', 'order_manage', 'order_status_update'],
cost_adjustments: ['cost_manage', 'finance_manage'],
fixed_costs: ['cost_manage', 'finance_manage'],
customer_statements: ['statement_manage', 'finance_manage'],
supplier_statements: ['statement_manage', 'finance_manage'],
statement_lines: ['statement_manage', 'finance_manage'],
statement_disputes: ['statement_manage', 'finance_manage'],
picking_containers: ['picking_manage', 'delivery_manage', 'order_manage', 'order_status_update', 'processing_manage'],
picking_scan_logs: ['picking_manage', 'delivery_manage', 'order_manage', 'order_status_update', 'processing_manage'],
supplier_rating_snapshots: ['supplier_manage'],
product_substitutions: ['order_manage', 'allocation_manage'],
delivery_signatures: ['delivery_manage', 'order_manage', 'order_status_update'],
customer_recipients: ['customer_manage', 'delivery_manage'],
market_prices: ['bid_manage', 'order_manage', 'product_manage'],
market_compare_exclusions: ['bid_manage', 'order_manage', 'product_manage'],
market_price_indices: ['bid_manage', 'order_manage', 'product_manage'],
seasonal_recommendations: ['bid_manage', 'order_manage', 'product_manage'],
order_allocation_batches: ['allocation_manage', 'order_manage'],
delivery_schedules: ['delivery_manage', 'delivery_person_manage'],
// A5: 敏感表须显式权限;空数组语义为拒绝(见 assertPermission)
notifications: ['system_manage', 'user_manage', 'order_manage', 'order_view'],
operation_logs: ['log_view', 'system_manage'],
alias_recognition_logs: ['alias_manage', 'order_entry', 'log_view'],
};
const READ_PERMISSIONS: Record<string, string[]> = {
...WRITE_PERMISSIONS,
// order_manage / order_view:菜单与只读;写订单仍走 WRITE(order_edit 等)
orders: [
...(WRITE_PERMISSIONS.orders || []),
'order_manage',
'order_view',
],
order_items: [
...(WRITE_PERMISSIONS.order_items || []),
'order_manage',
'order_view',
],
// branches:任意已登录用户可读(见 assertTableAccess 特例)
branches: ['system_manage', 'branch_manage', 'user_manage'],
permissions: ['role_manage', 'user_manage'],
role_permissions: ['role_manage', 'user_manage'],
role_definitions: ['role_manage', 'user_manage'],
// system_configs:白名单 config_key 已登录可读(见 assertTableAccess);其余仍需下列权限
system_configs: ['system_config', 'system_manage'],
user_roles: ['user_manage', 'role_manage'],
profiles: ['user_manage'],
supplier_users: ['supplier_manage'],
purchaser_users: ['purchase_manage'],
delivery_person_users: ['delivery_person_manage', 'delivery_manage'],
cost_details: ['cost_manage', 'finance_manage', 'statement_manage'],
cost_adjustments: ['cost_manage', 'finance_manage'],
fixed_costs: ['cost_manage', 'finance_manage'],
invoices: ['invoice_manage', 'finance_manage'],
customer_statements: ['statement_manage', 'finance_manage'],
supplier_statements: ['statement_manage', 'finance_manage'],
};
function forbidden(message: string) {
return Object.assign(new Error(message), { code: 'forbidden' });
}
/** 登录用户可只读的 system_configs 键(侧栏/空闲登出/打印/AI 图;不含密钥) */
const SYSTEM_CONFIG_PUBLIC_READ_KEYS = new Set([
'nav_menu_layout',
'auth_idle_timeout_minutes',
'print_templates',
'delivery_html_templates',
'sku_ai_image',
]);
function hasEqFilter(spec: QuerySpec, column: string, value: unknown) {
return (spec.filters || []).some((filter) => filter.op === 'eq' && filter.column === column && filter.value === value);
}
function isAllowlistedSystemConfigRead(spec: QuerySpec) {
if (spec.table !== 'system_configs' || spec.action !== 'select') return false;
return (spec.filters || []).some(
(filter) =>
filter.op === 'eq' &&
filter.column === 'config_key' &&
SYSTEM_CONFIG_PUBLIC_READ_KEYS.has(String(filter.value ?? ''))
);
}
function hasInFilterContaining(spec: QuerySpec, column: string, values: string[]) {
return (spec.filters || []).some((filter) => {
if (filter.op !== 'in' || filter.column !== column || !Array.isArray(filter.value)) return false;
return filter.value.every((value) => values.includes(String(value)));
});
}
function assertPermission(ctx: TenantContext, permissions: string[], action: '读取' | '写入', table: string) {
// A5: 空权限列表 = 拒绝(不再「放行」)
if (!permissions.length) {
throw forbidden(`无权${action}表 ${table}(未配置访问权限)`);
}
if (!permissions.some((perm) => ctx.permissions.includes(perm))) {
throw forbidden(`无权${action}表 ${table},需要权限:${permissions.join(' / ')}`);
}
}
/**
* TEC-1.3:敏感表禁止 select=* / 空 select,须显式列(仍走标识符白名单)。
* 降低同分公司低权限用户一次拖全列的风险。
*/
const SENSITIVE_SELECT_TABLES = new Set([
'operation_logs',
'profiles',
'user_roles',
'supplier_users',
'purchaser_users',
'delivery_person_users',
'invoices',
'customer_statements',
'supplier_statements',
'statement_lines',
'statement_disputes',
]);
/** 供单测与 data 路由调用 */
export function assertSensitiveSelectColumns(spec: QuerySpec) {
if (spec.action !== 'select') return;
if (!SENSITIVE_SELECT_TABLES.has(spec.table)) return;
const select = String(spec.select || '').trim();
if (!select || select === '*') {
throw forbidden(`表 ${spec.table} 禁止 select=*,请显式指定列`);
}
// 含 `*` 片段(如 `*, embed(...)`)同样拒绝
const parts = select.split(',').map((p) => p.trim());
if (parts.some((p) => p === '*' || p.startsWith('*'))) {
throw forbidden(`表 ${spec.table} 禁止 select 含 *,请显式指定列`);
}
}
/**
* T9F(2026-10-19 红队):通用数据网关不得写“存储对象 key”列。
*
* 这些列的值会参与后续 storage 对象的归属校验;如果允许客户端经 /api/data 任意
* 写入,就能把 `archive/<other-branch>/...` 之类的 key 毒化进业务行,再借
* “旧 key 反查业务表”的归属逻辑洗白,进而跨租户读取/删除对象。
* 因此 insert/update 一律拒绝(super_admin 也必须走业务接口),delete 不受影响。
*/
const SENSITIVE_STORAGE_WRITE_COLUMNS = new Set([
'inspection_photos',
'photo_url',
'outbound_photos',
'loading_photos',
'direct_delivery_photos',
'inbound_photo',
'processing_inspection_photos',
'invoice_url',
'voucher_url',
'voucher_urls',
'storage_path',
'file_paths',
'quality_report_files',
]);
/**
* 递归查找敏感存储字段(含 JSON/JSONB 列里的嵌套对象与数组项)。
* 只认列名本身,不按值猜;命中即拒绝,避免 `{ processing_details: { inspection_photos: [...] } }`
* 这类“外层列名合法、内层 key 毒化”的绕过。
*/
function findSensitiveStorageField(value: unknown, depth = 0): string | null {
if (!value || typeof value !== 'object' || depth > 12) return null;
if (Array.isArray(value)) {
for (const item of value) {
const hit = findSensitiveStorageField(item, depth + 1);
if (hit) return hit;
}
return null;
}
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
// SQL 列名在 queryExecutor 里是**不加引号**拼接的,PostgreSQL 会把 `Inspection_Photos`
// 折叠成 `inspection_photos`;因此必须大小写归一后再比对,否则大小写变体可绕过。
const normalized = key.trim().toLowerCase();
if (SENSITIVE_STORAGE_WRITE_COLUMNS.has(normalized)) return normalized;
const hit = findSensitiveStorageField(child, depth + 1);
if (hit) return hit;
}
return null;
}
function assertNoSensitiveStorageWrites(spec: QuerySpec) {
if (spec.action !== 'insert' && spec.action !== 'update') return;
const payload = spec.action === 'insert' ? spec.insertData : spec.updateData;
if (!payload || typeof payload !== 'object') return;
const column = findSensitiveStorageField(payload);
if (column) {
throw forbidden(`字段 ${column} 不允许通过数据接口写入,请使用专用接口`);
}
}
/** 校验通用数据接口的表访问权限,违规时抛错 */
export function assertTableAccess(spec: QuerySpec, ctx: TenantContext | null) {
if (!ALLOWED_TABLES.has(spec.table)) {
throw forbidden(`不允许访问表 ${spec.table}`);
}
if (!ctx) {
throw forbidden('请先登录');
}
assertNoSensitiveStorageWrites(spec);
assertSensitiveSelectColumns(spec);
if (spec.action === 'select') {
if (ctx.isSuperAdmin) return;
if (spec.table === 'profiles' && hasEqFilter(spec, 'id', ctx.userId)) return;
if (spec.table === 'user_roles' && hasEqFilter(spec, 'user_id', ctx.userId)) return;
if (spec.table === 'role_permissions' && hasInFilterContaining(spec, 'role', ctx.roles)) return;
if (spec.table === 'permissions' && ctx.roles.length > 0) return;
// 分公司列表 / 站内通知:已登录即可读(租户过滤仍生效)
if (spec.table === 'branches' || spec.table === 'notifications') return;
// system_configs:白名单键已登录可读(租户/平台范围仍由 applyTenantScope 收窄)
if (isAllowlistedSystemConfigRead(spec)) return;
// 供应商:读本人绑定行(Web 备货表解析 supplier_code)
if (
ctx.isSupplierAccount &&
spec.table === 'supplier_users' &&
hasEqFilter(spec, 'user_id', ctx.userId)
) {
return;
}
if (ctx.isSupplierAccount && ['supplier_preparations', 'purchase_orders'].includes(spec.table)) return;
// 采购员账号只读绕过(写入见下方,已收窄至采购单/验收单);数据范围仍受租户过滤约束
if (ctx.purchaserCode && ['purchase_orders', 'inspections', 'inventory', 'inventory_logs'].includes(spec.table)) return;
const required = READ_PERMISSIONS[spec.table];
if (!required) {
throw forbidden(`无权读取表 ${spec.table}`);
}
assertPermission(ctx, required, '读取', spec.table);
return;
}
if (spec.action === 'delete' && DENY_DELETE_TABLES.has(spec.table)) {
throw forbidden(`表 ${spec.table} 不允许通过数据接口删除,请使用专用接口`);
}
if (DENY_WRITE_TABLES.has(spec.table)) {
throw forbidden(`表 ${spec.table} 不允许通过数据接口写入`);
}
const isAdmin = ctx.isSuperAdmin || ctx.roles.includes('admin');
if (ADMIN_WRITE_TABLES.has(spec.table)) {
if (!isAdmin) {
throw forbidden(`仅管理员可修改 ${spec.table}`);
}
return;
}
if (ctx.isSuperAdmin) return;
// 已登录用户可标记通知已读
if (spec.table === 'notifications') return;
// 采购员账号:允许处理采购单 + 到货验收(PurchaserDashboard 流程)。
// 安全收窄:库存表(inventory/inventory_logs)的写入不再绕过权限码,须持有
// inventory_manage 或 purchase_manage(内置 purchaser 角色已种子授予 purchase_manage,
// 因此正常采购员流程不受影响);读取绕过见上方 select 分支。
if (ctx.purchaserCode && ['purchase_orders', 'inspections'].includes(spec.table)) {
return;
}
const required = WRITE_PERMISSIONS[spec.table];
if (!required) {
throw forbidden(`无权写入表 ${spec.table}`);
}
assertPermission(ctx, required, '写入', spec.table);
}