gongxiangp2/lib/__tests__/performance-survey-attachments.test.ts

142 lines
7.0 KiB
TypeScript

/** @jest-environment node */
import { mkdtemp, writeFile, rm, symlink, readFile, realpath } from 'fs/promises'
import path from 'path'
import os from 'os'
import AdmZip from 'adm-zip'
import {
getPerformanceCaseFileType,
validatePerformanceCaseAttachments,
serializePerformanceCaseAttachments,
} from '@/lib/performance-survey-attachment-contract'
import {
assertPerformanceAttachmentFormat,
performanceAttachmentPath,
storePerformanceAttachment,
} from '@/lib/performance-survey-attachment-storage'
import {
parsePerformanceAttachmentRange,
performanceAttachmentFile,
} from '@/lib/performance-survey-attachment-response'
import { authorizePerformanceSurveyAttachment } from '@/lib/performance-survey-service'
jest.mock('@/lib/prisma', () => ({ prisma: {} }))
jest.mock('@/lib/performance-survey-service', () => ({
authorizePerformanceSurveyAttachment: jest.fn(),
PerformanceSurveyApiError: class extends Error {
constructor(message: string, public status = 400) { super(message) }
},
}))
const id = '00000000-0000-4000-8000-000000000001'
let root = ''
let previousUploadDir: string | undefined
beforeEach(async () => {
previousUploadDir = process.env.UPLOAD_DIR
root = await mkdtemp(path.join(await realpath(os.tmpdir()), 'survey-attachment-test-'))
process.env.UPLOAD_DIR = root
jest.clearAllMocks()
})
afterEach(async () => {
if (previousUploadDir === undefined) delete process.env.UPLOAD_DIR
else process.env.UPLOAD_DIR = previousUploadDir
await rm(root, { recursive: true, force: true })
})
test('supports all agreed formats and enforces per-file, count and total limits', () => {
for (const extension of ['mp4', 'mov', 'webm', 'ppt', 'pptx', 'doc', 'docx', 'pdf']) {
expect(getPerformanceCaseFileType('作品.' + extension.toUpperCase())?.extension).toBe(extension)
}
expect(getPerformanceCaseFileType('作品.exe')).toBeNull()
expect(validatePerformanceCaseAttachments([{ name: '影片.mp4', size: 200 * 1024 * 1024 }])).toBeNull()
expect(validatePerformanceCaseAttachments([{ name: '影片.mp4', size: 200 * 1024 * 1024 + 1 }])).toContain('200MB')
expect(validatePerformanceCaseAttachments([{ name: '作品.pdf', size: 50 * 1024 * 1024 + 1 }])).toContain('50MB')
expect(validatePerformanceCaseAttachments(Array.from({ length: 6 }, () => ({ name: '作品.pdf', size: 1 })))).toContain('5个')
expect(validatePerformanceCaseAttachments([{ name: '1.mp4', size: 140 * 1024 * 1024 }, { name: '2.mp4', size: 140 * 1024 * 1024 }])).toContain('256MB')
expect(validatePerformanceCaseAttachments([{ name: '作品.pdf', size: 0 }])).toContain('无效')
expect(validatePerformanceCaseAttachments([])).toBeNull()
})
test('validates format signatures and rejects missing Office parts and macros', async () => {
const file = path.join(root, 'input')
await writeFile(file, '%PDF-1.7\n')
await expect(assertPerformanceAttachmentFormat(file, '作品.pdf')).resolves.toMatchObject({ kind: 'document' })
await expect(assertPerformanceAttachmentFormat(file, '作品.mp4')).rejects.toThrow('内容与格式不符')
const office = new AdmZip()
office.addFile('[Content_Types].xml', Buffer.from('<Types/>'))
await writeFile(file, office.toBuffer())
await expect(assertPerformanceAttachmentFormat(file, '作品.pptx')).rejects.toThrow('内容与格式不符')
office.addFile('ppt/presentation.xml', Buffer.from('<p:presentation/>'))
await writeFile(file, office.toBuffer())
await expect(assertPerformanceAttachmentFormat(file, '作品.pptx')).resolves.toMatchObject({ extension: 'pptx' })
office.addFile('ppt/vbaProject.bin', Buffer.from('macro'))
await writeFile(file, office.toBuffer())
await expect(assertPerformanceAttachmentFormat(file, '作品.pptx')).rejects.toThrow('宏')
})
test('private storage rejects traversal and symlink paths and stores the original exactly', async () => {
const input = path.join(root, 'input.pdf')
await writeFile(input, '%PDF-1.7\n')
await expect(performanceAttachmentPath('../outside')).rejects.toThrow('路径无效')
await expect(performanceAttachmentPath(id, '../outside')).rejects.toThrow('路径无效')
const hash = await storePerformanceAttachment(id, input, 'pdf')
expect(hash).toMatch(/^[a-f0-9]{64}$/)
expect(await readFile(await performanceAttachmentPath(id, 'original.pdf'), 'utf8')).toBe('%PDF-1.7\n')
const linked = '00000000-0000-4000-8000-000000000002'
await symlink(root, path.join(root, '.performance-survey-private', linked))
await expect(performanceAttachmentPath(linked, 'input.pdf')).rejects.toThrow('不可用')
})
test.each([
['bytes=0-9', { start: 0, end: 9 }],
['bytes=8-', { start: 8, end: 9 }],
['bytes=-3', { start: 7, end: 9 }],
['bytes=-50', { start: 0, end: 9 }],
['bytes=9-100', { start: 9, end: 9 }],
['bytes=10-', null],
['bytes=-0', null],
['bytes=2-1', null],
['bytes=0-1,3-4', null],
['bytes=9007199254740993-', null],
])('parses a strict single Range %s', (input, expected) => {
expect(parsePerformanceAttachmentRange(input, 10)).toEqual(expected)
})
test('authenticated downloads preserve private caching, HEAD, Range and 416 semantics', async () => {
const file = path.join(root, 'input.mp4')
await writeFile(file, '0123456789')
await storePerformanceAttachment(id, file, 'mp4')
;(authorizePerformanceSurveyAttachment as jest.Mock).mockResolvedValue({
id, originalName: '作品.mp4', extension: 'mp4', mimeType: 'video/mp4', kind: 'video', status: 'queued',
})
const request = new Request('https://example.test/file', { headers: { range: 'bytes=2-5' } })
const result = await performanceAttachmentFile(null, id, request)
expect(result.status).toBe(206)
expect(result.headers.get('cache-control')).toBe('private, no-store')
expect(result.headers.get('content-range')).toBe('bytes 2-5/10')
expect(result.headers.get('content-disposition')).toContain('attachment;')
expect(await result.text()).toBe('2345')
const head = await performanceAttachmentFile(null, id, new Request(request.url, { method: 'HEAD' }))
expect(head.headers.get('content-length')).toBe('10')
expect(await head.text()).toBe('')
const invalid = await performanceAttachmentFile(null, id, new Request(request.url, { headers: { range: 'bytes=30-' } }))
expect(invalid.status).toBe(416)
expect(invalid.headers.get('content-range')).toBe('bytes */10')
})
test('authorization is required before reading a private file or preview', async () => {
;(authorizePerformanceSurveyAttachment as jest.Mock).mockRejectedValue(new Error('禁止访问'))
await expect(performanceAttachmentFile(null, id, new Request('https://example.test/file'))).rejects.toThrow('禁止访问')
})
test('serializes only public attachment fields', () => {
const attachment = {
id, originalName: '作品.pdf', kind: 'document', size: 100, status: 'ready',
pageCount: 101, previewPageCount: 100, error: null, previewKey: 'private-path', leaseToken: 'private-token',
}
expect(serializePerformanceCaseAttachments([attachment])[0]).not.toHaveProperty('previewKey')
expect(serializePerformanceCaseAttachments([attachment])[0]).not.toHaveProperty('leaseToken')
})