Files
shumai/packages/api/src/upload.test.ts
T
Yiling-J 67b767f1e8 feat(upload): S3 multipart upload with offline resume and wake lock (#391)
* feat(upload): implement S3 multipart upload with offline resume and wake lock

* fix(upload): harden S3 sign and abort authorization, await confirmation, and clean up failed multipart uploads

* fix(webui): resume multipart upload on network recovery and log online event

* fix(webui): remove offline and online toast notifications
2026-09-07 16:49:00 +08:00

224 lines
6.7 KiB
TypeScript

import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import uploadRoute from './upload'
import { authMiddleware } from './middleware/auth'
import { uploadService } from '@shumai/core/src/upload/upload'
import type { CreateUploadTaskResponse, TaskInfo } from '@shumai/dtos'
import type { PaginatedData } from '@shumai/core/src/pagination'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { assetService } from '@shumai/core/src/asset/asset'
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('./middleware/auth', () => ({
// We use any here because mocking Hono context and middleware
// with full type safety is overly complex for these unit tests.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.set('user', { id: 'user1', name: 'Test User' } as any)
await next()
},
}))
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
ResourceType: {
Team: 'team',
Asset: 'asset',
},
}))
vi.mock('@shumai/core/src/notification/notification', () => ({
notificationService: {
create: vi.fn().mockResolvedValue(undefined),
},
}))
describe('Upload API', () => {
const app = new Hono().use('*', authMiddleware).route('/', uploadRoute)
beforeEach(() => {
vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
it('GET /teams/:teamId/upload/tasks', async () => {
// We mock the return value as it is only used for checking the call
vi.spyOn(uploadService, 'listUploadTasks').mockResolvedValue({
data: [],
pageInfo: {},
} as unknown as PaginatedData<TaskInfo[]>)
const res = await app.request('/teams/team1/upload/tasks', {
headers: { Authorization: 'Bearer test' },
})
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 'team1',
permission: Permission.Read,
}),
)
expect(uploadService.listUploadTasks).toHaveBeenCalled()
})
it('POST /teams/:teamId/upload/tasks', async () => {
// We mock the return value as it is only used for checking the call
vi.spyOn(uploadService, 'createUploadTask').mockResolvedValue({
taskId: 'task1',
presignedUrls: [],
} as unknown as CreateUploadTaskResponse)
const res = await app.request('/teams/team1/upload/tasks', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
parentId: 'parent1',
files: [],
}),
})
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'parent1',
permission: Permission.Edit,
}),
)
expect(uploadService.createUploadTask).toHaveBeenCalled()
})
it('PATCH /teams/:teamId/upload/tasks/:taskId', async () => {
vi.spyOn(uploadService, 'confirmFileUpload').mockResolvedValue(undefined)
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({
teamId: 'team1',
projectId: 'p1',
})
const res = await app.request('/teams/team1/upload/tasks/task1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
fileId: 'file1',
}),
})
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'file1',
permission: Permission.Edit,
}),
)
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
fileId: 'file1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'file_create',
teamId: 'team1',
userId: 'user1',
projectId: 'p1',
itemId: 'file1',
})
})
it('POST /teams/:teamId/upload/sign', async () => {
vi.spyOn(uploadService, 'signS3Upload').mockResolvedValue({
url: 'http://signed-url.com',
})
const res = await app.request('/teams/team1/upload/sign', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
key: 'files/test.mp4',
method: 'PUT',
fileId: 'file1',
uploadId: 'up1',
partNumber: 1,
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ url: 'http://signed-url.com' })
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'file1',
permission: Permission.Edit,
}),
)
expect(uploadService.signS3Upload).toHaveBeenCalledWith('team1', 'user1', {
key: 'files/test.mp4',
method: 'PUT',
fileId: 'file1',
uploadId: 'up1',
partNumber: 1,
})
})
it('POST /teams/:teamId/upload/sign fails validation when fileId is missing', async () => {
const res = await app.request('/teams/team1/upload/sign', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
key: 'files/test.mp4',
method: 'PUT',
}),
})
expect(res.status).toBe(400)
})
it('POST /teams/:teamId/upload/tasks/:taskId/abort', async () => {
vi.spyOn(uploadService, 'abortUpload').mockResolvedValue({
success: true,
})
const res = await app.request('/teams/team1/upload/tasks/task1/abort', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
fileId: 'file1',
uploadId: 'up1',
key: 'files/test.mp4',
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ success: true })
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'file1',
permission: Permission.Edit,
}),
)
expect(uploadService.abortUpload).toHaveBeenCalledWith('team1', 'user1', 'task1', {
fileId: 'file1',
uploadId: 'up1',
key: 'files/test.mp4',
})
})
})