Files
SupplierSystem/server/tests/storageIsolation.test.ts
Ubuntu a7bf284aed
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(存储隔离): 图片/归档包的落点收紧 —— 前缀为空不再可能静默写进主系统桶根
开发者核查:「定时脚本里那个图片压缩,会不会还是指向主系统的图片存放位置?」

**结论:不会**,但配置面有 4 个口子会让它**退化**成桶根(= 主系统图片区)。本系统与主系统共用
同一个 COS 桶(sku-imge-1343576026),对象只能靠前缀分开;前缀一丢两边互相可见、同名互相覆盖。

涉及的链路(都走 getStorageProvider(),前缀一改即全局生效;归档/压缩逻辑本身**未动**):
  · 定时「验收照片归档」每日 04:00 把满 60 天的照片 gzip 打成 archive/<分公司>/<年月>.tar.gz
  · 按需缩略图 storageThumbnail(sharp 缩放 + mozjpeg)写回 thumb/<宽>/…
  · 前端那个「图片压缩」只产出 base64 data URL 喂 AI 识别,不落任何存储

四个口子 → 处理:
  1. server/.env.example:`S3_KEY_PREFIX` 原是**注释行**(上一行 STORAGE_DIR 却是生效行)⇒ 照抄建 .env
     再启用 s3 就写桶根。改为**生效行**,注释写明「勿删勿留空;留空 ⇒ 写进桶根 = 主系统图片区」。
  2. docker-compose.prod.yml / docker-compose.split.yml:只设 STORAGE_DIR、**不传任何 S3_***
     ⇒ 谁加一句 STORAGE_PROVIDER=s3 就没有前缀。现透传 STORAGE_PROVIDER/S3_*,并给
     `S3_KEY_PREFIX` 兜底 `${S3_KEY_PREFIX:-supplier-system}`(已用 yaml 解析核对两个服务)。
  3. /api/health/details 的 storage 段**不回 keyPrefix** ⇒ 部署后看不出隔离有没有生效。
     getStorageProviderInfo() 增加 keyPrefix + keyPrefixConfigured;本地驱动改回**绝对**目录。
  4. README 仍写主系统默认 `STORAGE_DIR = ./uploads` ⇒ 更正为 ./uploads-supplier 并补 S3_KEY_PREFIX 一行。

代码面(新增,最小):STORAGE_PROVIDER=s3 且前缀为空时打印
`[storage] ⚠️ … 对象将写入**桶根**,与主系统图片混放 …`。只告警**不抛错** —— 抛错会连累上传/缩略图/归档
整条链路,而「写错地方」从 /api/health/details 就能立刻看出来并回滚。

回归守卫 server/tests/storageIsolation.test.ts(10 例):.env.example 两个隔离项必须是生效行、两个 compose
必须有前缀兜底、前缀缺失必须告警且诊断面可辨、归档包/照片对象键带 supplier-system/、空前缀确实落桶根。
**反向对照已做**:注释掉 .env.example 的前缀 / 删掉 compose 兜底行 ⇒ 对应两条用例立刻红,还原后转绿。

实测(真实配置 + 真库):
  · 有效配置 = 驱动 s3、桶 sku-imge-1343576026、前缀 supplier-system、本地根
    /home/ubuntu/harness/suppler/SupplierSystem/server/uploads-supplier(**不是**主系统仓库)
  · 对象键 = supplier-system/inspection-photos/…、supplier-system/inspection-photos/archive/BR003/2026-08.tar.gz
  · 4 个租户 schema 照片引用 0 行 / 归档台账 0 行 ⇒ 该任务至今零产出,**无历史污染**

验证:tsc --noEmit 通过;storageIsolation 10/10;服务端全量 377 文件 / 2368 用例 ⇒ 失败 25 文件
= 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice(非本次引入);API 3022 /api/health = ok,
日志无「桶根」误告警。
设计记录:docs/design/20260923-inspection-photo-archive.md §8.1 + 修订 v3
门禁:bash tools/design-consistency/run-all.sh --verify ⇒ 通过 8 / 未通过 1(check-ai-cost 有意为红) / 未执行 1(verify-facts 无 psql)
2026-10-11 12:56:42 +08:00

