Skip to content

🛡️ Sentinel: [CRITICAL] Fix SSRF vulnerability in bulk lookup API#197

Open
aicoder2009 wants to merge 1 commit into
mainfrom
sentinel/fix-ssrf-bulk-lookup-9423814406976627706
Open

🛡️ Sentinel: [CRITICAL] Fix SSRF vulnerability in bulk lookup API#197
aicoder2009 wants to merge 1 commit into
mainfrom
sentinel/fix-ssrf-bulk-lookup-9423814406976627706

Conversation

@aicoder2009

@aicoder2009 aicoder2009 commented Jun 29, 2026

Copy link
Copy Markdown
Owner

🚨 Severity: CRITICAL

💡 Vulnerability: The bulk lookup API (/api/lookup/bulk) used fetch() with dynamically derived hostnames (request.nextUrl.origin) for loopback requests to internal route handlers. This is an SSRF vulnerability because request.nextUrl.origin is constructed using the user-controllable Host (or X-Forwarded-Host) header.

🎯 Impact: An attacker could spoof the Host header to trick the internal server into making HTTP POST requests to arbitrary external domains, potentially exposing internal server behavior or acting as a proxy for malicious activity.

🔧 Fix: Removed the HTTP loopback mechanism. Instead, the specific Next.js route handlers (url, doi, isbn) are directly imported and invoked as functions, passing a synthetic NextRequest object. This eliminates the network layer parsing of the Host header entirely.

Verification:

  • Verify by sending a request to the bulk API with an invalid/malicious Host header (it should no longer redirect traffic).
  • The route.test.ts has been refactored to check that doiHandler, urlHandler, and isbnHandler are directly invoked instead of global.fetch. All tests pass.

PR created automatically by Jules for task 9423814406976627706 started by @aicoder2009

Summary by CodeRabbit

  • Bug Fixes
    • Improved security for bulk lookups by removing a path that could be influenced by request headers.
    • Bulk lookups now complete through a safer internal routing flow, with the same results and summary output as before.
    • Updated automated checks to reflect the new lookup behavior and keep batch processing reliable.

Removed loopback fetches relying on request.nextUrl.origin which is susceptible to Host header spoofing. Instead, route handlers are now directly imported and invoked with synthetic requests.

Co-authored-by: aicoder2009 <127642633+aicoder2009@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel

vercel Bot commented Jun 29, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
opencitation Ready Ready Preview, Comment Jun 29, 2026 6:21am

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The bulk lookup API route (/api/lookup/bulk) is refactored to eliminate SSRF: instead of calling fetch() with a URL derived from request.nextUrl.origin, it now imports and directly invokes the url, doi, and isbn route handlers with a synthetic NextRequest. Tests are updated to mock the handler modules instead of global.fetch, and a sentinel doc entry records the fix.

Changes

SSRF Fix: Bulk Lookup Direct Handler Dispatch

Layer / File(s) Summary
Direct handler dispatch in bulk route
src/app/api/lookup/bulk/route.ts
Imports POST from url/route, doi/route, isbn/route; removes request.nextUrl.origin derivation; refactors item-type detection to select a handler and handlerBody; replaces fetch with new NextRequest("http://localhost", …) and await handler(req).
Test mocking updated to handler mocks
src/app/api/lookup/bulk/route.test.ts
Replaces global.fetch mock with vi.mock of the three sub-route modules; routing and batch tests assert handler invocations via mockResolvedValueOnce instead of inspecting fetch call URLs.
Sentinel security doc
.jules/sentinel.md
Adds entry documenting the SSRF vulnerability (Host-header-derived loopback URL) and the mitigation (direct handler invocation).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 No more fetch through loopback land,
The Host header's tricks are banned.
We call our handlers face to face,
A synthetic request in their place.
SSRF begone—by a bunny's hand! 🛡️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main change: fixing an SSRF issue in the bulk lookup API.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch sentinel/fix-ssrf-bulk-lookup-9423814406976627706

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/api/lookup/bulk/route.test.ts`:
- Around line 3-10: The mocks for the URL/DOI/ISBN handlers are too permissive
and don’t verify the forwarded request body shape, so regressions in the bulk
route contract can slip through. Update the tests around bulk lookup to use the
mocked POST handlers from urlHandler, doiHandler, and isbnHandler with
mockImplementationOnce and inspect await req.json() inside each mock to assert
the expected payload keys ({ url }, { doi }, { isbn }). Keep the assertions tied
to the bulk route’s forwarding behavior so the tests fail if the wrong JSON
shape is sent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b8cb0fa8-b061-4b20-90d5-a0e078142dd7

📥 Commits

Reviewing files that changed from the base of the PR and between b69285b and 6ff1eea.

📒 Files selected for processing (3)
  • .jules/sentinel.md
  • src/app/api/lookup/bulk/route.test.ts
  • src/app/api/lookup/bulk/route.ts

Comment on lines +3 to +10
import { NextRequest, NextResponse } from 'next/server';
import { POST as urlHandler } from '../url/route';
import { POST as doiHandler } from '../doi/route';
import { POST as isbnHandler } from '../isbn/route';

vi.mock('../url/route', () => ({ POST: vi.fn() }));
vi.mock('../doi/route', () => ({ POST: vi.fn() }));
vi.mock('../isbn/route', () => ({ POST: vi.fn() }));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the forwarded JSON body in these handler mocks.

Right now these stubs succeed for any request, so a regression from { url } / { doi } / { isbn } to the wrong payload shape would still pass even though the real sub-routes reject it. Switching these to mockImplementationOnce and checking await req.json() locks the test to the actual cross-route contract, and it also gives NextResponse at Line 3 a real use.

Proposed test pattern
-    (urlHandler as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
-      ok: true,
-      json: async () => ({ data: { title: 'Example Page' } }),
-    });
+    (urlHandler as ReturnType<typeof vi.fn>).mockImplementationOnce(async (req: NextRequest) => {
+      expect(await req.json()).toEqual({ url: 'https://example.com' });
+      return NextResponse.json({ data: { title: 'Example Page' } });
+    });

As per coding guidelines, "Write tests for citation formatting and API route logic."

Also applies to: 62-97, 108-115, 126-133

🧰 Tools
🪛 ESLint

[error] 3-3: 'NextResponse' is defined but never used. Allowed unused vars must match /^_/u.

(@typescript-eslint/no-unused-vars)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/lookup/bulk/route.test.ts` around lines 3 - 10, The mocks for the
URL/DOI/ISBN handlers are too permissive and don’t verify the forwarded request
body shape, so regressions in the bulk route contract can slip through. Update
the tests around bulk lookup to use the mocked POST handlers from urlHandler,
doiHandler, and isbnHandler with mockImplementationOnce and inspect await
req.json() inside each mock to assert the expected payload keys ({ url }, { doi
}, { isbn }). Keep the assertions tied to the bulk route’s forwarding behavior
so the tests fail if the wrong JSON shape is sent.

Sources: Coding guidelines, Linters/SAST tools

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant