私有桶 key 形状白名单把租户分支根写死成主系统的 /^BR…$/,而本系统的
分公司编码是 SUP35143228 这类形状,于是 buildStorageObjectKey 直接抛
Invalid file name(库存→上传报告点「上传并解析」即弹这句英文)。
同一份 BR… 正则还重复写在归属判定与 stripStorageBranchPrefix 里,只改
一处会出现「上传成功但读/签名 403」。现收敛为唯一定义
TENANT_BRANCH_ROOT_RE = /^[A-Z0-9][A-Z0-9_-]{1,29}$/(branch_code 创建
时统一大写),三处使用点同口径;未知小写目录仍一律拒绝,层级上限、
穿越拒收、<branch>/ 前缀策略与存储布局均未动。
310 lines
13 KiB
TypeScript
310 lines
13 KiB
TypeScript
import { runWithBranchRls } from '../db';
|
||
import { buildSignedStoragePath } from './storageSignedUrl';
|
||
import { getTenantDbStore } from './tenantDbContext';
|
||
import { tenantSchemaName } from './tenantSchemaService';
|
||
import { TENANT_BRANCH_ROOT_RE } from './storageBucketConfig';
|
||
|
||
/**
|
||
* T9 SEC-5(2026-10-19 红队第 4 次攻破):存储对象**全链路租户归属**校验。
|
||
*
|
||
* 规则:
|
||
* ① 新 key 带 `<branchCode>/` 前缀 ⇒ 前缀必须等于调用者 branch,否则 403;
|
||
* ② 旧 key(无前缀)⇒ 在**调用者分支的 RLS 上下文**里反查业务表引用;查到本分支放行,
|
||
* 查不到 ⇒ 403(fail-closed,不跨 schema 搜索);
|
||
* ③ 拒绝 `..`/反斜杠/多重编码前缀;无 branchCode 且非超管 ⇒ 403;
|
||
* ④ super_admin 跨租户放行(运维/审计)。
|
||
*
|
||
* 调用点:签名 URL mint(发票 list/上传返回/处理照片等)、OCR/成本/付款凭证 getObject、
|
||
* 以及 invoice_url / storage_path / voucher_paths 等**写入前**校验。
|
||
*/
|
||
|
||
export const OBJECT_OWNER_CHECKS: Record<string, Array<{ table: string; column: string }>> = {
|
||
invoices: [
|
||
{ table: 'invoices', column: 'invoice_url' },
|
||
{ table: 'cost_details', column: 'voucher_url' },
|
||
{ table: 'fixed_costs', column: 'voucher_urls' },
|
||
{ table: 'free_cost_invoices', column: 'storage_path' },
|
||
{ table: 'free_cost_payment_vouchers', column: 'storage_path' },
|
||
],
|
||
'quality-reports': [
|
||
{ table: 'quality_reports', column: 'file_paths' },
|
||
{ table: 'inventory_batch_reports', column: 'file_paths' },
|
||
],
|
||
'inspection-photos': [
|
||
{ table: 'inspections', column: 'inspection_photos' },
|
||
{ table: 'inspection_photo_archive_entries', column: 'filename' },
|
||
],
|
||
'processing-inspection-photos': [{ table: 'processing_tasks', column: 'processing_inspection_photos' }],
|
||
'delivery-photos': [
|
||
{ table: 'picking_items', column: 'outbound_photos' },
|
||
{ table: 'picking_items', column: 'loading_photos' },
|
||
{ table: 'delivery_signatures', column: 'photo_url' },
|
||
{ table: 'purchase_orders', column: 'direct_delivery_photos' },
|
||
{ table: 'purchase_orders', column: 'inbound_photo' },
|
||
],
|
||
uploads: [
|
||
{ table: 'free_cost_invoices', column: 'storage_path' },
|
||
{ table: 'free_cost_payment_vouchers', column: 'storage_path' },
|
||
],
|
||
};
|
||
|
||
export interface StorageOwnerCtx {
|
||
branchCode?: string | null;
|
||
isSuperAdmin?: boolean;
|
||
}
|
||
|
||
/**
|
||
* 分支前缀解析与存储层共用同一个形状定义(`TENANT_BRANCH_ROOT_RE`)。
|
||
* 2026-10-21:这里原先另写了一份 `/^BR…$/`,本系统 `SUP35143228/…` 的 key 因此认不出前缀——
|
||
* 上传成功后读/签名一律 403。分支根形状只允许有一份定义。
|
||
*/
|
||
function parseStorageBranchPrefix(rawKey: string): { branch: string; rest: string } | null {
|
||
const normalized = String(rawKey || '').replace(/\/+/g, '/');
|
||
const slash = normalized.indexOf('/');
|
||
if (slash <= 0) return null;
|
||
const head = normalized.slice(0, slash);
|
||
if (!TENANT_BRANCH_ROOT_RE.test(head)) return null;
|
||
return { branch: head, rest: normalized.slice(slash + 1) };
|
||
}
|
||
|
||
/** 归一 key(拒绝穿越/反斜杠);返回 null 表示非法 */
|
||
export function normalizeStorageObjectKey(raw: unknown): string | null {
|
||
const text = String(raw ?? '').trim().replace(/\\/g, '/');
|
||
if (!text) return null;
|
||
if (text.includes('..') || text.startsWith('/') || /%2f|%5c/i.test(text)) return null;
|
||
let decoded = text;
|
||
try {
|
||
decoded = decodeURIComponent(text);
|
||
} catch {
|
||
return null;
|
||
}
|
||
if (decoded.includes('..') || decoded.includes('\\') || decoded.startsWith('/')) return null;
|
||
return text.replace(/\/+/g, '/');
|
||
}
|
||
|
||
/** 解析 key 的分支前缀(无前缀返回 null) */
|
||
export function readStorageKeyBranch(rawKey: string): string | null {
|
||
const key = String(rawKey || '').replace(/^\/+/, '');
|
||
return parseStorageBranchPrefix(key)?.branch ?? null;
|
||
}
|
||
|
||
/**
|
||
* T9F-1b:旧 key 没有分支前缀,只能按“已知上传命名空间”反查。
|
||
* 绝不能把 `archive/`、`合格/` 等结果/归档目录当成可反查来源(否则毒化行可自引用洗白,
|
||
* finalize 就会读/复制/删归档)。未知命名空间一律不放行,宁缺勿滥。
|
||
*/
|
||
const LEGACY_OWNER_KEY_PREFIXES = [
|
||
'inspection-photos/',
|
||
'processing-inspection-photos/',
|
||
'delivery-photos/',
|
||
'delivery-loading/',
|
||
'sku-direct/',
|
||
'supplier-invoices/',
|
||
'free-cost/',
|
||
'free-cost-invoice/',
|
||
'free-cost-payment/',
|
||
'quality-reports/',
|
||
'uploads/',
|
||
] as const;
|
||
|
||
async function legacyKeyBelongsToBranch(branchCode: string, bucket: string, safeName: string): Promise<boolean> {
|
||
if (!LEGACY_OWNER_KEY_PREFIXES.some((prefix) => safeName.startsWith(prefix))) return false;
|
||
const candidates = OBJECT_OWNER_CHECKS[bucket];
|
||
if (!candidates?.length) return false;
|
||
const schema = tenantSchemaName(branchCode);
|
||
if (!/^tenant_[a-z0-9_-]{2,40}$/.test(schema)) return false;
|
||
try {
|
||
return await runWithBranchRls(branchCode, async (client) => {
|
||
for (const candidate of candidates) {
|
||
if (!/^[a-z_][a-z0-9_]*$/.test(candidate.table) || !/^[a-z_][a-z0-9_]*$/.test(candidate.column)) continue;
|
||
try {
|
||
const exists = await client.query<{ t: string | null }>(
|
||
`SELECT to_regclass(format('%I.%I', $1::text, $2::text))::text AS t`,
|
||
[schema, candidate.table]
|
||
);
|
||
if (!exists.rows[0]?.t) continue;
|
||
const hit = await client.query(
|
||
`SELECT 1 FROM ${schema}.${candidate.table}
|
||
WHERE ${candidate.column}::text LIKE '%' || $1 || '%' LIMIT 1`,
|
||
[safeName]
|
||
);
|
||
if (hit.rowCount) return true;
|
||
} catch {
|
||
// fail-closed
|
||
}
|
||
}
|
||
return false;
|
||
});
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function forbidden(message: string) {
|
||
return Object.assign(new Error(message), { status: 403, code: 'forbidden' });
|
||
}
|
||
|
||
/**
|
||
* 断言对象属于调用者租户;不满足抛 403(code=forbidden)。
|
||
* @param bucket 逻辑桶(invoices/quality-reports/…)
|
||
* @param rawKey 对象 key(可带 `<branch>/` 前缀)
|
||
* @param ctx 调用者分支上下文(无 branchCode 且非超管 ⇒ 403)
|
||
*/
|
||
export async function assertStorageKeyOwned(
|
||
bucket: string,
|
||
rawKey: unknown,
|
||
ctx: StorageOwnerCtx | null | undefined
|
||
): Promise<string> {
|
||
const key = normalizeStorageObjectKey(rawKey);
|
||
if (!key) throw forbidden('对象路径非法');
|
||
// 归档目录是保留期数据,绝不作为可读/可删的源对象(即使业务行被毒化)。
|
||
// 大小写/前后空白变体也一律拒绝(对象存储 key 大小写敏感,但防御纵深不应依赖它)。
|
||
const lowered = key.trim().toLowerCase();
|
||
if (lowered === 'archive' || lowered.startsWith('archive/')) throw forbidden('归档对象不允许作为源对象');
|
||
if (ctx?.isSuperAdmin) return key;
|
||
const branch = String(ctx?.branchCode || '').trim();
|
||
if (!branch) throw forbidden('缺少租户上下文,拒绝访问私有文件');
|
||
const prefixBranch = readStorageKeyBranch(key);
|
||
if (prefixBranch) {
|
||
if (prefixBranch !== branch) throw forbidden('对象不属于当前租户');
|
||
return key;
|
||
}
|
||
if (await legacyKeyBelongsToBranch(branch, bucket, key)) return key;
|
||
throw forbidden('对象不属于当前租户');
|
||
}
|
||
|
||
/**
|
||
* 非桶内对象引用:外链与 data: 内联数据不参与归属校验(按历史语义原样落库)。
|
||
* 仅空白/外链/data: 会被跳过;真正的桶内 key 一律走 assertStorageKeyOwned。
|
||
*/
|
||
function isNonObjectStorageRef(value: string): boolean {
|
||
return /^(?:https?:)?\/\//i.test(value) || /^data:/i.test(value);
|
||
}
|
||
|
||
/**
|
||
* T9 P1(2026-10-19):写入口批量归属断言。**必须在 INSERT/UPDATE 之前 await**。
|
||
*
|
||
* - 逐项调用 `assertStorageKeyOwned`:新 key 校验 `<branch>/` 前缀,旧 key 在调用者分支
|
||
* 的 RLS 上下文里反查业务表引用(`legacyKeyBelongsToBranch`),不做"同步 mint 放行";
|
||
* - 任一桶内 key 不属于当前租户 ⇒ 抛 403(复用 `{ status: 403, code: 'forbidden' }` 形状);
|
||
* - 空白项 / `http(s)://` 外链 / `data:` 内联数据不是桶内对象,跳过(仍原样落库);
|
||
* - 返回归一化后的 key(跳过项不返回),便于调用方核对落库值。
|
||
*
|
||
* @param ctx 调用者分支上下文(无 branchCode 且非超管 ⇒ 403)
|
||
* @param bucket 逻辑桶(invoices/quality-reports/…)
|
||
* @param paths 待写入的 key 列表(也接受单个值,兼容旧调用)
|
||
*/
|
||
export async function assertOwnedStoragePaths(
|
||
ctx: StorageOwnerCtx | null | undefined,
|
||
bucket: string,
|
||
paths: readonly unknown[] | unknown
|
||
): Promise<string[]> {
|
||
const list = Array.isArray(paths) ? paths : paths == null ? [] : [paths];
|
||
const owned: string[] = [];
|
||
for (const raw of list) {
|
||
const value = String(raw ?? '').trim();
|
||
if (!value || isNonObjectStorageRef(value)) continue;
|
||
owned.push(await assertStorageKeyOwned(bucket, value, ctx));
|
||
}
|
||
return owned;
|
||
}
|
||
|
||
export async function canAccessStorageKey(
|
||
bucket: string,
|
||
rawKey: unknown,
|
||
ctx: StorageOwnerCtx | null | undefined
|
||
): Promise<boolean> {
|
||
try {
|
||
await assertStorageKeyOwned(bucket, rawKey, ctx);
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
export interface SignedStoragePathOptions {
|
||
/**
|
||
* 调用方已完成异步归属反查(`assertStorageKeyOwned`)后传 true。
|
||
* 仅用于“无前缀旧 key”:mint 本身是同步的,绝不在这里同步放行任何旧 key。
|
||
*/
|
||
legacyOwnershipVerified?: boolean;
|
||
}
|
||
|
||
/**
|
||
* T9 B1/B2 + T9F-5:带归属校验的签名 URL mint(同步)。
|
||
* · key 带 `<branch>/` 前缀 ⇒ 必须等于 ctx.branchCode;
|
||
* · `archive/<branch>/...` ⇒ 必须等于 ctx.branchCode(归档下载例外,不是业务源 key);
|
||
* · 无前缀旧 key ⇒ **默认 fail-closed 403**;只有调用方先完成异步归属反查
|
||
* (`assertStorageKeyOwned`,见 `buildSignedStoragePathForCtxChecked`)并显式传
|
||
* `legacyOwnershipVerified: true` 才签发。super_admin 是设计上的跨租户运维口。
|
||
* 旧文件需迁移为 `<branch>/` 前缀后才能直接展示
|
||
* (见 docs/design/20261019-storage-legacy-key-migration.md)。
|
||
* 不合规抛 403,由 route/service 决定返回错误或过滤。
|
||
*/
|
||
export function buildSignedStoragePathForCtx(
|
||
ctx: StorageOwnerCtx | null | undefined,
|
||
bucket: string,
|
||
rawKey: unknown,
|
||
options?: SignedStoragePathOptions
|
||
): string {
|
||
const key = normalizeStorageObjectKey(rawKey);
|
||
if (!key) throw forbidden('对象路径非法');
|
||
const store = getTenantDbStore();
|
||
const effectiveCtx = ctx ?? (store?.branchCode ? { branchCode: store.branchCode } : null);
|
||
ctx = effectiveCtx;
|
||
const branch = String(ctx?.branchCode || '').trim();
|
||
const prefixBranch = readStorageKeyBranch(key);
|
||
if (prefixBranch) {
|
||
if (!ctx?.isSuperAdmin && prefixBranch !== branch) throw forbidden('对象不属于当前租户');
|
||
return buildSignedStoragePath(bucket, key);
|
||
}
|
||
const archive = /^archive\/([^/]+)\//.exec(key);
|
||
if (archive && TENANT_BRANCH_ROOT_RE.test(archive[1])) {
|
||
if (!ctx?.isSuperAdmin && archive[1] !== branch) throw forbidden('归档对象不属于当前租户');
|
||
return buildSignedStoragePath(bucket, key);
|
||
}
|
||
// 无前缀旧 key:mint 侧绝不“同步放行”。
|
||
if (ctx?.isSuperAdmin) return buildSignedStoragePath(bucket, key);
|
||
if (options?.legacyOwnershipVerified && branch) return buildSignedStoragePath(bucket, key);
|
||
throw forbidden('旧存储文件名缺少分公司前缀,已停止同步签发;请先迁移为 <branch>/ 前缀对象');
|
||
}
|
||
|
||
/**
|
||
* T9F-5 的“签发前异步反查”路径:无前缀旧 key 先走 `assertStorageKeyOwned`
|
||
* (本分支 RLS 上下文 + 业务表 LIKE 反查),通过后才签发;跨租户/毒化/无上下文一律 403。
|
||
* 供 `/api/storage/:bucket/public-url` 等读入口使用,既不放行旧 key,也保留本分支旧文件可用性。
|
||
*/
|
||
export async function buildSignedStoragePathForCtxChecked(
|
||
ctx: StorageOwnerCtx | null | undefined,
|
||
bucket: string,
|
||
rawKey: unknown
|
||
): Promise<string> {
|
||
const key = normalizeStorageObjectKey(rawKey);
|
||
if (!key) throw forbidden('对象路径非法');
|
||
// 与同步 mint 同口径:显式 ctx 优先,其次请求级 tenant store(列表/装饰路径常只传 undefined)。
|
||
const store = getTenantDbStore();
|
||
const effectiveCtx = ctx ?? (store?.branchCode ? { branchCode: store.branchCode } : null);
|
||
// 归档对象不是业务源 key:按前缀/分支判定即可(assertStorageKeyOwned 对所有 archive 一律 403)。
|
||
const lowered = key.trim().toLowerCase();
|
||
if (lowered === 'archive' || lowered.startsWith('archive/')) {
|
||
return buildSignedStoragePathForCtx(effectiveCtx, bucket, key);
|
||
}
|
||
if (readStorageKeyBranch(key)) return buildSignedStoragePathForCtx(effectiveCtx, bucket, key);
|
||
await assertStorageKeyOwned(bucket, key, effectiveCtx);
|
||
return buildSignedStoragePathForCtx(effectiveCtx, bucket, key, { legacyOwnershipVerified: true });
|
||
}
|
||
|
||
/** 展示/列表用的宽容版:旧 key 未迁移时返回 null(不 500),由调用方决定空展示。 */
|
||
export function tryBuildSignedStoragePathForCtx(
|
||
ctx: StorageOwnerCtx | null | undefined,
|
||
bucket: string,
|
||
rawKey: unknown,
|
||
options?: SignedStoragePathOptions
|
||
): string | null {
|
||
try {
|
||
return buildSignedStoragePathForCtx(ctx, bucket, rawKey, options);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|