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(httpclientpool): rebuild malformed Location URL #5902

Merged

Conversation

dwisiswant0
Copy link
Member

@dwisiswant0 dwisiswant0 commented Dec 11, 2024

Proposed changes

Fix #5900

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • New Features

    • Introduced a function to check if URLs are properly encoded.
    • Added a new error variable for handling URL reconstruction failures.
  • Bug Fixes

    • Enhanced logic for managing redirects and rebuilding request URLs.

@auto-assign auto-assign bot requested a review from dogancanbakir December 11, 2024 15:22
Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes in this pull request enhance the httpclientpool package by introducing new functionalities and modifying existing methods. Key modifications include the addition of a new function to check if a URL is already URL-encoded and updates to the checkMaxRedirects function to handle request URLs more effectively. Additionally, a new error variable for URL reconstruction failures has been introduced, improving error handling related to URL processing.

Changes

File Path Change Summary
pkg/protocols/http/httpclientpool/clientpool.go - Updated checkMaxRedirects function signature to include req *http.Request.
- Added isURLEncoded function to check if a URL is encoded.
- Added import for github.com/projectdiscovery/utils/url.
pkg/protocols/http/httpclientpool/errors.go - Introduced new error variable ErrRebuildURL for URL reconstruction failures.

Assessment against linked issues

