Skip to content

fix: HTTP status code 3XX redirection for Parse Server URL not handled properly #2608

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 9, 2025

Conversation

dplewis
Copy link
Member

@dplewis dplewis commented May 8, 2025

Pull Request

Issue

The SDK doesn't support 3XX redirection status codes

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_redirection

Closes: #1945

Approach

  • Resend request when new redirection url
  • Handle redirection loops

Tasks

  • Add tests
  • Add changes to documentation (guides, repository pages, code comments)

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added support for manual handling of HTTP redirects in network requests, ensuring correct processing of redirects during server communication.
  • Bug Fixes

    • Improved reliability when interacting with servers or proxies that return HTTP redirects.
  • Tests

    • Introduced new test cases to verify correct handling of HTTP redirects in both general and batch request scenarios.
    • Added test to confirm redirect forwarding works correctly with object saving and querying.

Copy link

parse-github-assistant bot commented May 8, 2025

🚀 Thanks for opening this pull request!

Copy link

coderabbitai bot commented May 8, 2025

📝 Walkthrough

"""

Walkthrough

Manual HTTP redirect handling was introduced to the RESTController, ensuring requests explicitly follow redirects rather than relying on the default fetch behavior. New tests were added to verify correct redirect handling in both the RESTController and the ParseServer integration, particularly for batch requests and reverse proxy scenarios. No changes were made to public API signatures.

Changes

File(s) Change Summary
src/RESTController.ts Added getPath helper; modified ajax and request methods to implement manual HTTP redirect handling.
src/tests/RESTController-test.js Added tests verifying redirect handling for batch requests with custom SERVER_URL and multiple consecutive redirects.
integration/test/ParseServerTest.js Added integration test to verify end-to-end redirect handling in ParseServer with a local redirecting HTTP server.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RESTController
    participant Server
    participant RedirectedServer

    Client->>RESTController: request(method, path, data, options)
    RESTController->>Server: fetch (original URL)
    Server-->>RESTController: HTTP 301/302/303/307 with Location header
    RESTController->>RedirectedServer: fetch (redirect Location URL, possibly with method change)
    RedirectedServer-->>RESTController: HTTP 200 (success)
    RESTController-->>Client: Response (final result)
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure Parse.Object.saveAll() and batch requests work correctly with reverse proxy and handle redirects (#1945)
"""

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8095828 and 147973e.

📒 Files selected for processing (1)
  • src/__tests__/RESTController-test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/tests/RESTController-test.js
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (Node 22, 22.4.1)
  • GitHub Check: build (Node 20, 20.15.1)
  • GitHub Check: build (Node 18, 18.20.4)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented May 8, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (fc416dc) to head (147973e).
Report is 1 commits behind head on alpha.

Additional details and impacted files
@@            Coverage Diff            @@
##             alpha     #2608   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           63        63           
  Lines         6174      6193   +19     
  Branches      1465      1472    +7     
=========================================
+ Hits          6174      6193   +19     

☔ 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.

@dplewis dplewis requested a review from a team May 8, 2025 01:27
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/__tests__/RESTController-test.js (1)

437-472: Great addition – covers custom base URL + redirect path

The test simulates a reverse-proxy scenario accurately and ensures both the
initial and redirected URLs are hit in the correct order. Consider adding one
more case for a 308 response so that behaviour stays correct when you extend
support in the controller.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc416dc and eaddb1b.

