gongxiangp2/lib/__tests__/desktop-delivery-upload-auth.test.ts

43 lines
2.3 KiB
TypeScript

/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getDesktopDeliveryUploadUserId } from '@/lib/upload-auth'
import { requireDesktop } from '@/lib/desktop-client/service'
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
import { prisma } from '@/lib/prisma'
import { getOwnedUploadSession } from '@/lib/upload-sessions'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn() } }))
jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() }))
jest.mock('@/lib/upload-sessions', () => ({ getOwnedUploadSession: jest.fn() }))
function request(body: string) {
return new NextRequest('http://localhost/api/materials/upload/init', {
method: 'POST', headers: { authorization: `Bearer dcs_${'a'.repeat(64)}`, 'content-type': 'application/json' }, body,
})
}
describe('小壹交付上传认证', () => {
beforeEach(() => jest.resetAllMocks())
it('过期凭据不授权', async () => {
jest.mocked(requireDesktop).mockRejectedValue(new DesktopClientError('expired', 401, 'session_expired'))
await expect(getDesktopDeliveryUploadUserId(request('{}'), 'init')).resolves.toBeNull()
})
it('数据库错误不会伪装成授权失效', async () => {
jest.mocked(requireDesktop).mockResolvedValue({ account: { id: 'user', name: 'User' } } as any)
const failure = new Error('database unavailable')
jest.mocked(prisma.$queryRawUnsafe).mockRejectedValue(failure)
await expect(getDesktopDeliveryUploadUserId(request('{"uploadPurpose":"xiaoyi:project:request"}'), 'init')).rejects.toBe(failure)
})
it('非法 JSON 不授权', async () => {
jest.mocked(requireDesktop).mockResolvedValue({ account: { id: 'user', name: 'User' } } as any)
await expect(getDesktopDeliveryUploadUserId(request('{'), 'init')).resolves.toBeNull()
})
it('过期的上传会话交给上传接口返回 404', async () => {
jest.mocked(requireDesktop).mockResolvedValue({ account: { id: 'user', name: 'User' } } as any)
jest.mocked(getOwnedUploadSession).mockResolvedValue(null)
await expect(getDesktopDeliveryUploadUserId(request('{"uploadId":"gone"}'), 'complete')).resolves.toBe('user')
})
})