004ReviewseniorTypeScript / Axios真实来源改编 Axios

Axios:给内部 API client 增加请求 URL 校验

审查一个给带 Authorization 的 internal API client 增加 URL 校验的补丁:作者拒绝以 // 开头的 protocol-relative URL。

ai-pr.diffdiff · 35 lines
diff --git a/src/internal-api.ts b/src/internal-api.tsindex d42b342..bad0004 100644--- a/src/internal-api.ts+++ b/src/internal-api.ts@@ -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 }diff --git a/src/internal-api.test.ts b/src/internal-api.test.tsindex 5c1f0aa..2e7b913 100644--- a/src/internal-api.test.ts+++ b/src/internal-api.test.ts@@ -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() })