📒 Files selected for processing (3)
  • integration/test/ParseServerTest.js (2 hunks)
  • src/RESTController.ts (5 hunks)
  • src/__tests__/RESTController-test.js (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/RESTController.ts (2)
src/__tests__/RESTController-test.js (3)
  • CoreManager (7-7)
  • RESTController (8-8)
  • headers (29-33)
src/CoreManager.ts (1)
  • RESTController (135-145)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (Node 22, 22.4.1)
  • GitHub Check: build (Node 18, 18.20.4)
  • GitHub Check: build (Node 20, 20.15.1)
🔇 Additional comments (2)
src/RESTController.ts (2)

150-151: redirect: 'manual' is not universally supported – please verify runtimes

Node 18’s built-in fetch currently throws TypeError: redirect option ‘manual’ not supported
and some older browsers ignore it. If any officially-supported environment still
lacks this capability we will break networking completely.

Please confirm support matrix or polyfill it; otherwise fall back to the
default behaviour when 'manual' is rejected.


235-236: Nice abstraction

Replacing string concatenation with getPath() centralises the URL-building logic and makes future fixes easier. 👍

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
src/RESTController.ts (2)

57-62: Fix potential double-slash issue in URL construction

The getPath function can introduce a double-slash when path already starts with a leading slash, which can cause issues with some reverse proxies.

-function getPath(url: string, path: string) {
-  if (url[url.length - 1] !== '/') {
-    url += '/';
-  }
-  return url + path;
+function getPath(base: string, pathname: string) {
+  if (base.endsWith('/')) {
+    base = base.slice(0, -1);
+  }
+  if (!pathname.startsWith('/')) {
+    pathname = '/' + pathname;
+  }
+  return base + pathname;
}

316-327: 🛠️ Refactor suggestion

Limited redirect handling should support multiple hops

The current implementation only follows a single redirect. If the second request also returns a redirect, it won't be followed, which can lead to incomplete request handling in multi-hop redirect scenarios.

 return RESTController.ajax(method, url, payloadString, {}, options).then(async (result) => {
-  if (result.location) {
-    const newURL = getPath(result.location, path);
-    result = await RESTController.ajax(result.method, newURL, result.body, {}, options);
+  // Follow redirects (up to 5 hops to prevent infinite loops)
+  let redirectCount = 0;
+  const MAX_REDIRECTS = 5;
+  
+  while (result.location && redirectCount < MAX_REDIRECTS) {
+    redirectCount++;
+    const newURL = getPath(result.location, path);
+    result = await RESTController.ajax(result.method, newURL, result.body, {}, options);
   }
+  
+  // Warn if we hit the redirect limit
+  if (redirectCount === MAX_REDIRECTS && result.location) {
+    console.warn('Maximum redirect limit reached, response might be incomplete');
+  }
+  
   const { response, status, headers } = result;
   if (options.returnStatus) {
     return { ...response, _status: status, _headers: headers };
   } else {
     return response;
   }
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eaddb1b and d5f86be.

📒 Files selected for processing (2)
  • integration/test/ParseServerTest.js (2 hunks)
  • src/RESTController.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • integration/test/ParseServerTest.js
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (Node 22, 22.4.1)
  • GitHub Check: build (Node 18, 18.20.4)
  • GitHub Check: build (Node 20, 20.15.1)
🔇 Additional comments (2)
src/RESTController.ts (2)

150-150: Good addition of manual redirect handling

Setting redirect: 'manual' in fetch options is necessary to prevent automatic redirect following, allowing the SDK to implement its own redirect handling logic.


200-207: Proper implementation of redirect status code handling

The implementation correctly handles all redirect status codes (301, 302, 303, 307, 308) and properly adjusts the method and body for 303 redirects as per HTTP standards.

@dplewis dplewis changed the title feat: Properly handle proxy redirection feat: Properly handle 3XX redirection May 8, 2025
@mtrezza mtrezza changed the title feat: Properly handle 3XX redirection fix: HTTP code 3XX redirection for Parse Server URL not handled properly May 9, 2025
@mtrezza mtrezza changed the title fix: HTTP code 3XX redirection for Parse Server URL not handled properly fix: HTTP status code 3XX redirection for Parse Server URL not handled properly May 9, 2025
@mtrezza
Copy link
Member

mtrezza commented May 9, 2025

Changed PR title to bug fix, does that look right?

@dplewis
Copy link
Member Author

dplewis commented May 9, 2025

Looks good!

@mtrezza mtrezza merged commit 58e7f58 into parse-community:alpha May 9, 2025
13 checks passed
@dplewis dplewis deleted the follow-redirect branch June 2, 2025 15:56
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.

The request in Parse.Object.saveAll() does not have a reverse proxy
2 participants