gongxiangp2/lib/__tests__/external-auto-listing-callback.test.ts

107 lines
5.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** @jest-environment node */
import { lookup } from 'node:dns/promises'
import type { LookupAddress, LookupAllOptions } from 'node:dns'
import { request as httpRequest } from 'node:http'
import { request as httpsRequest } from 'node:https'
import { EventEmitter } from 'node:events'
import type { IncomingMessage, RequestOptions } from 'node:http'
import {
normalizeAutoListingCallbackUrl,
postAutoListingCallback,
validateAutoListingCallbackUrl,
validateCallbackAuth,
} from '@/lib/external-auto-listing-callback'
jest.mock('node:dns/promises', () => ({ lookup: jest.fn() }))
jest.mock('node:http', () => ({ ...jest.requireActual('node:http'), request: jest.fn() }))
jest.mock('node:https', () => ({ request: jest.fn() }))
const env = process.env.AUTO_LISTING_INTERNAL_CALLBACK_ORIGINS
const resolveAll: (hostname: string, options: LookupAllOptions) => Promise<LookupAddress[]> = lookup
const resolve = jest.mocked(resolveAll)
const https = jest.mocked(httpsRequest)
const http = jest.mocked(httpRequest)
beforeEach(() => {
jest.resetAllMocks()
delete process.env.AUTO_LISTING_INTERNAL_CALLBACK_ORIGINS
})
afterAll(() => {
if (env === undefined) delete process.env.AUTO_LISTING_INTERNAL_CALLBACK_ORIGINS
else process.env.AUTO_LISTING_INTERNAL_CALLBACK_ORIGINS = env
})
test.each([
'file:///tmp/secret',
'ftp://receiver.example.com/callback',
'http://receiver.example.com/callback',
'https://user:pass@receiver.example.com/callback',
'https://receiver.example.com/callback?token=secret',
'https://receiver.example.com/callback#fragment',
'https://127.1/callback',
'https://0x7f000001/callback',
'https://169.254.169.254/latest',
'https://168.63.129.16/callback',
'https://[::1]/callback',
'https://[::ffff:127.0.0.1]/callback',
'https://[2002:7f00:1::]/callback',
'https://192.168.10.20/callback',
])('拒绝不安全回调地址 %s', (url) => {
expect(() => normalizeAutoListingCallbackUrl(url)).toThrow()
expect(resolve).not.toHaveBeenCalled()
})
test('公网 HTTPS 拒绝混合私网解析和重绑定后的私网地址', async () => {
const callbackUrl = 'https://receiver.example.com:8443/callback'
resolve.mockResolvedValueOnce([{ address: '1.1.1.1', family: 4 }])
.mockResolvedValueOnce([{ address: '1.1.1.1', family: 4 }, { address: '10.0.0.2', family: 4 }])
await expect(validateAutoListingCallbackUrl(callbackUrl)).resolves.toBe(callbackUrl)
await expect(postAutoListingCallback(callbackUrl, {}, {})).rejects.toThrow('受保护的网络')
expect(https).not.toHaveBeenCalled()
})
test('只允许服务端明确授权的内网来源,并始终拒绝元数据和回环地址', async () => {
process.env.AUTO_LISTING_INTERNAL_CALLBACK_ORIGINS = 'http://listing.company.local:8000,http://169.254.169.254,https://127.0.0.1'
const callbackUrl = 'http://listing.company.local:8000/webhooks/material'
resolve.mockResolvedValueOnce([{ address: '192.168.10.20', family: 4 }])
await expect(validateAutoListingCallbackUrl(callbackUrl)).resolves.toBe(callbackUrl)
expect(() => normalizeAutoListingCallbackUrl('http://listing.company.local:8001/webhooks/material')).toThrow()
expect(() => normalizeAutoListingCallbackUrl('http://169.254.169.254/latest')).toThrow()
expect(() => normalizeAutoListingCallbackUrl('https://127.0.0.1/callback')).toThrow()
resolve.mockResolvedValueOnce([{ address: '::1', family: 6 }])
await expect(validateAutoListingCallbackUrl(callbackUrl)).rejects.toThrow('受保护的网络')
expect(http).not.toHaveBeenCalled()
})
test('发一次 POST,固定已验证 IP 并保留 HTTPS 主机,不跟随重定向或读取响应正文', async () => {
resolve.mockResolvedValueOnce([{ address: '1.1.1.1', family: 4 }])
const end = jest.fn()
const destroy = jest.fn()
const receive = jest.fn()
https.mockImplementation(((url: URL, options: RequestOptions, onResponse: (response: IncomingMessage) => void) => {
expect(url.hostname).toBe('receiver.example.com')
expect(options).toMatchObject({ method: 'POST', agent: false, headers: { 'X-Signature': 'fixture' } })
options.lookup?.('receiver.example.com', {}, receive)
queueMicrotask(() => onResponse({ statusCode: 302, destroy } as unknown as IncomingMessage))
return Object.assign(new EventEmitter(), { end })
}) as unknown as typeof httpsRequest)
await expect(postAutoListingCallback(
'https://receiver.example.com/callback', { 'X-Signature': 'fixture' }, { test: true },
)).resolves.toBe(302)
expect(receive).toHaveBeenCalledWith(null, '1.1.1.1', 4)
expect(end).toHaveBeenCalledWith('{"test":true}')
expect(destroy).toHaveBeenCalledTimes(1)
expect(https).toHaveBeenCalledTimes(1)
})
test('拒绝覆盖路由和消息边界的请求头及非法头值', () => {
expect(() => validateCallbackAuth('Host', 'wrong.example.com')).toThrow()
expect(() => validateCallbackAuth('Content-Length', '0')).toThrow()
expect(() => validateCallbackAuth('X-Forwarded-Host', 'wrong.example.com')).toThrow()
expect(() => validateCallbackAuth('X-Key', 'line\r\ninjected')).toThrow()
expect(() => validateCallbackAuth('X-Key', 'fixture')).not.toThrow()
})