Skip to content

fix(auth): handle GET OAuth callback with undefined req.body on Express 5#3496

Merged
PierreBrisorgueil merged 1 commit intomasterfrom
fix/oauth-callback-req-body-3492
Apr 23, 2026
Merged

fix(auth): handle GET OAuth callback with undefined req.body on Express 5#3496
PierreBrisorgueil merged 1 commit intomasterfrom
fix/oauth-callback-req-body-3492

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented Apr 23, 2026

Summary

  • Optional-chain req.body access in oauthCallback — Express 5 leaves req.body undefined on GET callbacks, crashing the classic web OAuth flow before reaching passport.authenticate().
  • Add integration test simulating an Express 5 GET callback (no body field on request).

Closes #3492

Context

Discovered while enabling Google OAuth on trawl (api.trawl.me). First real signin attempt returned:

{"message":"Cannot read properties of undefined (reading 'strategy')"}

Root cause: Express 5 no longer initializes req.body to {} when no body-parser middleware applies to the request. The existing unit test at auth.integration.tests.js:613 passed body: {} explicitly, hiding the bug.

Apple OAuth is unaffected (uses POST form_post → body populated by express.urlencoded).

Test plan

  • npm run test:integration — 260/260 green
  • Post-merge: propagate to downstream projects via /update-all-projects, re-test Google signin end-to-end on trawl.me

Related follow-ups (separate PRs)

Summary by CodeRabbit

  • Bug Fixes

    • Fixed OAuth callback handler to prevent crashes when processing certain request types, improving authentication reliability.
  • Tests

    • Added integration tests for OAuth callback handling to ensure robustness across different scenarios.

Copilot AI review requested due to automatic review settings April 23, 2026 14:54
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3c317075-5fa3-4983-a52f-243c8286701a

📥 Commits

Reviewing files that changed from the base of the PR and between bcfe797 and b728afe.

📒 Files selected for processing (2)
  • modules/auth/controllers/auth.controller.js
  • modules/auth/tests/auth.integration.tests.js

Walkthrough

This change addresses an Express 5 compatibility issue where OAuth GET callbacks crash because req.body is undefined. The fix applies optional chaining to safely access body properties and adds an integration test to prevent regression.

Changes

Cohort / File(s) Summary
OAuth Controller Fix
modules/auth/controllers/auth.controller.js
Added optional chaining (?.) when accessing req.body.strategy and req.body.key to safely handle undefined body in Express 5 GET requests.
Integration Test Addition
modules/auth/tests/auth.integration.tests.js
New test case for oauthCallback invoked on GET requests with undefined req.body, verifying token cookie creation and redirect behavior.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • #3268: Modifies the same oauthCallback handler with allowlist validation for req.body.key, potentially requiring coordination with this optional chaining change.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and specifically describes the primary fix: handling undefined req.body in OAuth callbacks on Express 5 using optional chaining.
Description check ✅ Passed The description covers the main problem, root cause, test plan, and related follow-ups. While it omits the detailed Scope, Risk level, and Guardrails sections from the template, the essential information is present and clear.
Linked Issues check ✅ Passed The PR successfully addresses the core coding requirements from #3492: using optional chaining for req.body access and adding a GET callback integration test to prevent regression.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue #3492: optional chaining in oauthCallback and a new integration test covering GET callbacks. No unrelated changes detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix/oauth-callback-req-body-3492

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 and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 23, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.99%. Comparing base (bcfe797) to head (b728afe).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #3496   +/-   ##
=======================================
  Coverage   85.99%   85.99%           
=======================================
  Files         116      116           
  Lines        2957     2957           
  Branches      829      829           
=======================================
  Hits         2543     2543           
  Misses        328      328           
  Partials       86       86           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes an Express 5 regression where req.body can be undefined on GET OAuth callbacks, causing the classic web OAuth callback handler to crash before invoking Passport.

Changes:

  • Guard req.body access in oauthCallback with optional chaining to avoid crashes on GET callbacks.
  • Add a regression test that calls oauthCallback with no req.body (Express 5 GET-style request).

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
modules/auth/controllers/auth.controller.js Prevents crash by optional-chaining req.body access in the client-side OAuth branch check.
modules/auth/tests/auth.integration.tests.js Adds a test covering the Express 5 GET callback scenario where req.body is missing.

Comment on lines +630 to +646
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(null, { id: 'mock-get-cb-user' }),
);
const cookies = {};
const redirectCalls = [];
const mockReq = { params: { strategy: 'google' } };
const mockRes = {
cookie(name, val, opts) { cookies[name] = { val, opts }; return this; },
redirect(code, url) { redirectCalls.push({ code, url }); },
};

await AuthController.oauthCallback(mockReq, mockRes, () => {});

expect(cookies.TOKEN).toBeDefined();
expect(redirectCalls[0]).toMatchObject({ code: 302 });
authenticateSpy.mockRestore();
});
await AuthController.oauthCallback(mockReq, mockRes, () => {});

expect(cookies.TOKEN).toBeDefined();
expect(redirectCalls[0]).toMatchObject({ code: 302 });
@codacy-production
Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity · 2 duplication

Metric Results
Complexity 0
Duplication 2

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes.

Copy link
Copy Markdown

@codacy-production codacy-production Bot left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

The PR successfully addresses the crash in the OAuth callback handler encountered with Express 5 by ensuring req.body is handled safely via optional chaining. All acceptance criteria, including the addition of integration tests for both the new edge case and existing manual strategy logic, have been met.

Codacy reports that the changes are up to standards. No security flaws or major logic bugs were identified. The only finding is a minor suggestion regarding code duplication in the newly added tests to improve long-term maintainability.

Test suggestions

  • OAuth callback handling with undefined req.body (Express 5 GET flow)
  • OAuth callback with valid req.body for manual strategy verification

🗒️ Improve review quality by adding custom instructions

);
const cookies = {};
const redirectCalls = [];
const mockReq = { params: { strategy: 'google' } };
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ LOW RISK

Nitpick: This test boilerplate for mocking the response object and tracking redirects is duplicated from lines 613-622. Extracting this into a shared helper function would simplify the test suite.

Try running the following prompt in your IDE agent:

Refactor the integration tests in modules/auth/tests/auth.integration.tests.js by creating a setupMockAuthResponse helper function that returns the cookies, redirectCalls, and mockRes object. Then, update the tests at lines 613 and 635 to use this helper.

@PierreBrisorgueil PierreBrisorgueil merged commit 35f28ff into master Apr 23, 2026
10 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the fix/oauth-callback-req-body-3492 branch April 23, 2026 18:29
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.

fix(auth): OAuth GET callback crashes on Express 5 (req.body undefined)

2 participants