From bedc23db03f1669f88d2ab244c71a0cff5370c78 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sun, 28 Jun 2026 06:28:22 +0000 Subject: [PATCH] Fix SSRF in bulk lookup API loopback calls Co-authored-by: aicoder2009 <127642633+aicoder2009@users.noreply.github.com> --- .jules/sentinel.md | 4 +++ src/app/api/lookup/bulk/route.test.ts | 48 +++++++++++---------------- src/app/api/lookup/bulk/route.ts | 20 ++++++----- 3 files changed, 34 insertions(+), 38 deletions(-) diff --git a/.jules/sentinel.md b/.jules/sentinel.md index 88805da..be11f02 100644 --- a/.jules/sentinel.md +++ b/.jules/sentinel.md @@ -6,3 +6,7 @@ **Vulnerability:** The application was using the `marked` library to parse Markdown content into HTML (in `src/app/docs/changelog/page.tsx` and `src/lib/docs.ts`) and subsequently rendering it using `dangerouslySetInnerHTML` without proper sanitization. **Learning:** `marked` does not sanitize HTML by default. While this may seem safe for trusted inputs (like internal docs or GitHub releases), if malicious input manages to enter these sources, it leads directly to an XSS vulnerability. **Prevention:** The output of `marked` (or any markdown parser) must always be wrapped with `DOMPurify.sanitize()` (using `isomorphic-dompurify` for SSR) before being passed to `dangerouslySetInnerHTML`. +## 2025-02-28 - [SSRF via Host Header Loopback in Next.js API] +**Vulnerability:** The bulk lookup API (`src/app/api/lookup/bulk/route.ts`) performed loopback API calls to process individual lookups by dynamically constructing URLs using `request.nextUrl.origin` (e.g., `fetch(`${request.nextUrl.origin}/api/lookup/...`)`). In Next.js, `request.nextUrl.origin` is derived directly from the user-controlled `Host` header. This allows attackers to manipulate the `Host` header and redirect the internal `fetch` call to a malicious server, leading to Server-Side Request Forgery (SSRF). +**Learning:** Never rely on the `Host` header or `request.nextUrl.origin` for internal loopback requests in a Next.js environment, as it is fully controllable by the client. Doing so inherently exposes SSRF risks. +**Prevention:** Rather than performing HTTP `fetch` requests over the network for internal API routes, directly import and invoke the corresponding Next.js Route Handler functions (e.g., `POST(syntheticRequest)`). For required network loopbacks, hardcode the trusted origin (e.g., via a protected environment variable or `localhost:`). diff --git a/src/app/api/lookup/bulk/route.test.ts b/src/app/api/lookup/bulk/route.test.ts index 7c14ffd..bd613e1 100644 --- a/src/app/api/lookup/bulk/route.test.ts +++ b/src/app/api/lookup/bulk/route.test.ts @@ -1,6 +1,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { POST } from './route'; -import { NextRequest } from 'next/server'; +import { NextRequest, NextResponse } from 'next/server'; +import { POST as urlLookup } from '@/app/api/lookup/url/route'; +import { POST as doiLookup } from '@/app/api/lookup/doi/route'; +import { POST as isbnLookup } from '@/app/api/lookup/isbn/route'; + +vi.mock('@/app/api/lookup/url/route', () => ({ POST: vi.fn() })); +vi.mock('@/app/api/lookup/doi/route', () => ({ POST: vi.fn() })); +vi.mock('@/app/api/lookup/isbn/route', () => ({ POST: vi.fn() })); global.fetch = vi.fn(); @@ -54,47 +61,32 @@ describe('Bulk Lookup API', () => { }); it('routes URLs to /api/lookup/url', async () => { - (global.fetch as ReturnType).mockResolvedValueOnce({ - ok: true, - json: async () => ({ data: { title: 'Example Page' } }), - }); + (urlLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ data: { title: 'Example Page' } }, { status: 200 })); const response = await POST(makeRequest({ items: ['https://example.com'] })); const data = await response.json(); expect(data.results[0].success).toBe(true); expect(data.results[0].data.title).toBe('Example Page'); - const [url] = (global.fetch as ReturnType).mock.calls[0] as [string]; - expect(url).toContain('/api/lookup/url'); + expect(urlLookup).toHaveBeenCalled(); }); it('routes DOIs to /api/lookup/doi', async () => { - (global.fetch as ReturnType).mockResolvedValueOnce({ - ok: true, - json: async () => ({ data: { title: 'Research Article' } }), - }); + (doiLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ data: { title: 'Research Article' } }, { status: 200 })); const response = await POST(makeRequest({ items: ['10.1000/xyz123'] })); const data = await response.json(); expect(data.results[0].success).toBe(true); - const [url] = (global.fetch as ReturnType).mock.calls[0] as [string]; - expect(url).toContain('/api/lookup/doi'); + expect(doiLookup).toHaveBeenCalled(); }); it('routes ISBNs to /api/lookup/isbn', async () => { - (global.fetch as ReturnType).mockResolvedValueOnce({ - ok: true, - json: async () => ({ data: { title: 'Book Title' } }), - }); + (isbnLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ data: { title: 'Book Title' } }, { status: 200 })); const response = await POST(makeRequest({ items: ['9780316769174'] })); const data = await response.json(); expect(data.results[0].success).toBe(true); - const [url] = (global.fetch as ReturnType).mock.calls[0] as [string]; - expect(url).toContain('/api/lookup/isbn'); + expect(isbnLookup).toHaveBeenCalled(); }); it('marks item as failed when sub-request fails', async () => { - (global.fetch as ReturnType).mockResolvedValueOnce({ - ok: false, - json: async () => ({ error: 'Not found' }), - }); + (doiLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ error: 'Not found' }, { status: 404 })); const response = await POST(makeRequest({ items: ['10.1000/nonexistent'] })); const data = await response.json(); expect(data.results[0].success).toBe(false); @@ -102,9 +94,8 @@ describe('Bulk Lookup API', () => { }); it('returns summary counts', async () => { - (global.fetch as ReturnType) - .mockResolvedValueOnce({ ok: true, json: async () => ({ data: { title: 'A' } }) }) - .mockResolvedValueOnce({ ok: false, json: async () => ({ error: 'fail' }) }); + (urlLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ data: { title: 'A' } }, { status: 200 })); + (doiLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ error: 'fail' }, { status: 400 })); const response = await POST( makeRequest({ items: ['https://success.com', '10.1000/fail'] }) ); @@ -115,9 +106,8 @@ describe('Bulk Lookup API', () => { }); it('handles mixed item types in one batch', async () => { - (global.fetch as ReturnType) - .mockResolvedValueOnce({ ok: true, json: async () => ({ data: { title: 'URL result' } }) }) - .mockResolvedValueOnce({ ok: true, json: async () => ({ data: { title: 'DOI result' } }) }); + (urlLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ data: { title: 'URL result' } }, { status: 200 })); + (doiLookup as ReturnType).mockResolvedValueOnce(NextResponse.json({ data: { title: 'DOI result' } }, { status: 200 })); const response = await POST( makeRequest({ items: ['https://example.com', '10.1000/abc'] }) ); diff --git a/src/app/api/lookup/bulk/route.ts b/src/app/api/lookup/bulk/route.ts index 96b8ed8..60ddb17 100644 --- a/src/app/api/lookup/bulk/route.ts +++ b/src/app/api/lookup/bulk/route.ts @@ -1,4 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; +import { POST as urlLookup } from "@/app/api/lookup/url/route"; +import { POST as doiLookup } from "@/app/api/lookup/doi/route"; +import { POST as isbnLookup } from "@/app/api/lookup/isbn/route"; interface LookupResult { input: string; @@ -22,8 +25,6 @@ export async function POST(request: NextRequest) { } // Refactored to process lookups concurrently for performance improvement - const baseUrl = request.nextUrl.origin; - const lookupPromises = items.map(async (item) => { const trimmedItem = item.trim(); if (!trimmedItem) { @@ -31,18 +32,19 @@ export async function POST(request: NextRequest) { } try { - let apiEndpoint: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let handler: (req: NextRequest) => Promise; let body: object; // Detect input type if (trimmedItem.match(/^(https?:\/\/|www\.)/i)) { - apiEndpoint = "/api/lookup/url"; + handler = urlLookup; body = { url: trimmedItem }; } else if (trimmedItem.match(/^10\.\d{4,}/)) { - apiEndpoint = "/api/lookup/doi"; + handler = doiLookup; body = { doi: trimmedItem }; } else if (trimmedItem.match(/^(97[89])?\d{9}[\dXx]$/)) { - apiEndpoint = "/api/lookup/isbn"; + handler = isbnLookup; body = { isbn: trimmedItem }; } else { return { @@ -52,13 +54,13 @@ export async function POST(request: NextRequest) { }; } - // Make the API call - const response = await fetch(`${baseUrl}${apiEndpoint}`, { + // Directly invoke the handler to prevent SSRF via Host header manipulation + const syntheticRequest = new NextRequest(new URL('http://localhost'), { method: "POST", - headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); + const response = await handler(syntheticRequest); const data = await response.json(); if (response.ok && data.data) {