gongxiangp2/lib/__tests__/external-api-key.test.ts
2026-05-07 16:37:22 +08:00

41 lines
1.3 KiB
TypeScript

/** @jest-environment node */
import { getApiKeyFromRequest } from '@/lib/external-api'
function createRequest(url: string, headers?: Record<string, string>) {
return {
nextUrl: new URL(url),
headers: new Headers(headers),
} as any
}
describe('getApiKeyFromRequest', () => {
test('默认只读取 X-API-Key 请求头', () => {
const request = createRequest('https://example.com/api/external/demo?apiKey=query-key', {
'X-API-Key': 'header-key',
})
expect(getApiKeyFromRequest(request)).toBe('header-key')
})
test('默认不读取 URL 参数,避免所有外部接口无意开放 query key', () => {
const request = createRequest('https://example.com/api/external/demo?apiKey=query-key')
expect(getApiKeyFromRequest(request)).toBeNull()
})
test('显式允许时可读取钉钉固定 URL 参数 apiKey', () => {
const request = createRequest('https://example.com/api/external/demo?apiKey=query-key')
expect(getApiKeyFromRequest(request, { allowQuery: true })).toBe('query-key')
})
test('请求头优先于 URL 参数', () => {
const request = createRequest('https://example.com/api/external/demo?apiKey=query-key', {
'X-API-Key': 'header-key',
})
expect(getApiKeyFromRequest(request, { allowQuery: true })).toBe('header-key')
})
})