Objective Addressed Explanation
Ensure spaces in Location headers are URL-encoded (Issue #5900)

🐰 In a world of code, I hop with glee,
New functions and fixes, oh what a spree!
URLs now encoded, no more 400s to see,
With error handling bright, we code merrily!
Hopping through changes, with joy we decree,
A smoother experience, for you and for me! 🐇✨

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 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 b4fe1df and 0c11347.

📒 Files selected for processing (1)
  • pkg/protocols/http/httpclientpool/clientpool.go (4 hunks)
🔇 Additional comments (3)
pkg/protocols/http/httpclientpool/clientpool.go (3)

29-29: LGTM!

The addition of the urlutil package is appropriate for handling URL parsing and encoding operations.


394-402: 🛠️ Refactor suggestion

Enhance URL rebuild logic and error handling

The current implementation has several areas for improvement:

  1. Error messages should include the original URL for better debugging
  2. The rebuilt URL should preserve the original request's query parameters
  3. Basic URL validation should be performed after rebuilding

Consider this enhanced implementation:

 // NOTE(dwisiswant0): rebuild request URL. See #5900.
 if u := req.URL.String(); !isURLEncoded(u) {
     parsed, err := urlutil.Parse(u)
     if err != nil {
-        return fmt.Errorf("%w: %w", ErrRebuildURL, err)
+        return fmt.Errorf("failed to rebuild URL %q: %w", u, err)
     }
+    
+    // Preserve original query parameters
+    if req.URL.RawQuery != "" {
+        parsed.URL.RawQuery = req.URL.RawQuery
+    }
+    
+    // Validate the rebuilt URL
+    if parsed.URL.Scheme == "" || parsed.URL.Host == "" {
+        return fmt.Errorf("invalid URL after rebuild: missing scheme or host")
+    }
 
     req.URL = parsed.URL
 }

Likely invalid or redundant comment.


407-418: 🛠️ Refactor suggestion

Improve URL encoding detection and consider package move

The current implementation has limitations with partially encoded URLs and edge cases. Also, as noted in the comment, this utility function should be moved to projectdiscovery/utils/urlutil.

Consider this enhanced implementation:

-// isURLEncoded is an helper function to check if the URL is already encoded
-//
-// NOTE(dwisiswant0): shall we move this under `projectdiscovery/utils/urlutil`?
-func isURLEncoded(s string) bool {
-    decoded, err := url.QueryUnescape(s)
-    if err != nil {
-        // If decoding fails, it may indicate a malformed URL/invalid encoding.
-        return false
-    }
-
-    return decoded != s
+// isURLFullyEncoded checks if a URL string is properly encoded
+// It handles partial encoding and common edge cases
+func isURLFullyEncoded(s string) bool {
+    // Quick check for common encoded characters
+    if !strings.Contains(s, "%") {
+        return false
+    }
+
+    decoded, err := url.QueryUnescape(s)
+    if err != nil {
+        return false
+    }
+
+    // Check if re-encoding produces the same string
+    reEncoded := url.QueryEscape(decoded)
+    return s == reEncoded
}

Consider:

  1. Moving this function to projectdiscovery/utils/urlutil package
  2. Renaming to isURLFullyEncoded for clarity
  3. Adding unit tests to cover edge cases

Let's verify if there are any existing URL encoding utilities in the codebase:


🪧 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
Contributor

@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: 2

🧹 Outside diff range and nitpick comments (1)
pkg/protocols/http/httpclientpool/clientpool.go (1)

394-402: Consider additional validation and error handling

While the URL reconstruction logic addresses the core issue, consider these improvements:

  1. Validate that parsed.URL is not nil before assignment
  2. Consider preserving the original query parameters if present
  3. Add debug logging for URL reconstruction attempts
 if u := req.URL.String(); !isURLEncoded(u) {
     parsed, err := urlutil.Parse(u)
     if err != nil {
         return fmt.Errorf("%w: %w", ErrRebuildURL, err)
     }
+    if parsed.URL == nil {
+        return fmt.Errorf("%w: nil URL after parsing", ErrRebuildURL)
+    }
+    // Preserve original query parameters if any
+    if req.URL.RawQuery != "" && parsed.URL.RawQuery == "" {
+        parsed.URL.RawQuery = req.URL.RawQuery
+    }
     req.URL = parsed.URL
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c731126 and 2926a98.

📒 Files selected for processing (2)
  • pkg/protocols/http/httpclientpool/clientpool.go (4 hunks)
  • pkg/protocols/http/httpclientpool/errors.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • pkg/protocols/http/httpclientpool/errors.go
🔇 Additional comments (1)
pkg/protocols/http/httpclientpool/clientpool.go (1)

394-402: Verify the fix with various URL patterns

While the implementation addresses the core issue of encoding spaces in URLs, let's verify it handles various URL patterns correctly.

✅ Verification successful

Based on the code analysis, I can now provide a final response:

Implementation correctly handles URL encoding

The implementation in isURLEncoded and the URL rebuilding logic is sound and properly handles URL encoding:

  1. isURLEncoded function correctly detects if a URL is already encoded by attempting to decode it and comparing with original
  2. The URL rebuilding logic properly handles malformed URLs by:
    • Checking if URL needs encoding
    • Using urlutil.Parse to properly parse and rebuild the URL
    • Returning appropriate errors if parsing fails

The implementation aligns with the fix's objectives and handles various URL patterns safely.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for test cases and URL handling patterns in the codebase

# Look for existing URL handling test cases
echo "Searching for URL-related test cases..."
rg -g "**/*_test.go" "func Test.*URL" -A 5

# Look for other URL encoding/decoding patterns
echo "Searching for URL encoding patterns..."
ast-grep --pattern 'url.QueryEscape($_)'

# Look for redirect-related test cases
echo "Searching for redirect test cases..."
rg -g "**/*_test.go" "Location.*header" -A 5

Length of output: 2585


Script:

#!/bin/bash
# Let's check for URL encoding and redirection test cases more specifically

# Look for URL encoding/decoding tests and implementations
echo "Searching for URL encoding/decoding tests..."
rg -g "**/*_test.go" "isURLEncoded|urlutil.Parse" -A 5

# Check the implementation of isURLEncoded function
echo "Checking isURLEncoded implementation..."
rg "func isURLEncoded" -A 10

# Look for URL-related test cases in the clientpool package
echo "Searching for clientpool URL tests..."
rg -g "pkg/protocols/http/httpclientpool/*_test.go" "func Test" -A 5

# Check for URL handling in redirect scenarios
echo "Checking redirect handling..."
rg "Location.*=|Location.*:" -A 5

Length of output: 72085


Script:

#!/bin/bash
# Let's check the implementation and test coverage more specifically

# Check the implementation of isURLEncoded and related functions
echo "Checking URL encoding implementation..."
rg "isURLEncoded|urlutil.Parse" -A 10

# Look for URL-related test cases in the httpclientpool package
echo "Searching for URL-related tests in httpclientpool..."
fd -g "*_test.go" pkg/protocols/http/httpclientpool/ --exec cat {}

# Check for URL encoding/decoding in urlutil package
echo "Checking urlutil package implementation..."
fd -g "*.go" pkg/protocols/utils/urlutil/ --exec cat {}

Length of output: 43221

@dwisiswant0 dwisiswant0 marked this pull request as draft December 11, 2024 15:51
@dwisiswant0 dwisiswant0 force-pushed the dwisiswant0/fix/httpclientpool/rebuild-malformed-location-URL branch from 2926a98 to 650bd67 Compare December 12, 2024 04:36
@dwisiswant0 dwisiswant0 force-pushed the dwisiswant0/fix/httpclientpool/rebuild-malformed-location-URL branch from 650bd67 to b4fe1df Compare December 12, 2024 04:39
@dwisiswant0 dwisiswant0 marked this pull request as ready for review December 12, 2024 14:01
Copy link
Contributor

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2926a98 and b4fe1df.

📒 Files selected for processing (2)
  • pkg/protocols/http/httpclientpool/clientpool.go (4 hunks)
  • pkg/protocols/http/httpclientpool/errors.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/protocols/http/httpclientpool/errors.go
🔇 Additional comments (3)
pkg/protocols/http/httpclientpool/clientpool.go (3)

29-29: LGTM: Import addition is appropriate

The addition of the urlutil package is well-aligned with the PR's objective of improving URL handling.


407-418: Consider enhancing URL encoding detection

The current implementation has limitations with partially encoded URLs and edge cases. Also, as noted in the comment, this utility function could be moved to projectdiscovery/utils/urlutil.


Line range hint 382-403: Verify the fix handles spaces in URLs correctly

Let's ensure the changes properly handle the URL encoding issue described in #5900.

✅ Verification successful

Based on the code analysis, I can now provide a final response:

The URL encoding fix is properly implemented and handles spaces correctly

The implementation is sound because:

  1. The isURLEncoded function correctly detects if a URL is already encoded by comparing the decoded and original strings
  2. The fix rebuilds the URL only when necessary (when not already encoded)
  3. The implementation uses the standard Go URL parsing and encoding functions
  4. The error handling is comprehensive, returning ErrRebuildURL if URL parsing fails

The changes properly address issue #5900 by:

  1. Checking if URL needs encoding before proceeding
  2. Using urlutil.Parse to properly handle URL encoding
  3. Only rebuilding the URL when necessary to avoid double-encoding
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for test cases and real-world usage of URL encoding in redirects

# Look for test cases covering URL encoding in redirects
echo "Searching for relevant test cases..."
rg -l "Location.*%20|Location.* " --type go

# Look for URL encoding related code
echo "Searching for URL encoding handling..."
ast-grep --pattern 'url.QueryEscape($$$)'

# Look for redirect handling code
echo "Searching for redirect handling..."
rg "CheckRedirect|Location:" --type go

Length of output: 1144


Script:

#!/bin/bash
# Let's examine the issue #5900 and related code more thoroughly

# First, let's look at the isURLEncoded function implementation
echo "Checking isURLEncoded implementation..."
rg -A 10 "func isURLEncoded" --type go

# Look for URL encoding related test cases
echo "Checking URL encoding test cases..."
fd ".*_test.go" --exec rg -l "isURLEncoded|checkMaxRedirects"

# Check the actual implementation in the test files
echo "Examining test implementations..."
fd ".*_test.go" --exec rg -A 10 "TestCheckMaxRedirects|TestIsURLEncoded"

# Look at the urlutil.Parse implementation
echo "Checking urlutil.Parse implementation..."
rg -A 10 "func Parse" pkg/protocols/common/urlutil/

Length of output: 1279


Script:

#!/bin/bash
# Let's check the urlutil package location and implementation

# Find urlutil package
echo "Finding urlutil package..."
fd -t f -e go urlutil

# Check the implementation of Parse function
echo "Looking for Parse function implementation..."
rg -A 10 "func Parse" --type go

# Check for any test cases related to URL encoding and spaces
echo "Looking for URL encoding and space-related tests..."
rg -A 5 "test.*url.*space|test.*space.*url" --type go -i

# Look for the actual issue #5900 to understand the context
echo "Looking for references to issue #5900..."
rg "#5900" --type go

Length of output: 5162


Script:

#!/bin/bash
# Let's find and examine the urlutil package and its Parse function

# Find all Go files containing urlutil
echo "Finding files with urlutil..."
fd -e go --exec rg -l "urlutil"

# Look for the actual urlutil package implementation
echo "Looking for urlutil package implementation..."
rg -A 5 "package urlutil" --type go

# Check for URL parsing related functions in the codebase
echo "Looking for URL parsing functions..."
rg -A 5 "func.*URL" --type go

# Look for any test cases that verify URL handling
echo "Looking for URL-related test cases..."
rg -A 5 "Test.*URL" --type go

Length of output: 29227

Comment on lines +394 to +402
// NOTE(dwisiswant0): rebuild request URL. See #5900.
if u := req.URL.String(); !isURLEncoded(u) {
parsed, err := urlutil.Parse(u)
if err != nil {
return fmt.Errorf("%w: %w", ErrRebuildURL, err)
}

req.URL = parsed.URL
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and URL validation

The URL rebuilding logic could be improved in several ways:

  1. Add context to the error message
  2. Validate the rebuilt URL
  3. Consider potential side effects of direct URL modification

Consider this enhanced implementation:

 // NOTE(dwisiswant0): rebuild request URL. See #5900.
 if u := req.URL.String(); !isURLEncoded(u) {
     parsed, err := urlutil.Parse(u)
     if err != nil {
-        return fmt.Errorf("%w: %w", ErrRebuildURL, err)
+        return fmt.Errorf("failed to rebuild URL %q: %w", u, ErrRebuildURL)
     }
+    
+    // Validate the rebuilt URL
+    if parsed.URL.Host == "" || parsed.URL.Scheme == "" {
+        return fmt.Errorf("invalid URL after rebuild %q: missing host or scheme", parsed.URL)
+    }
 
     req.URL = parsed.URL
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// NOTE(dwisiswant0): rebuild request URL. See #5900.
if u := req.URL.String(); !isURLEncoded(u) {
parsed, err := urlutil.Parse(u)
if err != nil {
return fmt.Errorf("%w: %w", ErrRebuildURL, err)
}
req.URL = parsed.URL
}
// NOTE(dwisiswant0): rebuild request URL. See #5900.
if u := req.URL.String(); !isURLEncoded(u) {
parsed, err := urlutil.Parse(u)
if err != nil {
return fmt.Errorf("failed to rebuild URL %q: %w", u, ErrRebuildURL)
}
// Validate the rebuilt URL
if parsed.URL.Host == "" || parsed.URL.Scheme == "" {
return fmt.Errorf("invalid URL after rebuild %q: missing host or scheme", parsed.URL)
}
req.URL = parsed.URL
}


// isURLEncoded is an helper function to check if the URL is already encoded
//
// NOTE(dwisiswant0): shall we move this under `projectdiscovery/utils/urlutil`?
Copy link
Member

Choose a reason for hiding this comment

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

++

@ehsandeep ehsandeep merged commit f21a82a into dev Dec 19, 2024
19 checks passed
@ehsandeep ehsandeep deleted the dwisiswant0/fix/httpclientpool/rebuild-malformed-location-URL branch December 19, 2024 15:01
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.

[BUG] Follow redirect doesn’t URL encode Location header whitespaces.
4 participants