mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-03 06:24:30 +00:00
Merge commit from fork
This commit is contained in:
+119
-139
@@ -1,168 +1,148 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
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'
|
||||
|
||||
const { mockServeStatic } = vi.hoisted(() => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockServeStatic: vi.fn<(args: any) => any>(() => (c: any) => c.text('static-file')),
|
||||
}))
|
||||
|
||||
vi.mock('hono/bun', () => ({
|
||||
serveStatic: mockServeStatic,
|
||||
}))
|
||||
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', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.resetModules()
|
||||
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)
|
||||
})
|
||||
|
||||
it('GET /files/* calls serveStatic with correct options when valid signature is provided', async () => {
|
||||
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
|
||||
const { signature, expires } = signLocalGetUrl('b1', 'test.webp')
|
||||
afterAll(async () => {
|
||||
process.chdir(originalDir)
|
||||
await rm(storageDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('STORAGE_BACKEND', 'local')
|
||||
})
|
||||
|
||||
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`)
|
||||
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(await res.text()).toBe('static-file')
|
||||
expect(mockServeStatic).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
root: './data',
|
||||
rewriteRequestPath: expect.any(Function),
|
||||
}),
|
||||
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}`,
|
||||
)
|
||||
|
||||
// Verify rewriteRequestPath logic
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const options = vi.mocked(mockServeStatic).mock.calls[0][0] as any
|
||||
if (options && options.rewriteRequestPath) {
|
||||
expect(options.rewriteRequestPath('/files/b1/test.webp')).toBe('b1/test.webp')
|
||||
}
|
||||
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('GET /files/* returns 403 Forbidden when signature is missing', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
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' }))
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
expect(res.status).toBe(403)
|
||||
const json = await res.json()
|
||||
expect(json.error).toContain('Forbidden')
|
||||
})
|
||||
|
||||
it('GET /files/* returns 403 Forbidden when signature is invalid', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp?Signature=invalidsig&Expires=9999999999')
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('GET /files/* returns 403 Forbidden when signature is expired', async () => {
|
||||
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
|
||||
// Signed with -10 seconds (expired)
|
||||
const { signature, expires } = signLocalGetUrl('b1', 'test.webp', -10)
|
||||
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('GET /files/* sets Content-Disposition with filename when download=1 & filename query params are present', async () => {
|
||||
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
|
||||
const { signature, expires } = signLocalGetUrl('b1', 'test.webp')
|
||||
|
||||
// We need to capture the onFound callback from serveStatic options
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let onFoundCallback: ((path: string, c: any) => void) | undefined
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockServeStatic.mockImplementationOnce((options: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
onFoundCallback = (options as any).onFound
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return (c: any) => c.text('static-file')
|
||||
})
|
||||
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
await app.request(
|
||||
`/files/b1/test.webp?Signature=${signature}&Expires=${expires}&download=1&filename=foo.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')
|
||||
})
|
||||
|
||||
expect(onFoundCallback).toBeDefined()
|
||||
it('honors explicit downloads of inline formats with and without a filename', async () => {
|
||||
const key = 'files/a/preview.webp'
|
||||
await writeStoredFile(key)
|
||||
|
||||
// Test with download=1 and filename
|
||||
const mockContextWithDownload = {
|
||||
req: {
|
||||
query: (key: string) =>
|
||||
key === 'download' ? '1' : key === 'filename' ? 'foo.png' : undefined,
|
||||
},
|
||||
header: vi.fn(),
|
||||
}
|
||||
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')
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContextWithDownload)
|
||||
expect(mockContextWithDownload.header).toHaveBeenCalledWith(
|
||||
'Content-Disposition',
|
||||
'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
|
||||
)
|
||||
}
|
||||
const withoutName = await app.request(signedPath(key, { download: '1' }))
|
||||
expect(withoutName.status).toBe(200)
|
||||
expect(withoutName.headers.get('Content-Disposition')).toBe('attachment')
|
||||
})
|
||||
|
||||
// Test with download=1 but no filename
|
||||
const mockContextDownloadNoFilename = {
|
||||
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
|
||||
header: vi.fn(),
|
||||
}
|
||||
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)),
|
||||
])
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContextDownloadNoFilename)
|
||||
expect(mockContextDownloadNoFilename.header).toHaveBeenCalledWith(
|
||||
'Content-Disposition',
|
||||
'attachment',
|
||||
)
|
||||
}
|
||||
|
||||
// Test without download param
|
||||
const mockContextWithout = {
|
||||
req: { query: () => undefined },
|
||||
header: vi.fn(),
|
||||
}
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContextWithout)
|
||||
expect(mockContextWithout.header).not.toHaveBeenCalled()
|
||||
for (const res of responses) {
|
||||
expect(res.status).toBe(403)
|
||||
expect(await res.json()).toMatchObject({ error: expect.stringContaining('Forbidden') })
|
||||
}
|
||||
})
|
||||
|
||||
it('PUT /files/:bucket/:key returns 404', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
const body = new TextEncoder().encode('test-data')
|
||||
|
||||
const res = await app.request('/files/b1/test.webp', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'content-length': body.byteLength.toString(),
|
||||
},
|
||||
body,
|
||||
})
|
||||
|
||||
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('GET /files/* returns 404 when STORAGE_BACKEND is not local', async () => {
|
||||
const s3Module = await import('@shumai/core/src/s3/s3')
|
||||
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('s3')
|
||||
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)
|
||||
})
|
||||
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
+39
-3
@@ -1,3 +1,4 @@
|
||||
import { basename, extname } from 'node:path'
|
||||
import { Hono } from 'hono'
|
||||
import {
|
||||
buildContentDisposition,
|
||||
@@ -6,6 +7,32 @@ import {
|
||||
} from '@shumai/core/src/s3/s3'
|
||||
import { serveStatic } from 'hono/bun'
|
||||
|
||||
// Only serve formats used by preview and media clients inline on the app origin.
|
||||
const inlineFileTypes = new Map([
|
||||
['.aac', 'audio/aac'],
|
||||
['.avif', 'image/avif'],
|
||||
['.bmp', 'image/bmp'],
|
||||
['.gif', 'image/gif'],
|
||||
['.glb', 'model/gltf-binary'],
|
||||
['.gltf', 'model/gltf+json'],
|
||||
['.ico', 'image/x-icon'],
|
||||
['.jpeg', 'image/jpeg'],
|
||||
['.jpg', 'image/jpeg'],
|
||||
['.m3u8', 'application/vnd.apple.mpegurl'],
|
||||
['.m4a', 'audio/mp4'],
|
||||
['.m4s', 'video/iso.segment'],
|
||||
['.mp3', 'audio/mpeg'],
|
||||
['.mp4', 'video/mp4'],
|
||||
['.ogg', 'audio/ogg'],
|
||||
['.opus', 'audio/opus'],
|
||||
['.pdf', 'application/pdf'],
|
||||
['.png', 'image/png'],
|
||||
['.ts', 'video/mp2t'],
|
||||
['.wav', 'audio/wav'],
|
||||
['.webm', 'video/webm'],
|
||||
['.webp', 'image/webp'],
|
||||
])
|
||||
|
||||
const route = new Hono()
|
||||
.use('*', async (c, next) => {
|
||||
if (getStorageBackend() !== 'local') {
|
||||
@@ -36,9 +63,18 @@ const route = new Hono()
|
||||
serveStatic({
|
||||
root: './data',
|
||||
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
||||
onFound: (_path, c) => {
|
||||
if (c.req.query('download') === '1') {
|
||||
c.header('Content-Disposition', buildContentDisposition(c.req.query('filename')))
|
||||
onFound: (path, c) => {
|
||||
const inlineType = inlineFileTypes.get(extname(path).toLowerCase())
|
||||
c.header('Content-Type', inlineType ?? 'application/octet-stream')
|
||||
c.header('X-Content-Type-Options', 'nosniff')
|
||||
|
||||
if (!inlineType) {
|
||||
c.header('Content-Security-Policy', 'sandbox')
|
||||
}
|
||||
|
||||
if (!inlineType || c.req.query('download') === '1') {
|
||||
const filename = c.req.query('filename') ?? (inlineType ? undefined : basename(path))
|
||||
c.header('Content-Disposition', buildContentDisposition(filename))
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user