Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/app/api/ask-ai/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,24 @@ async function callGroqWithFallback(
/**
* Main AI Solver API Route.
*/
// Maximum allowed Content-Length for this route in bytes.
// imageBase64 payloads are read entirely into memory before the slice, so a
// large body allocates the full payload on the server heap before any truncation
// occurs. Enforcing this limit early keeps memory usage predictable under load.
const MAX_BODY_BYTES = 512 * 1024; // 512 KB

export async function POST(req: Request) {
try {
// Reject oversized payloads before parsing JSON to avoid loading
// a multi-megabyte body into memory only to discard most of it.
const contentLength = parseInt(req.headers.get('content-length') ?? '0', 10);
if (contentLength > MAX_BODY_BYTES) {
Comment on lines +211 to +212
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: This size guard trusts the client-supplied Content-Length header, so a request sent with chunked transfer encoding (no Content-Length) or a missing header bypasses the check and still reaches req.json(), allowing large bodies to be fully buffered in memory. Enforce the limit based on actual bytes read from the request stream (or reject requests without a valid length for this endpoint) so oversized payloads cannot bypass the protection. [security]

Severity Level: Major ⚠️
- ❌ /api/ask-ai accepts >512 KB bodies via chunked.
- ❌ Memory usage spikes when large chunked bodies parsed.
- ⚠️ 512 KB limit ineffective against crafted HTTP clients.
Steps of Reproduction ✅
1. Start the DoubtDesk application so the Next.js API route implemented in
`src/app/api/ask-ai/route.ts` is served; this route defines `export async function
POST(req: Request)` with the `contentLength` guard at approximately lines 32–38 (as seen
in the file content).

2. From a custom HTTP client (e.g., `nc`, `telnet`, or a raw Node.js `net` socket), send
an HTTP/1.1 request to `POST /api/ask-ai` with headers including `Transfer-Encoding:
chunked` and **no `Content-Length` header**, and a JSON body larger than 512 KB (for
example, a large `imageBase64` string) so that the request remains under the framework's
global 4 MB limit but above `MAX_BODY_BYTES`.

3. On the server, the POST handler at `src/app/api/ask-ai/route.ts` executes the guard
`const contentLength = parseInt(req.headers.get('content-length') ?? '0', 10);` followed
by `if (contentLength > MAX_BODY_BYTES) { ... }`. Because the request is chunked and omits
`Content-Length`, `req.headers.get('content-length')` returns `null`, `parseInt('0', 10)`
yields `0`, and the `if (contentLength > MAX_BODY_BYTES)` condition at lines 211–212
evaluates to `false`, so the 413 response is not triggered.

4. Execution continues into the rest of the POST handler, which later calls `await
req.json()` to parse the request body; this causes the full >512 KB JSON payload
(including the large `imageBase64` field) to be read and buffered into memory, bypassing
the intended size restriction and allowing repeated large requests to consume significant
heap memory under concurrent load.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/app/api/ask-ai/route.ts
**Line:** 211:212
**Comment:**
	*Security: This size guard trusts the client-supplied `Content-Length` header, so a request sent with chunked transfer encoding (no `Content-Length`) or a missing header bypasses the check and still reaches `req.json()`, allowing large bodies to be fully buffered in memory. Enforce the limit based on actual bytes read from the request stream (or reject requests without a valid length for this endpoint) so oversized payloads cannot bypass the protection.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

return NextResponse.json(
{ error: 'Request payload too large. Maximum size is 512 KB.' },
{ status: 413 }
Comment on lines +205 to +215
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 Architect Review — HIGH

The new 512 KB server-side body limit for /api/ask-ai reduces the maximum accepted image payload well below what the Ask AI UI promises ("Max 10MB") and below what the client currently enforces, so typical camera-sized uploads that previously worked will now be rejected with 413 while the UI still suggests larger files are acceptable.

Suggestion: Align the backend limit with the product flow by either increasing the server limit or, if 512 KB is required, adding client-side file-size enforcement/compression plus updated UX copy and explicit handling of 413 responses in src/app/ask-ai/page.tsx so users are warned before upload and see a clear size-related error.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is an **Architect / Logical Review** comment left during a code review. These reviews are first-class, important findings — not optional suggestions. Do NOT dismiss this as a 'big architectural change' just because the title says architect review; most of these can be resolved with a small, localized fix once the intent is understood.

**Path:** src/app/api/ask-ai/route.ts
**Line:** 205:215
**Comment:**
	*HIGH: The new 512 KB server-side body limit for /api/ask-ai reduces the maximum accepted image payload well below what the Ask AI UI promises ("Max 10MB") and below what the client currently enforces, so typical camera-sized uploads that previously worked will now be rejected with 413 while the UI still suggests larger files are acceptable.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
If a suggested approach is provided above, use it as the authoritative instruction. If no explicit code suggestion is given, you MUST still draft and apply your own minimal, localized fix — do not punt back with 'no suggestion provided, review manually'. Keep the change as small as possible: add a guard clause, gate on a loading state, reorder an await, wrap in a conditional, etc. Do not refactor surrounding code or expand scope beyond the finding.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix

);
}

const user = await currentUser();

if (!user) {
Expand Down
Loading