004ReviewseniorTypeScript / Axios真实来源改编 Axios
Axios:给内部 API client 增加请求 URL 校验
审查一个给带 Authorization 的 internal API client 增加 URL 校验的补丁:作者拒绝以 // 开头的 protocol-relative URL。
@@ -13,6 +13,12 @@ export const internalApi = axios.create({ // Callers pass a path that is appended to baseURL. export async function fetchInternal(path: string) {+ // Protocol-relative URLs (//host) are treated as absolute by Axios and+ // would bypass baseURL, sending our Authorization header off-host.+ if (path.startsWith('//')) {+ throw new Error('absolute URL is not allowed')+ }+ const response = await internalApi.get(path) return response.data }@@ -10,6 +10,11 @@ test('fetches relative internal paths', async () => { const data = await fetchInternal('/users') expect(data).toEqual({ ok: true }) }) +test('rejects protocol-relative urls', async () => {+ await expect(fetchInternal('//evil.test/a')).rejects.toThrow()+})+ test('propagates non-2xx responses as errors', async () => { mockAxios.onGet('/missing').reply(404) await expect(fetchInternal('/missing')).rejects.toThrow() })