/** @jest-environment node */ import { EventEmitter } from 'node:events' import { lookup } from 'node:dns/promises' import { request } from 'node:https' import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import { PassThrough } from 'node:stream' import { downloadProductPackageRemoteFile, parseProductPackageRemoteUrl } from '@/lib/product-package-remote-file' jest.mock('node:dns/promises', () => ({ lookup: jest.fn() })) jest.mock('node:https', () => ({ request: jest.fn() })) const url = 'https://images.example/first.jpg?signature=fixture' const publicAddress = { address: '1.1.1.1', family: 4 } let root: string let destination: string beforeEach(async () => { jest.resetAllMocks() ;(lookup as jest.Mock).mockResolvedValue([publicAddress]) root = await mkdtemp(path.join(tmpdir(), 'package-remote-file-')) destination = path.join(root, 'asset') }) afterEach(async () => { await rm(root, { recursive: true, force: true }) }) function mockResponse(statusCode: number, headers: Record = {}, chunks?: string[]) { const body = Object.assign(new PassThrough(), { statusCode, headers }) let notifyRequested!: () => void const requested = new Promise((resolve) => { notifyRequested = resolve }) const idle = jest.fn() jest.mocked(request).mockImplementationOnce((_url: any, _options: any, callback: any) => { const req = Object.assign(new EventEmitter(), { setTimeout: idle, end() { callback(body) notifyRequested() if (chunks) { for (const chunk of chunks) body.write(chunk) body.end() } }, destroy(error: Error) { body.destroy(error) }, }) return req as any }) return { body, requested, idle } } test('DNS 结果固定到连接,重定向重新解析,响应流分块写入', async () => { const first = mockResponse(302, { location: '/final.jpg?signature=fixture' }) mockResponse(200, {}, ['im', 'age']) await expect(downloadProductPackageRemoteFile(url, destination, 5)).resolves.toBe(5) expect(await readFile(destination, 'utf-8')).toBe('image') expect(lookup).toHaveBeenCalledTimes(2) const calls = (request as jest.Mock).mock.calls expect(calls.map(([target]) => target.pathname)).toEqual(['/first.jpg', '/final.jpg']) for (const [, options] of calls) { const connected = jest.fn() options.lookup('images.example', {}, connected) expect(connected).toHaveBeenCalledWith(null, publicAddress.address, 4) } expect(first.body.destroyed).toBe(true) }) test('同源跳转每跳 DNS 重新判定,非公网解析结果不能建立连接', async () => { ;(lookup as jest.Mock).mockResolvedValueOnce([publicAddress]).mockResolvedValueOnce([ publicAddress, { address: '192.0.2.1', family: 4 }, ]) mockResponse(302, { location: '/final.jpg' }) await expect(downloadProductPackageRemoteFile(url, destination, 10)).rejects.toThrow('受保护的网络') expect(request).toHaveBeenCalledTimes(1) }) test('禁止跨站跳转,并且只允许三次同源跳转', async () => { const foreign = mockResponse(302, { location: 'https://other.example/final.jpg' }) await expect(downloadProductPackageRemoteFile(url, destination, 10)).rejects.toThrow('不允许跨站重定向') expect(foreign.body.destroyed).toBe(true) expect(request).toHaveBeenCalledTimes(1) for (let index = 0; index < 4; index += 1) mockResponse(302, { location: '/final.jpg' }) await expect(downloadProductPackageRemoteFile(url, destination, 10)).rejects.toThrow('次数过多') expect(request).toHaveBeenCalledTimes(5) }) test.each([{}, { 'content-length': '50' }])('响应超出限额会销毁流 (%j)', async (headers) => { const { body } = mockResponse(200, headers as Record, headers['content-length'] ? undefined : ['123', '456']) await expect(downloadProductPackageRemoteFile(url, destination, 5)).rejects.toThrow('超过声明大小或单文件上限') expect(body.destroyed).toBe(true) }) test('响应体停滞时超时释放连接', async () => { const { requested, idle, body } = mockResponse(200) const result = downloadProductPackageRemoteFile(url, destination, 10) const rejected = expect(result).rejects.toThrow('超时') await requested idle.mock.calls[0][1]() await rejected expect(body.destroyed).toBe(true) }) test('合并调用方取消和整个传输的硬超时', async () => { const timeout = new AbortController() const clock = jest.spyOn(AbortSignal, 'timeout').mockReturnValue(timeout.signal) try { const { requested, body } = mockResponse(200) const caller = new AbortController() const result = downloadProductPackageRemoteFile(url, destination, 10, caller.signal) const rejected = expect(result).rejects.toThrow() await requested timeout.abort() await rejected expect(clock).toHaveBeenCalledWith(60_000) expect(body.destroyed).toBe(true) } finally { clock.mockRestore() } }) test('有账号密码的 URL 与默认内网来源会在发起请求前拒绝,显式内网授权按 origin', () => { const saved = process.env.PRODUCT_PACKAGE_INTERNAL_DOWNLOAD_ORIGINS delete process.env.PRODUCT_PACKAGE_INTERNAL_DOWNLOAD_ORIGINS try { expect(() => parseProductPackageRemoteUrl('https://account:pass@images.example/fixture.jpg')).toThrow() expect(() => parseProductPackageRemoteUrl('http://asset-store.internal/file.jpg')).toThrow() process.env.PRODUCT_PACKAGE_INTERNAL_DOWNLOAD_ORIGINS = 'http://asset-store.internal:8080' expect(parseProductPackageRemoteUrl('http://asset-store.internal:8080/file.jpg').port).toBe('8080') expect(() => parseProductPackageRemoteUrl('http://asset-store.internal/file.jpg')).toThrow() expect(request).not.toHaveBeenCalled() } finally { if (saved === undefined) delete process.env.PRODUCT_PACKAGE_INTERNAL_DOWNLOAD_ORIGINS else process.env.PRODUCT_PACKAGE_INTERNAL_DOWNLOAD_ORIGINS = saved } })