import express from 'express'; import request from 'supertest'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * T9 SEC-5/SEC-7(2026-10-19): * · 私有桶(invoices/quality-reports/…)签名 URL 铸造与上传必须按桶权限 + 租户上下文,越权 403; * · weigh-apk 仅管理员,且 APK 必须 ZIP 魔数 / JSON 必须可解析(可选 x-content-sha256 校验); * · weigh-apk 匿名公开读只允许 manifest.json 与 releases/*.apk,其它路径 403(80MB 文件不再裸公开)。 */ const H = vi.hoisted(() => ({ ctx: null as Record | null, put: vi.fn(async () => undefined), getObject: vi.fn(async () => ({ buffer: Buffer.from('ok'), contentType: 'text/plain' })), getRedirect: vi.fn(async () => null), errors: 0, })); vi.mock('../src/middleware/auth', () => ({ authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => { req.userId = 'u1'; next(); }, })); vi.mock('../src/services/tenantScope', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, loadTenantContext: async () => H.ctx }; }); vi.mock('../src/services/storageProvider', () => ({ getStorageProvider: () => ({ putObject: (...args: unknown[]) => H.put(...args), getObject: (...args: unknown[]) => H.getObject(...args), getReadRedirectUrl: (...args: unknown[]) => H.getRedirect(...args), }), })); const { default: storageRoutes } = await import('../src/routes/storage'); const app = express(); app.use(express.json({ limit: '5mb' })); app.use('/api/storage', storageRoutes); const admin = { userId: 'u1', isSuperAdmin: false, roles: ['admin'], permissions: [], branchCode: 'BR002' }; const superAdmin = { userId: 'u1', isSuperAdmin: true, roles: ['super_admin'], permissions: [], branchCode: 'BR002' }; const operator = { userId: 'u1', isSuperAdmin: false, roles: ['operator'], permissions: [], branchCode: 'BR002' }; const finance = { userId: 'u1', isSuperAdmin: false, roles: ['finance'], permissions: ['invoice_manage', 'finance_manage'], branchCode: 'BR002', }; beforeEach(() => { H.put.mockClear(); H.getObject.mockClear(); H.getRedirect.mockClear(); H.ctx = operator; }); describe('SEC-7:上传按桶授权', () => { it('weigh-apk 非管理员 ⇒ 403 且不写对象', async () => { H.ctx = operator; const res = await request(app) .post('/api/storage/weigh-apk/upload?path=releases/2/app.apk') .send({ content: Buffer.from('PK\u0003\u0004xxxx').toString('base64') }); expect(res.status).toBe(403); expect(H.put).not.toHaveBeenCalled(); }); it('weigh-apk 管理员但内容不是 ZIP ⇒ 400 invalid_apk', async () => { H.ctx = admin; const res = await request(app) .post('/api/storage/weigh-apk/upload?path=releases/2/app.apk') .send({ content: Buffer.from('not-a-zip').toString('base64') }); expect(res.status).toBe(400); expect(res.body.error).toBe('invalid_apk'); expect(H.put).not.toHaveBeenCalled(); }); it('weigh-apk 管理员 + 合法 ZIP ⇒ 200,返回 sha256 且写对象', async () => { H.ctx = admin; const buf = Buffer.from('PK\u0003\u0004apk-content'); const res = await request(app) .post('/api/storage/weigh-apk/upload?path=releases/2/app.apk') .send({ content: buf.toString('base64') }); expect(res.status).toBe(200); expect(res.body.sha256).toMatch(/^[a-f0-9]{64}$/); expect(H.put).toHaveBeenCalledTimes(1); }); it('invoices 无财务权限 ⇒ 403;有 invoice_manage ⇒ 200 且 key 带 branch 前缀', async () => { H.ctx = operator; let res = await request(app) .post('/api/storage/invoices/upload?path=invoice.pdf') .send({ content: Buffer.from('%PDF-1.4 x').toString('base64') }); expect(res.status).toBe(403); H.ctx = finance; res = await request(app) .post('/api/storage/invoices/upload?path=invoice.pdf') .send({ content: Buffer.from('%PDF-1.4 x').toString('base64') }); expect(res.status).toBe(200); expect(String(res.body.path).startsWith('BR002/')).toBe(true); }); it('小程序成本录入:mp_purchaser_free_cost 可传 free-cost/* 到 invoices', async () => { H.ctx = { ...operator, roles: ['purchaser'], permissions: ['mp_purchaser_free_cost'] }; let res = await request(app) .post('/api/storage/invoices/upload?path=free-cost/v.pdf') .send({ content: Buffer.from('%PDF-1.4 x').toString('base64') }); expect(res.status).toBe(200); H.ctx = operator; res = await request(app) .post('/api/storage/invoices/upload?path=free-cost/v.pdf') .send({ content: Buffer.from('%PDF-1.4 x').toString('base64') }); expect(res.status).toBe(403); }); }); describe('SEC-5:私有桶签名 URL 铸造授权', () => { it('invoices 无财务权限 ⇒ 403,不返回签名路径', async () => { H.ctx = operator; const res = await request(app).get('/api/storage/invoices/public-url/a.pdf'); expect(res.status).toBe(403); }); it('invoices 有 invoice_manage + 同分支 key ⇒ 200 且返回签名路径', async () => { H.ctx = finance; const res = await request(app).get('/api/storage/invoices/public-url/BR002/a.pdf'); expect(res.status).toBe(200); expect(String(res.body.publicUrl)).toContain('/api/storage/invoices/'); }); it('BR001 token 请求 BR002 的 key ⇒ 403(跨租户归属校验)', async () => { H.ctx = { ...finance, branchCode: 'BR001' }; const res = await request(app).get('/api/storage/invoices/public-url/BR002/a.pdf'); expect(res.status).toBe(403); expect(String(res.body.error_description)).toContain('不属于当前租户'); }); it('无 branchCode ⇒ 403(私有桶不能脱离租户签发)', async () => { H.ctx = { ...finance, branchCode: null }; const res = await request(app).get('/api/storage/invoices/public-url/BR002/a.pdf'); expect(res.status).toBe(403); }); it('旧 key(无 branch 前缀、业务表反查不到)⇒ 403 fail-closed', async () => { H.ctx = finance; const res = await request(app).get('/api/storage/invoices/public-url/legacy-key.pdf'); expect(res.status).toBe(403); }); it('avatars 公开桶流程不回归(任意登录、无需租户归属)', async () => { H.ctx = operator; const res = await request(app).get('/api/storage/avatars/public-url/u.png'); expect(res.status).toBe(200); }); it('super_admin ⇒ 200(全桶)', async () => { H.ctx = superAdmin; const res = await request(app).get('/api/storage/quality-reports/public-url/r.pdf'); expect(res.status).toBe(200); }); }); describe('SEC-7:weigh-apk 公开读范围', () => { it('匿名读 manifest.json ⇒ 200(保留 OTA)', async () => { const res = await request(app).get('/api/storage/weigh-apk/public/manifest.json'); expect(res.status).toBe(200); }); it('匿名读 releases/2/app.apk ⇒ 200(保留 OTA 下载)', async () => { const res = await request(app).get('/api/storage/weigh-apk/public/releases/2/app.apk'); expect(res.status).toBe(200); }); it('匿名读 buckt 内其它文件 ⇒ 403(80MB 不再裸公开)', async () => { const res = await request(app).get('/api/storage/weigh-apk/public/other.json'); expect(res.status).toBe(403); }); }); describe('SEC-7:multer 上限与错误映射(源码契约)', () => { it('multer limit 与 weigh-apk 规则对齐 80MB;LIMIT_FILE_SIZE ⇒ 413', () => { const { readFileSync } = require('node:fs'); const { join } = require('node:path'); const src = readFileSync(join(__dirname, '../src/routes/storage.ts'), 'utf8'); expect(src).toContain('fileSize: 80 * 1024 * 1024'); expect(src).toContain("err?.code === 'LIMIT_FILE_SIZE'"); expect(src).toContain('res.status(413)'); }); });