소스 검색

Fix fetch-metadata endpoint (#212)

* fetch-metadata endpoint

* cancel
Bernt Christian Egeland 3 달 전
부모
커밋
c4420eb212
2개의 변경된 파일과 199개의 추가작업 그리고 25개의 파일을 삭제
  1. 131 0
      src/__tests__/api/fetch-metadata-ssrf.test.ts
  2. 68 25
      src/app/api/protected/fetch-metadata/route.ts

+ 131 - 0
src/__tests__/api/fetch-metadata-ssrf.test.ts

@@ -0,0 +1,131 @@
+/**
+ * Regression guard for the SSRF fix in POST /api/protected/fetch-metadata
+ * (GHSA-cpp2-8rm9-f8c5). Locks in that:
+ *   - the SSRF guard runs on the initial URL AND every redirect hop,
+ *   - redirects are followed manually (redirect: "manual", not "follow"),
+ *   - a blocked target (direct or via redirect) is rejected before fetch,
+ *   - legitimate direct + redirecting URLs still return parsed metadata.
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/auth", () => ({
+  auth: { api: { getSession: vi.fn() } },
+}));
+
+vi.mock("next/headers", () => ({
+  headers: vi.fn().mockResolvedValue(new Headers()),
+}));
+
+vi.mock("@/features/webhooks/Lib/ssrf", () => ({
+  checkWebhookUrl: vi.fn(),
+}));
+
+import { auth } from "@/lib/auth";
+import { headers } from "next/headers";
+import { checkWebhookUrl } from "@/features/webhooks/Lib/ssrf";
+import { POST } from "@/app/api/protected/fetch-metadata/route";
+import type { NextRequest } from "next/server";
+
+const mockGetSession = vi.mocked(auth.api.getSession);
+const mockCheck = vi.mocked(checkWebhookUrl);
+const mockFetch = vi.fn();
+
+function req(url: unknown): NextRequest {
+  return { json: async () => ({ url }) } as unknown as NextRequest;
+}
+
+function res(
+  status: number,
+  headers: Record<string, string> = {},
+  body = "",
+): Response {
+  return {
+    status,
+    ok: status >= 200 && status < 300,
+    headers: new Headers(headers),
+    text: async () => body,
+  } as unknown as Response;
+}
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  vi.stubGlobal("fetch", mockFetch);
+  // resetAllMocks wipes implementations, so re-establish the default mocks.
+  vi.mocked(headers).mockResolvedValue(new Headers());
+  mockGetSession.mockResolvedValue({ user: { id: "user-1" } } as never);
+});
+
+describe("POST /api/protected/fetch-metadata — SSRF guard", () => {
+  it("returns 401 when unauthenticated (and never fetches)", async () => {
+    mockGetSession.mockResolvedValue(null as never);
+    const r = await POST(req("http://internal.local"));
+    expect(r.status).toBe(401);
+    expect(mockFetch).not.toHaveBeenCalled();
+  });
+
+  it("rejects a blocked target with 400 and never fetches it", async () => {
+    mockCheck.mockResolvedValue({ ok: false, reason: "private_ip" });
+    const r = await POST(req("http://169.254.169.254/latest/meta-data/"));
+    expect(r.status).toBe(400);
+    expect(await r.json()).toEqual({ error: "This URL is not allowed." });
+    expect(mockCheck).toHaveBeenCalledWith("http://169.254.169.254/latest/meta-data/");
+    expect(mockFetch).not.toHaveBeenCalled();
+  });
+
+  it("returns parsed metadata for a legitimate direct URL", async () => {
+    mockCheck.mockResolvedValue({ ok: true });
+    mockFetch.mockResolvedValue(
+      res(200, { "content-type": "text/html" }, "<title>Example Domain</title>"),
+    );
+    const r = await POST(req("https://example.com"));
+    expect(r.status).toBe(200);
+    expect((await r.json()).name).toBe("Example Domain");
+    expect(mockFetch.mock.calls[0][1].redirect).toBe("manual");
+  });
+
+  it("follows a redirect and validates EVERY hop", async () => {
+    mockCheck.mockResolvedValue({ ok: true });
+    mockFetch
+      .mockResolvedValueOnce(res(301, { location: "https://final.example/page" }))
+      .mockResolvedValueOnce(
+        res(200, { "content-type": "text/html" }, "<title>Final Page</title>"),
+      );
+
+    const r = await POST(req("http://start.example"));
+
+    expect(r.status).toBe(200);
+    expect((await r.json()).name).toBe("Final Page");
+    expect(mockFetch).toHaveBeenCalledTimes(2);
+    // Guard ran on both the initial URL and the redirect target.
+    expect(mockCheck).toHaveBeenCalledWith("http://start.example");
+    expect(mockCheck).toHaveBeenCalledWith("https://final.example/page");
+    // Never delegates redirect-following to fetch.
+    expect(mockFetch.mock.calls[0][1].redirect).toBe("manual");
+  });
+
+  it("blocks a redirect that points at an internal target (no second fetch)", async () => {
+    mockCheck
+      .mockResolvedValueOnce({ ok: true }) // initial public URL
+      .mockResolvedValueOnce({ ok: false, reason: "private_ip" }); // redirect target
+    mockFetch.mockResolvedValueOnce(
+      res(302, { location: "http://127.0.0.1:5432/" }),
+    );
+
+    const r = await POST(req("http://start.example"));
+
+    expect(r.status).toBe(400);
+    expect(mockFetch).toHaveBeenCalledTimes(1); // never fetched the internal target
+    expect(mockCheck).toHaveBeenCalledWith("http://127.0.0.1:5432/");
+  });
+
+  it("stops with 422 on a redirect loop instead of following forever", async () => {
+    mockCheck.mockResolvedValue({ ok: true });
+    let n = 0;
+    mockFetch.mockImplementation(async () =>
+      res(302, { location: `https://hop.example/${n++}` }),
+    );
+    const r = await POST(req("http://start.example"));
+    expect(r.status).toBe(422);
+    expect(await r.json()).toEqual({ error: "Too many redirects" });
+  });
+});

+ 68 - 25
src/app/api/protected/fetch-metadata/route.ts

@@ -1,6 +1,11 @@
 import { NextRequest, NextResponse } from "next/server";
 import { NextRequest, NextResponse } from "next/server";
 import { auth } from "@/lib/auth";
 import { auth } from "@/lib/auth";
 import { headers } from "next/headers";
 import { headers } from "next/headers";
+import { checkWebhookUrl } from "@/features/webhooks/Lib/ssrf";
+
+// Cap the redirect chain we will follow (mirrors browser/undici defaults) so a
+// malicious or misconfigured target can't loop us indefinitely.
+const MAX_REDIRECTS = 20;
 
 
 interface Metadata {
 interface Metadata {
   name?: string;
   name?: string;
@@ -38,31 +43,69 @@ export async function POST(request: NextRequest) {
     const controller = new AbortController();
     const controller = new AbortController();
     const timeout = setTimeout(() => controller.abort(), 10000);
     const timeout = setTimeout(() => controller.abort(), 10000);
 
 
-    // Strip fragment from URL (servers don't receive it)
-    const fetchUrl = url.split("#")[0];
-
-    const response = await fetch(fetchUrl, {
-      signal: controller.signal,
-      headers: {
-        "User-Agent":
-          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
-        Accept:
-          "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
-        "Accept-Language": "en-US,en;q=0.9,no;q=0.8",
-        "Accept-Encoding": "gzip, deflate, br",
-        "Cache-Control": "no-cache",
-        Pragma: "no-cache",
-        "Sec-Ch-Ua": '"Chromium";v="131", "Not_A Brand";v="24"',
-        "Sec-Ch-Ua-Mobile": "?0",
-        "Sec-Ch-Ua-Platform": '"Windows"',
-        "Sec-Fetch-Dest": "document",
-        "Sec-Fetch-Mode": "navigate",
-        "Sec-Fetch-Site": "none",
-        "Sec-Fetch-User": "?1",
-        "Upgrade-Insecure-Requests": "1",
-      },
-      redirect: "follow",
-    });
+    const requestHeaders = {
+      "User-Agent":
+        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
+      Accept:
+        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
+      "Accept-Language": "en-US,en;q=0.9,no;q=0.8",
+      "Accept-Encoding": "gzip, deflate, br",
+      "Cache-Control": "no-cache",
+      Pragma: "no-cache",
+      "Sec-Ch-Ua": '"Chromium";v="131", "Not_A Brand";v="24"',
+      "Sec-Ch-Ua-Mobile": "?0",
+      "Sec-Ch-Ua-Platform": '"Windows"',
+      "Sec-Fetch-Dest": "document",
+      "Sec-Fetch-Mode": "navigate",
+      "Sec-Fetch-Site": "none",
+      "Sec-Fetch-User": "?1",
+      "Upgrade-Insecure-Requests": "1",
+    };
+
+    // Follow redirects manually so the SSRF guard runs on EVERY hop. Plain
+    // `redirect: "follow"` would let an allowed public URL bounce (via 3xx) into
+    // the internal network; here the initial URL and every Location target are
+    // validated by checkWebhookUrl (blocks private/loopback/link-local/metadata
+    // hosts and non-http(s) schemes, with DNS resolution) before we fetch them.
+    // Strip fragment from URL (servers don't receive it).
+    let currentUrl = url.split("#")[0];
+    let response: Response;
+    for (let redirects = 0; ; redirects++) {
+      const safety = await checkWebhookUrl(currentUrl);
+      if (!safety.ok) {
+        clearTimeout(timeout);
+        return NextResponse.json(
+          { error: "This URL is not allowed." },
+          { status: 400 }
+        );
+      }
+
+      response = await fetch(currentUrl, {
+        signal: controller.signal,
+        headers: requestHeaders,
+        redirect: "manual",
+      });
+
+      // Non-3xx → this is the final response (its body is read below).
+      if (response.status < 300 || response.status >= 400) break;
+
+      // It's a redirect: capture the target, then release this intermediate
+      // response body so undici can free the socket instead of holding it open
+      // across the chain until GC.
+      const location = response.headers.get("location");
+      await response.body?.cancel();
+      if (!location) break; // redirect without a target — treat as final
+
+      if (redirects >= MAX_REDIRECTS) {
+        clearTimeout(timeout);
+        return NextResponse.json(
+          { error: "Too many redirects" },
+          { status: 422 }
+        );
+      }
+      // Resolve relative redirects against the current URL; drop any fragment.
+      currentUrl = new URL(location, currentUrl).toString().split("#")[0];
+    }
 
 
     clearTimeout(timeout);
     clearTimeout(timeout);