Files
shumai/packages/api/src/s3.test.ts
T
2026-12-03 10:44:12 +08:00

149 lines
5.4 KiB
TypeScript

import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { Hono } from 'hono'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { signLocalGetUrl } from '@shumai/core/src/s3/s3'
import route from './s3'
describe('S3 API', () => {
const app = new Hono().route('/files', route)
const bucket = 'test-bucket'
const body = 'inert file contents'
let originalDir: string
let storageDir: string
beforeAll(async () => {
originalDir = process.cwd()
storageDir = await mkdtemp(join(tmpdir(), 'shumai-local-file-test-'))
process.chdir(storageDir)
})
afterAll(async () => {
process.chdir(originalDir)
await rm(storageDir, { recursive: true, force: true })
})
beforeEach(() => {
vi.stubEnv('STORAGE_BACKEND', 'local')
})
afterEach(() => {
vi.unstubAllEnvs()
})
function signedPath(key: string, query: Record<string, string> = {}, lifetime?: number) {
const { signature, expires } = signLocalGetUrl(bucket, key, lifetime)
const params = new URLSearchParams({ Signature: signature, Expires: String(expires), ...query })
return `/files/${bucket}/${key}?${params}`
}
async function writeStoredFile(key: string) {
const path = join(storageDir, 'data', bucket, key)
await mkdir(dirname(path), { recursive: true })
await writeFile(path, body)
}
it.each([
['files/a/poster.WEBP', 'image/webp'],
['files/a/proxy.pdf', 'application/pdf'],
['files/a/video.mp4', 'video/mp4'],
['files/a/stream.m3u8', 'application/vnd.apple.mpegurl'],
['files/a/segment.m4s', 'video/iso.segment'],
['files/a/model.glb', 'model/gltf-binary'],
])('serves %s inline with its media type', async (key, mimeType) => {
await writeStoredFile(key)
const res = await app.request(signedPath(key))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe(mimeType)
expect(res.headers.get('Content-Disposition')).toBeNull()
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
expect(await res.text()).toBe(body)
})
it.each([
'files/a/original.html',
'attachments/a/notes.HTML',
'attachments/a/diagram.svg',
'kanban/attachments/team/user/a/notes.html',
'kanban/attachments/team/user/a/diagram.svg',
'files/a/document.xhtml',
'files/a/source.js',
'files/a/unknown.ext',
'files/a/extensionless',
])('serves %s as a download even without a download request', async (key) => {
await writeStoredFile(key)
const res = await app.request(signedPath(key))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
const filename = basename(key)
expect(res.headers.get('Content-Disposition')).toBe(
`attachment; filename="${filename}"; filename*=UTF-8''${filename}`,
)
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
expect(res.headers.get('Content-Security-Policy')).toBe('sandbox')
expect(await res.text()).toBe(body)
})
it('uses the stored file type when an explicit download has a different filename', async () => {
const key = 'attachments/a/diagram.svg'
await writeStoredFile(key)
const res = await app.request(signedPath(key, { download: '1', filename: '図.png' }))
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
expect(res.headers.get('Content-Disposition')).toBe(
"attachment; filename*=UTF-8''%E5%9B%B3.png",
)
expect(res.headers.get('Content-Security-Policy')).toBe('sandbox')
})
it('honors explicit downloads of inline formats with and without a filename', async () => {
const key = 'files/a/preview.webp'
await writeStoredFile(key)
const withName = await app.request(signedPath(key, { download: '1', filename: 'image.webp' }))
expect(withName.status).toBe(200)
expect(withName.headers.get('Content-Disposition')).toBe(
'attachment; filename="image.webp"; filename*=UTF-8\'\'image.webp',
)
expect(withName.headers.get('Content-Type')).toBe('image/webp')
const withoutName = await app.request(signedPath(key, { download: '1' }))
expect(withoutName.status).toBe(200)
expect(withoutName.headers.get('Content-Disposition')).toBe('attachment')
})
it('returns 403 when a signature is missing, invalid, or expired', async () => {
const key = 'files/a/preview.webp'
const responses = await Promise.all([
app.request(`/files/${bucket}/${key}`),
app.request(signedPath(key, { Signature: 'invalid' })),
app.request(signedPath(key, {}, -10)),
])
for (const res of responses) {
expect(res.status).toBe(403)
expect(await res.json()).toMatchObject({ error: expect.stringContaining('Forbidden') })
}
})
it('returns 404 for a validly signed missing file', async () => {
const res = await app.request(signedPath('files/a/missing.webp'))
expect(res.status).toBe(404)
})
it('returns 404 for PUT /files/:bucket/:key', async () => {
const res = await app.request(signedPath('files/a/preview.webp'), { method: 'PUT', body })
expect(res.status).toBe(404)
})
it('returns 404 for local URLs when the storage backend is S3', async () => {
vi.stubEnv('STORAGE_BACKEND', 's3')
const res = await app.request(signedPath('files/a/preview.webp'))
expect(res.status).toBe(404)
})
})