Skip to content

fix(api): parse request bodies after auth - #3833

Merged
jordan-simonovski merged 2 commits into
mainfrom
jordansimonovski/parse-body-after-auth
Nov 27, 2026
Merged

jordan-simonovski merged 2 commits into
mainfrom
jordansimonovski/parse-body-after-auth

Conversation

@jordan-simonovski

@jordan-simonovski jordan-simonovski commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The API parsed JSON, text and form bodies up to 32 MB on every route before checking auth, so anyone could make it buffer and parse 32 MB per request and only then get a 401. Bodies are now parsed after the auth check.

  • An anonymous request to a protected route gets a 401 without its body being read.
  • Login, register and team setup accept bodies up to 100 KB. An oversized login is sent back to the login page; the other two return 413.
  • Signed-in users, API keys (/api/v2, /mcp) and local mode keep the 32 MB limit.

Breaking changes: none for authenticated callers. A client posting more than 100 KB to login, register or team setup is now rejected.

Implementation detail
  • Each auth mount runs parseBody after isUserAuthenticated or validateUserAccessKey. A new route that takes a body outside those mounts has to add parsePublicBody itself.
  • /mcp uses express() plus the SDK's localhostHostValidation instead of createMcpExpressApp, whose built-in JSON parser ran before the access key check.
  • captureProxyBody matches on baseUrl + path, because the parser now runs inside the /clickhouse-proxy mount, where req.path drops the mount prefix.
  • Tested with the new bodyParser.int.test.ts and the full packages/api integration suite.

How to reproduce

Starting point: yarn dev, with API set to the API URL. Malformed JSON shows whether the body was parsed before auth.

curl -s -o /dev/null -w '%{http_code}\n' -X POST "$API/dashboards" \
  -H 'content-type: application/json' -d '{"a":'

On main:

  1. The command prints 400: the body was parsed before the auth check.

On this branch:

  1. The command prints 401: the request is rejected before the body is read.

The issue has a repro that shows the memory growth from four 32 MB requests.

How to test on Vercel preview

N/A, non-UI change.

References


Note

Medium Risk
Touches global Express middleware ordering for all body-bearing routes; miswired mounts could break login or proxy forwarding, but behavior is covered by new integration tests.

