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: Nil pointer dereference with Must Bind binding #3171

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

ItsMeSamey
Copy link

if err is nil err.Error() panics
(eg. c.Bind().Must().JSON(...) successfully binds but panics

if err is nil err.Error() panics
(eg. c.Bind().Must().JSON(...) successfully binds but panics
@ItsMeSamey ItsMeSamey requested a review from a team as a code owner October 17, 2024 20:55
@ItsMeSamey ItsMeSamey requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team October 17, 2024 20:55
Copy link

welcome bot commented Oct 17, 2024

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes in this pull request involve modifications to the Bind struct in the fiber package by removing the should field and associated methods. Error handling is now directly integrated into various binding methods, simplifying the logic. The Test_Bind_Must function has been removed from bind_test.go, eliminating direct validation for the Must method. Additionally, the DefaultCtx struct in ctx.go has been updated to initialize the bind field differently and to enhance the context management methods.

Changes

File Change Summary
bind.go Removed should field and methods (Should, Must, returnErr). Simplified error handling in binding methods.
bind_test.go Removed Test_Bind_Must function, which validated the Must method's behavior.
ctx.go Updated Bind, Reset, and release methods in DefaultCtx for improved context management.

Possibly related PRs

Suggested reviewers

  • sixcolors
  • gaby
  • efectn
  • ReneWerner87

Poem

In the meadow where bunnies play,
A tweak was made to save the day.
With errors checked, oh what a sight,
Binding's clearer, everything's right!
Hops of joy, we leap and cheer,
For better code is finally here! 🐇✨


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

@ItsMeSamey ItsMeSamey changed the title Fix nil pointer dereference with Must Bind binding error Fix nil pointer dereference with Must Bind binding Oct 17, 2024
@gaby
Copy link
Member

gaby commented Oct 18, 2024

@ItsMeSamey Anyway we could trigger this in a new unit-test?

@gaby gaby changed the title Fix nil pointer dereference with Must Bind binding 🐛 fix: Nil pointer dereference with Must Bind binding Oct 18, 2024
Copy link

codecov bot commented Oct 18, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.16%. Comparing base (298975a) to head (b15eda0).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3171      +/-   ##
==========================================
- Coverage   82.36%   82.16%   -0.21%     
==========================================
  Files         113      113              
  Lines        8474    11012    +2538     
==========================================
+ Hits         6980     9048    +2068     
- Misses       1089     1561     +472     
+ Partials      405      403       -2     
Flag Coverage Δ
unittests 82.16% <100.00%> (-0.21%) ⬇️

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.

make sure returnErr works with nil error
as in majority of cases we expect err to be nil, this should provide better short-cutting
@ItsMeSamey
Copy link
Author

@gaby I've added a test for this

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

🧹 Outside diff range and nitpick comments (1)
bind_test.go (1)

22-29: Approve the new test function with a suggestion.

The new Test_returnErr function is a good addition to test the fix for the nil pointer dereference issue. It correctly checks that no error is returned when a nil error is passed to returnErr.

To make the test more robust, consider adding an additional assertion to check the response status code:

 err := c.Bind().Must().returnErr(nil)
 require.Equal(t, nil, err)
+require.Equal(t, 200, c.Response().StatusCode())

This will ensure that not only is no error returned, but also that the response status remains unchanged when a nil error is passed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0fa70ab and dde670f.

📒 Files selected for processing (2)
  • bind.go (1 hunks)
  • bind_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
bind_test.go (1)

Line range hint 1-1183: Overall approval of the test file.

The bind_test.go file appears to be well-structured and comprehensive, covering various binding scenarios including Query, Header, Body, URI, and Cookie bindings. The addition of the Test_returnErr function complements the existing test suite by addressing the specific issue mentioned in the PR.

The file also includes benchmark functions, which are valuable for monitoring performance. No significant issues or necessary improvements are identified in the rest of the file.

bind.go (1)

44-45: Properly handling nil errors to prevent nil pointer dereference

The updated condition if err == nil || b.should ensures that the function returns early when err is nil or b.should is true, preventing a nil pointer dereference when calling err.Error() later in the code. This change effectively fixes the panic issue described in the pull request.

bind.go Show resolved Hide resolved
bind.go Show resolved Hide resolved
@ItsMeSamey ItsMeSamey requested a review from gaby October 19, 2024 23:42
@ItsMeSamey
Copy link
Author

@gaby
I've been wondering why is Must() even needed, it only adds overhead so won't we be better off removing it altogether. Setting status should be user's job anyway
Should i open a discussion / issue about this?

@gaby
Copy link
Member

gaby commented Oct 21, 2024

@gaby I've been wondering why is Must() even needed, it only adds overhead so won't we be better off removing it altogether. Setting status should be user's job anyway Should i open a discussion / issue about this?

That's a question for @efectn

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

🧹 Outside diff range and nitpick comments (1)
bind.go (1)

43-43: Update documentation for Custom binding

The comment "NOTE: Should/Must is still valid for Custom binders" above the Custom method is now outdated since Should/Must methods have been removed.

Remove or update the comment to reflect the new error handling approach.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b15eda0 and dde4c81.

📒 Files selected for processing (3)
  • bind.go (11 hunks)
  • bind_test.go (0 hunks)
  • ctx.go (0 hunks)
💤 Files with no reviewable changes (2)
  • bind_test.go
  • ctx.go
🧰 Additional context used
🔇 Additional comments (3)
bind.go (3)

52-52: LGTM: Consistent error handling pattern across all binding methods

The binding methods now follow a consistent and clean pattern:

  1. Call the appropriate binder
  2. Return any binding errors directly
  3. Validate the struct if binding succeeds

This simplification makes the error handling more predictable and allows users to handle status codes according to their needs.

Also applies to: 61-61, 71-71, 80-80, 89-89, 98-98, 107-107, 116-116, 125-125


147-147: LGTM: Clean error handling in Body binding

The Body binding method maintains a clean separation of concerns while consistently handling errors from custom binders. The direct error return aligns with the new error handling pattern.


22-22: Breaking Change: Removal of Must/Should chaining capability

The removal of the should field from the Bind struct is a breaking change that will affect existing code using the Must()/Should() chaining pattern. This change is necessary to fix the nil pointer dereference issue, but requires careful migration planning.

Consider documenting the migration path for users in the changelog, suggesting alternative error handling patterns such as:

if err := c.Bind().JSON(&data); err != nil {
    return err
}

@ReneWerner87
Copy link
Member

we will discuss this again internally and then let you know which way we want to go, thank you for your work and help

@ReneWerner87
Copy link
Member

here the last statement
#3178 (comment)

we want to rename the feature so that there is no confusion with the golang concept of MUST for panics

because the methods always return an error
the feature only ensures that the response is filled with it

@ReneWerner87
Copy link
Member

give us a little time, we are currently discussing what this could look like
whether a config or the method should be renamed and where this can be found

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants