payload icon indicating copy to clipboard operation
payload copied to clipboard

addDataAndFileToRequest returns 500 for malformed JSON request bodies

Open allandelmare opened this issue 9 months ago • 2 comments

Description

The addDataAndFileToRequest() utility in packages/next/src/utilities/ calls JSON.parse() without error handling. When malformed JSON is sent to Payload's REST API or GraphQL endpoints, the parsing fails with a SyntaxError that propagates as an unhandled 500 Internal Server Error instead of returning 400 Bad Request.

This affects all auto-generated REST API endpoints and the GraphQL endpoint since they share the same body parsing utility.

Current Behavior

Sending malformed JSON (e.g., with invalid escape sequences like \x or \z) to any Payload API endpoint returns:

  • HTTP Status: 500 Internal Server Error
  • Error in logs:
    SyntaxError: Bad escaped character in JSON at position 55
        at JSON.parse (<anonymous>)
        at addDataAndFileToRequest (dist/utilities/addDataAndFileToRequest.js:41:...)
    

Expected Behavior

Malformed JSON should return:

  • HTTP Status: 400 Bad Request
  • Response: Structured error message indicating invalid JSON
  • Logs: No stack trace (client error, not server error)

Reproduction Steps

curl -X POST https://your-app.com/api/posts \
  -H "Content-Type: application/json" \
  -d '{"title": "test\x"}'

Result: 500 Internal Server Error Expected: 400 Bad Request

Impact

  1. Incorrect HTTP semantics — client errors reported as server errors
  2. Noisy production logs — stack traces from bots/scanners sending malformed requests
  3. Monitoring pollution — can't distinguish real server issues from bad client input
  4. No workaround — auto-generated collection endpoints can't add custom error handling

Proposed Solution

Wrap JSON.parse() in addDataAndFileToRequest with try/catch:

try {
  const data = JSON.parse(bodyText);
  // ... continue processing
} catch (error) {
  if (error instanceof SyntaxError) {
    throw new APIError('Invalid JSON in request body', httpStatus.BAD_REQUEST);
  }
  throw error;
}

Related Issues

  • #13410 — Fixed similar issue in v3.51.0 for missing filename case, but didn't address broader JSON parsing errors
  • Next.js #86945 — Framework-level body parsing issue (still open)

Environment

  • Payload: ^3.75.0
  • Next.js: ^16.1.6
  • Node.js: 20+

Context

Discovered during automated security assessment. Pentester sent malformed JSON to test error handling. While not a security vulnerability per se, returning 500 for client errors violates HTTP semantics and creates operational issues with logging and monitoring.

allandelmare avatar Feb 15 '26 18:02 allandelmare

🚀 This is included in version v3.78.0

github-actions[bot] avatar Feb 27 '26 20:02 github-actions[bot]

This issue has been automatically locked. Please open a new issue if this issue persists with any additional detail.

github-actions[bot] avatar Mar 07 '26 05:03 github-actions[bot]