Overview
Request bodies are no longer parsed globally up to 32 MB. Protected routes (/dashboards, /api/v2/*, /mcp, etc.) run parseBody only after session or API-key auth, so anonymous POSTs get 401 without reading the body (fixes unauthenticated large-body abuse).

Pre-auth routes (login/password, register/password, team/setup/:token) use parsePublicBody with a 100 KB cap instead of the old global limit. Oversized register/team-setup payloads return 413; login still surfaces oversize via redirect.

The MCP router drops createMcpExpressApp’s built-in JSON parser and parses after validateUserAccessKey. captureProxyBody matches ClickHouse proxy paths via baseUrl + path because parsing now lives inside the /clickhouse-proxy mount. Integration tests assert anonymous 401 without parse, public 100 KB caps, and authenticated 32 MB behavior.

Reviewed by Cursor Bugbot for commit e360a7e. Bugbot is set up for automated code reviews on this repo. Configure here.

Body parsers ran globally with a 32 MB limit before any auth check, so an
anonymous caller could make the API buffer and parse 32 MB per request
before getting a 401. Parsing now runs after each auth middleware;
authenticated callers keep 32 MB, and login, register and team setup take
up to 100 KB.

Fixes #3831
@jordan-simonovski
jordan-simonovski requested a review from a team as a code owner November 25, 2026 23:52
@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Nov 27, 2026 1:54pm UTC
hyperdx-storybook Ready Ready Preview Nov 27, 2026 1:54pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: e360a7e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@hyperdx/api Patch
@hyperdx/app Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions github-actions Bot added the review/tier-4 Critical — deep review + domain expert sign-off label Nov 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔴 Tier 4 — Critical

Touches authentication, tenancy data models, the public API or shipped database config — or substantially changes the query rendering engine, background tasks, the OTel pipeline, image build, or release CI.

Why this tier:

  • Critical-path files (1) — tenancy, public API, or shipped database config:
    • packages/api/src/routers/external-api/v2/index.ts

Review process: Deep review from a domain expert. Synchronous walkthrough may be required.
SLA: Schedule synchronous review within 2 business days.

Stats
  • Production files changed: 6
  • Production lines changed: 127 (+ 72 in test files, excluded from tier calculation)
  • Critical-path lines changed: 38
  • Branch: jordansimonovski/parse-body-after-auth
  • Author: jordan-simonovski

To override this classification, remove the review/tier-4 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 108 in total (1.10%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@github-actions

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

2 finding(s): 🔴 0 P0/P1 · 🟡 0 P2 · 🔵 2 P3

No inline comments. 2 P3 folded at the bottom.

🔵 2 P3 — no action needed before merge
  • 🔵 P3 packages/api/src/api-app.ts:101 — parseBody has to be added by hand next to every auth middleware (22 mounts); a mount that leaves it out gets req.body === undefined and no error → Export composed stacks from middleware/auth.ts or middleware/bodyParser.ts, for example authenticatedSession = [isUserAuthenticated, ...parseBody] and authenticatedAccessKey = [validateUserAccessKey, ...parseBody]. Use them in api-app.ts, routers/external-api/v2/index.ts and mcp/app.ts, so an authenticated mount always parses its body after auth. Today a new app.use('/x', isUserAuthenticated, xRouter) would silently get no body, and only the PR description says otherwise.
  • 🔵 P3 packages/api/src/utils/proxyBody.ts:391 — captureProxyBody still matches the mount path with a regex, even though parsers are now mounted per route → Now that parsing happens per mount, give /clickhouse-proxy its own parser stack whose verify always captures, and drop the verify from the shared parseBody/parsePublicBody. This removes the baseUrl + path regex, which is a second copy of the mount path in api-app.ts, and stops every JSON, text and form request on other routes from running this check.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@security-ai-gate-reviewer security-ai-gate-reviewer 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.

Auto-approved by the AI review gate on 3222596. Details in the approver's comment on this pull request.

@security-ai-gate-reviewer

Copy link
Copy Markdown

AI review gate — auto-approved

32225966221a is approved by security-ai-gate-reviewer[bot], an automated identity, not a human. The approval stands on the required AI review: Cursor Bugbot concluded green on this commit and the AI review gate is SUCCESS (its own comment has the verdict), and the change touches no path that requires a human reviewer. It is bound to this commit: a new push dismisses it and the approver re-evaluates.

History (latest 5 heads, newest first)

  • 32225966221a approved — green: Cursor Bugbot

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 478 passed • 1 skipped • 1141s

Status Count
✅ Passed 478
❌ Failed 0
⚠️ Flaky 13
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@github-actions

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. Eleven reviewers traced every route mount, middleware ordering, the proxy baseUrl+path matching, and the MCP app rebuild; the fix is complete and well-guarded. Every private, external-v2, and /mcp route gates parseBody behind auth, all three public POST routes carry parsePublicBody (100kb), the removed global parsers leave no body-reading route unparsed, and body-parse errors (413/400) bubble cleanly to the global appErrorHandler. The authenticated /mcp happy-path and the clickhouse-proxy mount are both covered by pre-existing integration tests that exercise the new arrangement.

🟡 P2 -- recommended

  • packages/api/src/mcp/app.ts:17 -- rebuilding the MCP app as express() + localhostHostValidation() drops whatever createMcpExpressApp contributed beyond host validation and the JSON parser; this could not be confirmed because the SDK is not installed in the review environment.
    • Fix: run the full packages/api integration suite in CI (where the SDK is installed) and confirm the helper added no error handler, accept negotiation, or DNS-rebinding middleware that is now missing; re-add any that was dropped.
    • correctness, security, adversarial, reliability, agent-native
🔵 P3 nitpicks (5)
  • packages/api/src/middleware/bodyParser.ts:11 -- the new per-route pattern is an unenforced convention: a future authed route that omits parseBody (or a public body route that omits parsePublicBody) silently yields req.body === undefined rather than a parse error.
    • Fix: export a combined helper such as authed = [isUserAuthenticated, ...parseBody] used at every private mount, or add an assertion that an authed body route has a parser.
    • maintainability
  • packages/api/src/utils/proxyBody.ts:23 -- the /clickhouse-proxy literal now lives in three source locations (the mount in api-app.ts, the strip in clickhouseProxy.ts, and this capture regex), so remounting the proxy would silently break body capture with no compile-time link.
    • Fix: extract the mount path to one shared exported constant referenced by all three sites.
    • maintainability
  • packages/api/src/middleware/bodyParser.ts:13 -- parseBody/parsePublicBody are middleware arrays but named as singular verbs, and call sites mix bare passing with spread (...parseBody in mcp/app.ts), obscuring their shape.
    • Fix: give them collection names and standardize on one passing form across call sites.
    • maintainability
  • packages/api/src/middleware/__tests__/bodyParser.int.test.ts:54 -- the only authenticated body-parse assertion sends ~200kb of malformed JSON expecting 400, which proves parsing ran past the 100kb cap but neither pins the 32mb private limit nor proves a well-formed large body populates req.body.
    • Fix: add a signed-in case sending a well-formed body above 100kb asserting 2xx with the field round-tripping, and optionally a just-over-32mb case asserting 413.
    • testing
  • packages/api/src/routers/api/root.ts:89 -- an oversized/malformed body yields divergent error shapes across public routes (login redirects to /login?err=unknown; register and team-setup return appErrorHandler JSON), though it is only reachable above 100kb where no legitimate credential payload lands.
    • Fix: align the three public routes on one error shape for parse/size failures, or document the divergence as intentional.
    • api-contract, reliability

Pre-existing (non-blocking)

  • packages/api/src/mcp/app.ts:46 -- the async POST handler has no catch, so a rejection from server.connect()/transport.handleRequest() is not forwarded to Express 4's error middleware and the request can hang until socket timeout. The handler body is unchanged by this PR (only the middleware array moved), so this is not introduced here, but it now lives in a hand-rolled app.
    • reliability

Reviewers (11): correctness, security, adversarial, api-contract, reliability, testing, maintainability, kieran-typescript, project-standards, agent-native, learnings-researcher.

Testing gaps:

  • No test exercises a POST form body (application/x-www-form-urlencoded) on /v1/prometheus through the extended:false parseBody mount after the global parser's removal.
  • No positive assertion that a normal under-100kb body on /register/password and /team/setup/:token is still parsed and populated.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — e360a7e2 Deployed Nov 27, 2026 by vercel[bot]
Preview – hyperdx-storybook — e360a7e2 Deployed Nov 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-4 Critical — deep review + domain expert sign-off

Projects

None yet

Development

Successfully merging this pull request may close these issues.

API parses request bodies up to 32 MB before auth

3 participants