Skip to content
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

fix: avoid redos on host and protocol getter #17

Merged
merged 1 commit into from
Feb 12, 2025
Merged

fix: avoid redos on host and protocol getter #17

merged 1 commit into from
Feb 12, 2025

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Feb 12, 2025

GHSA-593f-38f6-jp5m

pick from koajs@5f294bb

Summary by CodeRabbit

  • Bug Fixes

    • Improved processing of header values by trimming extraneous spaces, ensuring accurate extraction of host, protocol, and IP information.
    • Enhanced HTML content detection in responses to assign the correct content type even when additional whitespace is present.
  • Refactor

    • Streamlined the handling of comma-separated header values for consistency across request and response processing.

Copy link

coderabbitai bot commented Feb 12, 2025

Walkthrough

This pull request updates the header-processing logic in the Request classes and the body-handling logic in the Response class. A new function, splitCommaSeparatedValues, has been introduced to centralize and standardize the splitting and trimming of comma-separated strings. The host, protocol, and ips getters in Request now use this utility for cleaner and more consistent output. In Response, the regex in the body setter was refined to better detect HTML content with preceding whitespace. New test cases have been added to verify these behaviors.

Changes

File(s) Change Summary
example/extend/Request.ts, src/request.ts Modified Request processing: updated CustomRequest's host getter to trim whitespace; introduced splitCommaSeparatedValues and used it in host, protocol, and ips getters.
src/response.ts, test/response/body.test.ts Adjusted Response body setter: updated regex to account for leading whitespace before < and revised the corresponding test to use an extensive whitespace string before HTML content.
test/request/host.test.ts, test/request/ips.test.ts Added test cases to validate fallback to the host header when x-forwarded-host is invalid and to ensure correct extraction of IPs from malformed, comma-separated headers.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant R as Request Object
    participant U as splitCommaSeparatedValues()
    
    C->>R: Send request with headers (host, X-Forwarded-Proto, X-Forwarded-For)
    R->>U: Call U with raw header value
    U-->>R: Return trimmed value(s)
    R-->>C: Return processed header value
Loading
sequenceDiagram
    participant T as Test/Client
    participant Res as Response Object
    
    T->>Res: Set body with extensive leading whitespace + HTML
    Res->>Res: Apply regex /^\s*</ to detect HTML marker
    Res-->>T: Set content type to "html" if condition met
Loading

Possibly related PRs

Poem

I'm a happy rabbit hopping through the code,
Trimming spaces and headers in a tidy mode.
Utility functions lead the way so neat,
While tests and regex ensure each case is complete.
With whiskers twitching in digital delight,
I celebrate these changes from morning to night! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.

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 docstrings to generate docstrings for this PR. (Beta)
  • @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

pkg-pr-new bot commented Feb 12, 2025

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/koa/@eggjs/koa@17

commit: d0a4fb2

Copy link

codecov bot commented Feb 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.45%. Comparing base (f4315d9) to head (d0a4fb2).
Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #17      +/-   ##
==========================================
+ Coverage   98.44%   98.45%   +0.01%     
==========================================
  Files           6        6              
  Lines        1924     1939      +15     
  Branches      366      368       +2     
==========================================
+ Hits         1894     1909      +15     
  Misses         30       30              

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

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: 0

🧹 Nitpick comments (2)
example/extend/Request.ts (1)

20-20: Consider using the new utility function.

While the current implementation is secure, consider using the splitCommaSeparatedValues utility function for consistency with the main Request class.

-    this[HOST] = rawHost.split(/,/)[0].trim();
+    this[HOST] = splitCommaSeparatedValues(rawHost, 1)[0];
test/response/body.test.ts (1)

82-82: Consider reducing the whitespace length in the test.

While stress testing is important, using 10 million spaces might significantly impact test execution time and memory usage. Consider using a smaller but still significant number (e.g., 10,000 spaces) that would still effectively test the functionality without excessive resource consumption.

-        res.body = ' '.repeat(10000000) + '\t\r\n<h1>Tobi</h1>';
+        res.body = ' '.repeat(10000) + '\t\r\n<h1>Tobi</h1>';
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f97184e and d0a4fb2.

📒 Files selected for processing (6)
  • example/extend/Request.ts (1 hunks)
  • src/request.ts (5 hunks)
  • src/response.ts (1 hunks)
  • test/request/host.test.ts (1 hunks)
  • test/request/ips.test.ts (1 hunks)
  • test/response/body.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Node.js / Test (windows-latest, 23)
  • GitHub Check: Node.js / Test (windows-latest, 22)
  • GitHub Check: Node.js / Test (windows-latest, 20)
  • GitHub Check: Node.js / Test (windows-latest, 18.19.0)
  • GitHub Check: Node.js / Test (windows-latest, 18)
  • GitHub Check: Node.js / Test (macos-latest, 23)
🔇 Additional comments (9)
src/request.ts (4)

215-217: LGTM! Improved host header processing.

The changes properly handle malformed input by using the new utility function, which safely processes and sanitizes the header value.


347-351: LGTM! Enhanced protocol header security.

The changes improve the handling of X-Forwarded-Proto header by using the new utility function, ensuring consistent and secure processing.


374-376: LGTM! Improved IP address processing.

The changes enhance the handling of X-Forwarded-For header by using the new utility function, ensuring consistent processing across all proxy-related headers.


647-649: LGTM! Well-designed utility function.

The new splitCommaSeparatedValues function effectively centralizes the comma-separated value processing logic, improving code maintainability and security.

test/request/host.test.ts (1)

93-119: LGTM! Comprehensive test coverage for invalid headers.

The new test cases effectively verify the security improvements by testing:

  1. Invalid x-forwarded-host handling
  2. Proper fallback behavior
  3. Both HTTP/1 and HTTP/2 scenarios
test/request/ips.test.ts (2)

24-25: LGTM! Good test for malformed X-Forwarded-For header.

The test properly verifies that the code handles malformed headers with extra commas and spaces correctly.


28-33: LGTM! Important security test case.

The test ensures that completely invalid IP addresses (only commas and spaces) result in an empty array, preventing potential security issues.

src/response.ts (2)

128-128: Great optimization for HTML detection!

The non-greedy quantifier ? in the regex pattern ^\s*?< helps prevent potential ReDoS issues by efficiently handling leading whitespace. This is a good security improvement.


128-128: Consider adding more robust HTML validation.

While the current regex efficiently handles leading whitespace, it might incorrectly identify some strings as HTML. Consider using a more comprehensive check or adding a comment explaining the trade-off between performance and accuracy.

Let's check if there are any existing HTML validation utilities in the codebase:

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Search for HTML validation related code
rg -i "html.*valid|valid.*html" --type ts

Length of output: 43


Additional HTML Validation Recommended

The current regex in src/response.ts only checks for leading whitespace before a < to classify content as HTML. Our search did not reveal any alternative or more robust HTML validation utilities elsewhere in the codebase. To prevent potential misclassification, consider either improving the validation logic (e.g., verifying closing tags or using a parser) or adding a comment to highlight the trade-offs between performance and accuracy.

@fengmk2 fengmk2 merged commit cd6b487 into master Feb 12, 2025
24 checks passed
@fengmk2 fengmk2 deleted the redos branch February 12, 2025 03:04
fengmk2 pushed a commit that referenced this pull request Feb 12, 2025
[skip ci]

## [2.20.7](v2.20.6...v2.20.7) (2025-02-12)

### Bug Fixes

* avoid redos on host and protocol getter ([#17](#17)) ([cd6b487](cd6b487))
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.

1 participant