import { describe, expect, it, vi, beforeEach } from 'vitest' import { Hono } from 'hono' import uploadRoute, { localUploadRoute } from './upload' import { authMiddleware } from './middleware/auth' import { uploadService } from '@shumai/core/src/upload/upload' import * as s3Module from '@shumai/core/src/s3/s3' 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) 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', }) }) it('POST /teams/:teamId/upload/tasks/:taskId/cancel', async () => { vi.spyOn(uploadService, 'cancelUploadTask').mockResolvedValue({ success: true, }) const res = await app.request('/teams/team1/upload/tasks/task1/cancel', { method: 'POST', headers: { Authorization: 'Bearer test' }, }) expect(res.status).toBe(200) const json = await res.json() expect(json).toEqual({ success: true }) expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ type: ResourceType.Team, id: 'team1', permission: Permission.Edit, }), ) expect(uploadService.cancelUploadTask).toHaveBeenCalledWith('team1', 'user1', 'task1') }) describe('PUT /upload/local', () => { it('returns 404 when STORAGE_BACKEND is s3', async () => { vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('s3') const localApp = new Hono().route('/', localUploadRoute) const res = await localApp.request('/upload/local?bucket=b&key=k&Signature=sig', { method: 'PUT', }) expect(res.status).toBe(404) }) it('accepts a valid signed local upload URL', async () => { vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local') const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined) const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt') const localPath = signedPath.replace(/^\/api/, '') const localApp = new Hono().route('/', localUploadRoute) const res = await localApp.request(localPath, { method: 'PUT', headers: { 'Content-Type': 'text/plain', 'Content-Length': '5' }, body: 'hello', }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ success: true }) expect(putObjectSpy).toHaveBeenCalledWith( 'test-bucket', 'files/test.txt', expect.anything(), 5, 'text/plain', ) }) it('returns 403 when local upload URL signature is expired', async () => { vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local') const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined) const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt', -10) const localPath = signedPath.replace(/^\/api/, '') const localApp = new Hono().route('/', localUploadRoute) const res = await localApp.request(localPath, { method: 'PUT', body: 'hello', }) expect(res.status).toBe(403) expect(putObjectSpy).not.toHaveBeenCalled() }) it('returns 403 when Expires query param is missing or invalid', async () => { vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local') const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined) const localApp = new Hono().route('/', localUploadRoute) const missingRes = await localApp.request('/upload/local?bucket=b&key=k&Signature=sig', { method: 'PUT', body: 'hello', }) expect(missingRes.status).toBe(403) const invalidRes = await localApp.request( '/upload/local?bucket=b&key=k&Signature=sig&Expires=not-a-number', { method: 'PUT', body: 'hello', }, ) expect(invalidRes.status).toBe(403) expect(putObjectSpy).not.toHaveBeenCalled() }) }) })