134 lines
6.2 KiB
TypeScript
Raw Permalink 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 { readFileSync } from 'node:fs';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
/**
* **本系统存储隔离**(developer 2026-10-10 核查:「定时脚本里那个图片压缩,会不会还是指向
* 主系统的图片存放位置?」)。
*
* 本系统与主系统**同机开发、共用同一个 COS 桶**,对象只能靠前缀隔离:
* · 本系统 = `supplier-system/{bucket}/{文件名}`
* · 主系统 = `{bucket}/{文件名}`(桶根)
* 前缀一丢,我们的照片/归档包就落进**主系统的图片区**(互相可见、同名互相覆盖)。
*
* 与本主题相关的两条链路(都走 `getStorageProvider()`,所以前缀对它们同时生效):
* ① 定时任务「验收照片归档」每日 04:00 把满 60 天的照片 **gzip 打成**
* `inspection-photos/archive/<分公司>/<年月>.tar.gz`(`inspectionPhotoArchiveService` + `TarGzWriter`);
* ② 按需缩略图 `storageThumbnail`(sharp 缩放 + mozjpeg 压缩)写回 `thumb/<宽>/…`。
*
* 这里钉住四件事:
* ① `.env.example` 里两个隔离项**都是生效行**(前缀曾被注释掉 —— 照抄建 .env 即写进桶根);
* ② 两个 docker-compose 都透传 S3_* 且给 `S3_KEY_PREFIX` 兜底 `supplier-system`;
* ③ 前缀为空时**必须告警**(写到错地方不能是静默的),且 `/api/health/details` 能看出前缀有没有生效;
* ④ 归档包的最终对象键确实在我们前缀之下。
*/
const SERVER_DIR = path.resolve(__dirname, '..');
const ROOT_DIR = path.resolve(SERVER_DIR, '..');
function read(relFromRoot: string) {
return readFileSync(path.join(ROOT_DIR, relFromRoot), 'utf8');
}
describe('存储隔离项:`.env.example` 必须是生效行', () => {
const envExample = read('server/.env.example');
it('STORAGE_DIR=./uploads-supplier 生效(不得回落到 server/uploads)', () => {
expect(envExample).toMatch(/^STORAGE_DIR=\.\/uploads-supplier$/m);
});
it('S3_KEY_PREFIX=supplier-system 生效(不能是注释;共用一个桶时前缀是唯一隔离手段)', () => {
expect(envExample).toMatch(/^S3_KEY_PREFIX=supplier-system$/m);
expect(envExample).not.toMatch(/^#\s*S3_KEY_PREFIX=/m);
});
it('注释里写明「留空 = 写进主系统桶根」的后果', () => {
expect(envExample).toContain('桶根');
});
it('README 的存储行不再写主系统默认值', () => {
const readme = read('README.md');
expect(readme).toMatch(/\|\s*`STORAGE_DIR`\s*\|[^|]*\|\s*`\.\/uploads-supplier`\s*\|/);
expect(readme).toMatch(/\|\s*`S3_KEY_PREFIX`\s*\|/);
});
});
describe('存储隔离项:docker-compose 必须透传并兜底前缀', () => {
for (const file of ['docker-compose.prod.yml', 'docker-compose.split.yml']) {
it(`${file} 给 S3_KEY_PREFIX 兜底 supplier-system`, () => {
const compose = read(file);
expect(compose).toContain('S3_KEY_PREFIX: ${S3_KEY_PREFIX:-supplier-system}');
// 只设 STORAGE_DIR、不传任何 S3_* 的写法(旧状态)会让"启用 s3"变成写桶根
expect(compose).toMatch(/S3_BUCKET:/);
expect(compose).toMatch(/STORAGE_PROVIDER:/);
});
}
});
describe('存储隔离项:前缀缺失必须告警 + 诊断面可见', () => {
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
vi.resetModules();
});
async function loadProviderInfo(keyPrefix: string) {
vi.resetModules();
vi.stubEnv('JWT_SECRET', 'test-secret');
vi.stubEnv('STORAGE_PROVIDER', 's3');
vi.stubEnv('S3_ENDPOINT', 'https://cos.example.com');
vi.stubEnv('S3_BUCKET', 'sku-imge-test');
vi.stubEnv('S3_ACCESS_KEY_ID', 'ak');
vi.stubEnv('S3_SECRET_ACCESS_KEY', 'sk');
vi.stubEnv('S3_KEY_PREFIX', keyPrefix);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
const { getStorageProviderInfo } = await import('../src/services/storageProvider');
const info = getStorageProviderInfo();
return { info, warn };
}
it('配了前缀 ⇒ 诊断面能看到,且不告警', async () => {
const { info, warn } = await loadProviderInfo('supplier-system');
expect(info).toMatchObject({ provider: 's3', keyPrefix: 'supplier-system', keyPrefixConfigured: true });
expect(warn).not.toHaveBeenCalled();
});
it('前缀为空 ⇒ 告警「桶根」(不得静默写到主系统图片区)', async () => {
const { info, warn } = await loadProviderInfo('');
expect(info).toMatchObject({ keyPrefix: '', keyPrefixConfigured: false });
const messages = warn.mock.calls.map((call) => String(call[0])).join('\n');
expect(messages).toContain('桶根');
expect(messages).toContain('supplier-system');
});
it('本地驱动时报告**绝对**目录(便于运维核对不是主系统的 uploads)', async () => {
vi.resetModules();
vi.stubEnv('JWT_SECRET', 'test-secret');
vi.stubEnv('STORAGE_PROVIDER', 'local');
vi.stubEnv('STORAGE_DIR', './uploads-supplier');
const { getStorageProviderInfo } = await import('../src/services/storageProvider');
const info = getStorageProviderInfo();
expect(info.provider).toBe('local');
expect(String((info as { dir: string }).dir)).toMatch(/^\/.*uploads-supplier$/);
});
});
describe('存储隔离项:定时归档包的最终对象键在我们的前缀之下', () => {
it('照片与归档包都带 supplier-system/ 前缀(主系统侧则是桶根)', async () => {
const { buildStorageObjectKey, buildInspectionPhotoArchiveName } = await import(
'../src/services/storageBucketConfig'
);
const prefix = 'supplier-system';
expect(buildStorageObjectKey('inspection-photos', '1710000000000-a.jpg', prefix)).toBe(
'supplier-system/inspection-photos/1710000000000-a.jpg'
);
const archiveKey = buildStorageObjectKey(
'inspection-photos',
buildInspectionPhotoArchiveName('BR003', '2026-08'),
prefix
);
expect(archiveKey).toBe('supplier-system/inspection-photos/archive/BR003/2026-08.tar.gz');
// 前缀为空就是主系统的位置 —— 这正是必须告警的那种配置
expect(buildStorageObjectKey('inspection-photos', 'a.jpg', '')).toBe('inspection-photos/a.jpg');
});
});