diff --git a/lib/__tests__/desktop-delivery-upload-auth.test.ts b/lib/__tests__/desktop-delivery-upload-auth.test.ts new file mode 100644 index 00000000..46a5ee09 --- /dev/null +++ b/lib/__tests__/desktop-delivery-upload-auth.test.ts @@ -0,0 +1,36 @@ +/** @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' + +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() + }) +}) diff --git a/lib/upload-auth.ts b/lib/upload-auth.ts index 9bd20724..804891d7 100644 --- a/lib/upload-auth.ts +++ b/lib/upload-auth.ts @@ -3,6 +3,7 @@ import type { NextRequest } from 'next/server' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' import { requireDesktop } from '@/lib/desktop-client/service' +import { DesktopClientError } from '@/lib/desktop-client/contract.mjs' import { getOwnedUploadSession } from '@/lib/upload-sessions' import { DINGTALK_PERFORMANCE_SESSION_HEADER, @@ -48,27 +49,31 @@ const DELIVERY_PURPOSE = /^xiaoyi:([a-zA-Z0-9_-]{1,80}):([a-zA-Z0-9_-]{1,80})$/ export async function getDesktopDeliveryUploadUserId(request: NextRequest, mode: 'init' | 'chunk' | 'complete'): Promise { if (!/^Bearer dcs_[\w-]{64}$/.test(request.headers.get('authorization') || '')) return null + let account: Awaited>['account'] try { - const { account } = await requireDesktop(request) - let purpose = '' - if (mode === 'init') { - purpose = String((await request.clone().json()).uploadPurpose || '') - } else { - const uploadId = mode === 'chunk' - ? request.headers.get('x-upload-id') || request.nextUrl.searchParams.get('uploadId') || '' - : String((await request.clone().json()).uploadId || '') - purpose = (await getOwnedUploadSession(uploadId, account.id))?.uploadPurpose || '' - } - const match = DELIVERY_PURPOSE.exec(purpose) - if (!match) return null - const project = await prisma.$queryRawUnsafe<{ id: string }[]>( - 'SELECT id FROM desktop_workspace_projects WHERE id=$1 AND owner_id=$2 AND deleted_at IS NULL', - match[1], account.id, - ) - return project.length ? account.id : null - } catch { - return null + ;({ account } = await requireDesktop(request)) + } catch (error) { + if (error instanceof DesktopClientError && ['unauthenticated', 'session_expired', 'feature_disabled', 'account_inactive'].includes(error.code)) return null + throw error } + let purpose = '' + if (mode === 'init') { + const body = await request.clone().json().catch(() => null) + purpose = String(body?.uploadPurpose || '') + } else { + const body = mode === 'complete' ? await request.clone().json().catch(() => null) : null + const uploadId = mode === 'chunk' + ? request.headers.get('x-upload-id') || request.nextUrl.searchParams.get('uploadId') || '' + : String(body?.uploadId || '') + purpose = (await getOwnedUploadSession(uploadId, account.id))?.uploadPurpose || '' + } + const match = DELIVERY_PURPOSE.exec(purpose) + if (!match) return null + const project = await prisma.$queryRawUnsafe<{ id: string }[]>( + 'SELECT id FROM desktop_workspace_projects WHERE id=$1 AND owner_id=$2 AND deleted_at IS NULL', + match[1], account.id, + ) + return project.length ? account.id : null } export function isDesktopDeliveryPurpose(purpose: string): boolean {