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

🐛 bug: fasthttp errors cause panic when Params is used #3055

Merged
merged 3 commits into from
Jul 5, 2024

Conversation

efectn
Copy link
Member

@efectn efectn commented Jun 30, 2024

Description

Fixes #2832

Type of change

  • Enhancement (improvement to existing features and functionality)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

@efectn efectn requested a review from a team as a code owner June 30, 2024 23:38
@efectn efectn requested review from gaby, sixcolors and ReneWerner87 and removed request for a team June 30, 2024 23:38
Copy link
Contributor

coderabbitai bot commented Jun 30, 2024

Walkthrough

The recent changes introduce a new method, Route(), in the DefaultCtx struct to retrieve route information more securely within the Params method. This refactoring aims to address issues surrounding parameter retrieval after body size limit errors. Additionally, a test function Test_Ctx_Params_ErrorHandler_Panic_Issue_2832 is added to verify error handling, focusing on scenarios with large request bodies that exceed limits.

Changes

Files Change Summary
ctx.go Introduced Route method in DefaultCtx to refactor parameter access in Params method.
ctx_test.go Added Test_Ctx_Params_ErrorHandler_Panic_Issue_2832 for testing error handling with large requests.

Assessment against linked issues

Objective (Issue #2832) Addressed Explanation
Fix issue where context.Route() returns nil after exceeding body limit
Ensure ctx.AllParams() does not panic and returns expected values even after body limit error

Poem

In fibers of code where routes do play,
A refactored path now holds sway,
Params retrieved without delay,
Even when bodies go astray.
Tests ensure no error stay,
In Fiber’s realm, we find our way.
🐇🎶


Tip

Early access features: enabled

We are currently testing the following features in early access:

  • OpenAI gpt-4o model for code reviews and chat: OpenAI claims that this model is better at understanding and generating code than the previous models. We seek your feedback over the next few weeks before making it generally available.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are currently opted into early access features by default.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@efectn efectn added this to the v3 milestone Jun 30, 2024
Copy link

codecov bot commented Jun 30, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.97%. Comparing base (6108475) to head (f935a9b).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3055      +/-   ##
==========================================
- Coverage   83.04%   82.97%   -0.08%     
==========================================
  Files         115      115              
  Lines        8315     8316       +1     
==========================================
- Hits         6905     6900       -5     
- Misses       1077     1081       +4     
- Partials      333      335       +2     
Flag Coverage Δ
unittests 82.97% <100.00%> (-0.08%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 49ba8df and 94ad7cf.

Files selected for processing (2)
  • ctx.go (1 hunks)
  • ctx_test.go (1 hunks)
Additional comments not posted (15)
ctx.go (2)

Line range hint 989-1006: Addition of Route() method to handle nil route scenarios

The new Route() method effectively addresses the issue where ctx.route could be nil, particularly after a body limit error, by safely returning a default Route object if c.route is nil. This change is crucial for preventing the panic described in the PR objectives and ensures that ctx.AllParams() and similar methods can operate safely without causing runtime panics.


Line range hint 988-1006: Refactoring of Params() to use new Route() method

The modification in the Params() method to utilize the newly added Route() method ensures that route parameter retrieval is safe, even when c.route might be nil. This change is crucial for the stability and reliability of the application, especially in error handling scenarios where ctx.route could be unset due to premature termination of request processing (like a body limit error).

ctx_test.go (13)

2369-2386: Review of Test_Ctx_Params_ErrorHandler_Panic_Issue_2832:

The test function Test_Ctx_Params_ErrorHandler_Panic_Issue_2832 is designed to simulate a scenario where a large request body triggers an error, and the error handler attempts to access route parameters. The setup involves configuring the application with a custom error handler and a body limit. The test then sends a request that exceeds this limit and checks if the error is handled as expected.

This test is crucial for ensuring that the application behaves correctly under error conditions and does not lead to unexpected crashes or behavior. It also helps to verify that the error handling mechanism is robust and can gracefully handle errors triggered by large request bodies.

Overall, the test appears to be well-structured and effectively tests the intended scenario. It is a valuable addition to the test suite as it helps to ensure the stability and reliability of the application under error conditions.


Line range hint 2388-2405: Review of Test_Ctx_Params_Case_Sensitive:

The function Test_Ctx_Params_Case_Sensitive checks the case sensitivity of parameter extraction from the context. It sets up routes with parameters in various cases and tests if the parameters are correctly retrieved in a case-sensitive manner.

This test is essential for ensuring that the framework handles URL parameters accurately, respecting the case sensitivity settings. Proper handling of case sensitivity in URL parameters can prevent bugs related to routing and parameter retrieval, which might lead to security issues or incorrect application behavior.

The test is well-implemented and covers the necessary aspects of case sensitivity in parameter handling. It is a good practice to have such tests to prevent regressions in future changes.


Line range hint 2406-2418: Review of Benchmark_Ctx_Params:

The benchmark Benchmark_Ctx_Params is designed to measure the performance of the Params method in the context object. It sets up a scenario where the context has predefined parameters, and it repeatedly retrieves these parameters to measure performance.

This benchmark is crucial for understanding the performance characteristics of parameter retrieval, which is a common operation in web applications. The setup appears correct, and the benchmark runs the parameter retrieval operation multiple times to get a reliable measurement.

It is good practice to include such benchmarks in the test suite as they help identify performance regressions and optimize critical parts of the framework.


Line range hint 2419-2428: Review of Test_Ctx_Path:

The function Test_Ctx_Path tests the Path method of the context object, which retrieves the current request path. The test checks if the method accurately returns the path for various requests, including those with special characters and URL encoding.

Testing the Path method is crucial because it impacts routing and middleware functionality. Ensuring that this method behaves correctly under different scenarios prevents bugs in route handling and improves the robustness of the application.

The test is well-structured and covers a range of scenarios, from simple paths to those involving special characters and URL encoding. This thorough testing is excellent for ensuring the reliability of the Path method.


Line range hint 2429-2437: Review of Test_Ctx_Protocol:

The function Test_Ctx_Protocol tests the Protocol method of the context object, which retrieves the HTTP protocol version used in the request. The test checks if the method correctly identifies HTTP/1.1 and HTTP/2 protocols based on the request headers.

Testing the protocol retrieval is important for applications that might behave differently based on the HTTP version, such as those using specific features available only in HTTP/2. Ensuring accurate protocol identification helps in correctly tailoring the response and functionalities to the capabilities of the client's HTTP version.

The test covers the necessary scenarios and is implemented correctly, providing assurance that the Protocol method functions as expected.


Line range hint 2438-2446: Review of Test_Ctx_Scheme:

The function Test_Ctx_Scheme tests the Scheme method of the context object, which determines the URL scheme (http or https) of the request. The test checks the method's ability to correctly identify the scheme based on various headers like X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl, and X-Url-Scheme.

Correctly identifying the URL scheme is crucial for security purposes, such as enforcing HTTPS on sensitive pages, and for functionality that depends on the nature of the connection (secure or not). It is also essential for generating correct absolute URLs in responses.

The test is comprehensive and covers multiple scenarios, ensuring that the Scheme method behaves reliably across different configurations and header setups. This thorough testing is critical for maintaining the security and functionality of web applications that rely on scheme-specific behavior.


Line range hint 2447-2455: Review of Benchmark_Ctx_Scheme:

The benchmark Benchmark_Ctx_Scheme measures the performance of the Scheme method in the context object under various scenarios, including different headers and configurations that affect scheme determination.

Performance benchmarking for this method is valuable because it is often called in web applications, especially those that enforce or react differently based on the request scheme. Knowing the performance characteristics helps in optimizing the method and ensuring that it does not become a bottleneck in request processing.

The benchmark is set up correctly, running multiple iterations and covering different scenarios to provide a comprehensive view of the method's performance. This approach helps in identifying potential performance issues and areas for optimization.


Line range hint 2456-2460: Review of Test_Ctx_Vary:

The function Test_Ctx_Vary tests the Vary method of the context object, which manipulates the Vary HTTP header. The test checks if the method correctly sets the Vary header based on the input headers provided.

Proper handling of the Vary header is crucial for correct content delivery and caching behavior, especially in environments with diverse client configurations and capabilities. The Vary header helps caches understand how to store and serve different versions of a resource.

The test is well-implemented, covering multiple scenarios and ensuring that the Vary method behaves as expected. This is important for maintaining the efficiency and correctness of HTTP caching mechanisms in web applications.


Line range hint 2461-2465: Review of Benchmark_Ctx_Vary:

The benchmark Benchmark_Ctx_Vary measures the performance of the Vary method in the context object. It tests the method's efficiency in setting the Vary HTTP header under repeated calls.

Performance benchmarking for this method is important because it is frequently used in responses that require specific caching behaviors based on the request headers. The setup of the benchmark is appropriate, and it runs multiple iterations to ensure reliable measurements.

This benchmark is useful for identifying potential performance bottlenecks in the Vary method and for ensuring that it performs efficiently in high-load scenarios.


Line range hint 2466-2474: Review of Test_Ctx_Set:

The function Test_Ctx_Set tests the Set method of the context object, which is used to set response headers. The test checks if the method correctly sets various headers and handles cases of overwriting existing headers.

Proper functionality of the Set method is crucial as it directly affects the HTTP response headers, which can influence caching, security, and content negotiation. The test covers multiple scenarios, including setting new headers and overwriting existing ones, which is important for verifying the method's behavior in real-world applications.

The test is well-structured and effectively ensures that the Set method behaves as expected, maintaining the integrity and correctness of response headers.


Line range hint 2475-2482: Review of Benchmark_Ctx_Set:

The benchmark Benchmark_Ctx_Set measures the performance of the Set method in the context object. It tests how efficiently the method can set response headers, which is a frequent operation in web applications.

Performance benchmarking for the Set method is critical because it is involved in every HTTP response, and its efficiency can impact the overall response time. The benchmark is set up correctly, testing the method under repeated calls to simulate a high-load scenario.

This benchmark is valuable for identifying potential optimizations in the Set method to enhance the performance of web applications.


Line range hint 2483-2490: Review of Test_Ctx_Status:

The function Test_Ctx_Status tests the Status method of the context object, which sets the HTTP status code for the response. The test checks if the method correctly sets various status codes and ensures that the response body and status are correctly aligned.

Accurately setting the status code is crucial as it informs the client about the outcome of their request, affecting client-side logic and user experience. The test effectively covers different scenarios, including normal and error status codes, which is essential for ensuring robust and predictable behavior in web applications.

The test is well-implemented, providing confidence that the Status method functions correctly across different use cases.


Line range hint 2499-2505: Review of Benchmark_Ctx_Type:

The benchmark Benchmark_Ctx_Type measures the performance of the Type method in the context object. It tests how efficiently the method can set the Content-Type header, which is a common operation in web applications, especially those serving various types of content.

Understanding the performance of the Type method is important because it can affect the response time, especially in content-heavy applications. The benchmark is set up correctly, running multiple iterations and covering different content types to ensure comprehensive performance data.

This benchmark is valuable for identifying potential optimizations in the Type method to enhance the performance and responsiveness of web applications.

@gaby gaby added the v3 label Jun 30, 2024
Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

LGTM

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 94ad7cf and 7d4a779.

Files selected for processing (2)
  • ctx.go (1 hunks)
  • ctx_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • ctx.go
  • ctx_test.go

@ReneWerner87 ReneWerner87 merged commit 4e5a501 into main Jul 5, 2024
15 of 16 checks passed
@efectn efectn deleted the ctx-fix-panic branch July 16, 2024 13:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: route (and Route()) property from fiber context returning nil when called after body limit error
3 participants