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(🩹): error handling in CSRF token storage retrieval #3021

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

renanbastos93
Copy link
Member

Description

Resolved TODO for error handling to ensure code quality in retrieving CSRF token data from storage.

Fixes #3020

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

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

Resolved TODO for error handling to ensure code quality in
retrieving CSRF token data from storage.
@renanbastos93 renanbastos93 requested a review from a team as a code owner May 30, 2024 21:13
@renanbastos93 renanbastos93 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team May 30, 2024 21:13
@renanbastos93 renanbastos93 linked an issue May 30, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented May 30, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes enhance error handling in the CSRF middleware by introducing new error variables and updating function signatures to return errors. This involves modifications in csrf.go, session_manager.go, and storage_manager.go to improve robustness and provide more informative error responses.

Changes

Files Change Summary
middleware/csrf/csrf.go Added new error variables, updated error messages, modified error handling in New function, changed return type of getRawFromStorage.
middleware/csrf/session_manager.go Updated getRaw method in sessionManager to return a tuple of rawToken []byte and err error.
middleware/csrf/storage_manager.go Added error handling and updated return types for getRaw, setRaw, and delRaw methods in storageManager.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant Client
    participant Middleware
    participant Storage

    Client->>Middleware: Request with CSRF token
    Middleware->>Storage: getRaw(key)
    Storage-->>Middleware: raw, err
    alt err is not nil
        Middleware-->>Client: Error Response (ErrNotGetStorage)
    else
        Middleware->>Middleware: Validate Token
        alt Token Invalid
            Middleware-->>Client: Error Response (ErrTokenInvalid)
        else
            Middleware-->>Client: Success Response
        end
    end
Loading

Assessment against linked issues

Objective (Issue #3020) Addressed Explanation
Enhance error handling in session_manager.go and storage_manager.go
Refactor error handling logic to provide robust responses

Poem

In the land of code, where errors roam,
A rabbit hopped, to make it known,
With careful tweaks and thoughtful care,
Improved the CSRF, errors now rare.
Robust and strong, the middleware stands,
Thanks to the rabbit, with its nimble hands.
🌟🐇✨


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.

Copy link

codecov bot commented May 30, 2024

Codecov Report

Attention: Patch coverage is 61.76471% with 13 lines in your changes missing coverage. Please review.

Project coverage is 83.01%. Comparing base (4e5a501) to head (f301d39).

Files Patch % Lines
middleware/csrf/storage_manager.go 47.61% 11 Missing ⚠️
middleware/csrf/session_manager.go 75.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3021       /-   ##
==========================================
- Coverage   83.03%   83.01%   -0.02%     
==========================================
  Files         115      115              
  Lines        8323     8339       16     
==========================================
  Hits         6911     6923       12     
- Misses       1079     1087        8     
  Partials      333      329       -4     
Flag Coverage Δ
unittests 83.01% <61.76%> (-0.02%) ⬇️

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

Outside diff range and nitpick comments (2)
middleware/csrf/csrf.go (2)

Line range hint 225-225: Ensure to handle the error returned by storageManager.setRaw to prevent potential issues.

- storageManager.setRaw(token, dummyValue, cfg.Expiration)
  if err := storageManager.setRaw(token, dummyValue, cfg.Expiration); err != nil {
      return cfg.ErrorHandler(c, err)
  }

Line range hint 233-233: Ensure to handle the error returned by storageManager.delRaw to maintain consistent error handling.

- storageManager.delRaw(token)
  if err := storageManager.delRaw(token); err != nil {
      return cfg.ErrorHandler(c, err)
  }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ed9d7cf and 2f82476.

Files selected for processing (3)
  • middleware/csrf/csrf.go (4 hunks)
  • middleware/csrf/session_manager.go (1 hunks)
  • middleware/csrf/storage_manager.go (2 hunks)
Additional context used
GitHub Check: lint
middleware/csrf/session_manager.go

[failure] 29-29:
named return "rawToken" with type "[]byte" found (nonamedreturns)


[failure] 29-29:
named return "err" with type "error" found (nonamedreturns)

middleware/csrf/storage_manager.go

[failure] 44-44:
named return "raw" with type "[]byte" found (nonamedreturns)

middleware/csrf/csrf.go

[failure] 110-110:
Error return value is not checked (errcheck)


[failure] 213-213:
named return "err" with type "error" found (nonamedreturns)


[failure] 213-213:
named return "raw" with type "[]byte" found (nonamedreturns)


[failure] 225-225:
unhandled-error: Unhandled error in call to function csrf.storageManager.setRaw (revive)


[failure] 225-225:
Error return value of storageManager.setRaw is not checked (errcheck)


[failure] 233-233:
unhandled-error: Unhandled error in call to function csrf.storageManager.delRaw (revive)


[failure] 233-233:
Error return value of storageManager.delRaw is not checked (errcheck)

Additional comments not posted (1)
middleware/csrf/storage_manager.go (1)

62-73: The error handling in setRaw and delRaw methods enhances the robustness of the CSRF middleware.

Also applies to: 77-87

middleware/csrf/session_manager.go Outdated Show resolved Hide resolved
middleware/csrf/storage_manager.go Outdated Show resolved Hide resolved
middleware/csrf/csrf.go Outdated Show resolved Hide resolved
middleware/csrf/csrf.go Outdated Show resolved Hide resolved
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: 3

Outside diff range and nitpick comments (3)
middleware/csrf/csrf.go (3)

24-24: Clarify the comment for errOriginNotFound.

The comment "internal error, will not be returned to the user" could be expanded to explain why this error is internal and under what circumstances it might be used internally.


Line range hint 225-225: Handle the error returned by storageManager.setRaw.

The error returned by storageManager.setRaw is not checked. This could lead to silent failures. Ensure that errors are handled appropriately:

- storageManager.setRaw(token, dummyValue, cfg.Expiration)
  if err := storageManager.setRaw(token, dummyValue, cfg.Expiration); err != nil {
      return cfg.ErrorHandler(c, err)
  }

Line range hint 233-233: Check the error returned by storageManager.delRaw.

The error from storageManager.delRaw is not handled, which might result in unreported failures:

- storageManager.delRaw(token)
  if err := storageManager.delRaw(token); err != nil {
      return cfg.ErrorHandler(c, err)
  }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2f82476 and 750c7f5.

Files selected for processing (1)
  • middleware/csrf/csrf.go (4 hunks)
Additional context used
GitHub Check: lint
middleware/csrf/csrf.go

[failure] 213-213:
named return "raw" with type "[]byte" found (nonamedreturns)


[failure] 213-213:
named return "err" with type "error" found (nonamedreturns)


[failure] 225-225:
unhandled-error: Unhandled error in call to function csrf.storageManager.setRaw (revive)


[failure] 225-225:
Error return value of storageManager.setRaw is not checked (errcheck)


[failure] 233-233:
unhandled-error: Unhandled error in call to function csrf.storageManager.delRaw (revive)


[failure] 233-233:
Error return value of storageManager.delRaw is not checked (errcheck)

Additional comments not posted (1)
middleware/csrf/csrf.go (1)

213-213: Remove named return values to enhance code clarity.

This issue was previously flagged and remains valid. Consider simplifying the function signature by removing named return values:

- func getRawFromStorage(c fiber.Ctx, token string, cfg Config, sessionManager *sessionManager, storageManager *storageManager) (raw []byte, err error) {
  func getRawFromStorage(c fiber.Ctx, token string, cfg Config, sessionManager *sessionManager, storageManager *storageManager) ([]byte, error) {

Comment on lines 110 to 111
raw, err := getRawFromStorage(c, cookieToken, cfg, sessionManager, storageManager)
if raw != nil && err == nil {
Copy link
Contributor

@coderabbitai coderabbitai bot May 30, 2024

Choose a reason for hiding this comment

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

Handle potential errors from getRawFromStorage properly.

The error from getRawFromStorage is checked, but the handling could be more robust. Consider adding specific error handling for different types of errors that could be returned:

  raw, err := getRawFromStorage(c, cookieToken, cfg, sessionManager, storageManager)
  if err != nil {
      if errors.Is(err, ErrNotGetStorage) {
          // Handle specific error
      }
      return cfg.ErrorHandler(c, err)
  }

Committable suggestion was skipped due low confidence.

Copy link
Member Author

Choose a reason for hiding this comment

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

@coderabbitai it doesn't make sense, can you explain why I need to do that?

Copy link
Contributor

Choose a reason for hiding this comment

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

@renanbastos93 The suggestion to handle specific errors from getRawFromStorage more robustly is aimed at improving the middleware's ability to respond appropriately to different failure scenarios. Currently, the error handling in the switch case for GET, HEAD, OPTIONS, and TRACE methods does not differentiate between the types of errors that could be returned from getRawFromStorage. This function could return errors like ErrNotGetStorage, which specifically indicates issues in retrieving data from storage.

By handling such specific errors distinctly, you can tailor the middleware's response to better suit the nature of the error. For example, if ErrNotGetStorage is encountered, it might be beneficial to log this as a critical error or perform a specific action, because it indicates a failure in the storage backend, which is critical for CSRF protection. This makes the error handling more granular and can help in debugging and maintaining the system more effectively.

Let me know if this clarifies the suggestion or if there's anything else you'd like to discuss!

Copy link
Member Author

Choose a reason for hiding this comment

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

@coderabbitai I got it I am waiting for the team comment for that too.

Copy link
Contributor

Choose a reason for hiding this comment

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

@renanbastos93, understood! It's great to hear that you're considering the suggestion and discussing it further with your team. If you need any more information or further clarification as you move forward, feel free to reach out. I'm here to help!

middleware/csrf/csrf.go Outdated Show resolved Hide resolved
middleware/csrf/csrf.go Outdated Show resolved Hide resolved
@gaby
Copy link
Member

gaby commented May 30, 2024

Why isnt this fix in the rewrite PR #3016 ? It's a 1 line change @sixcolors

@renanbastos93
Copy link
Member Author

Why isnt this fix in the rewrite PR #3016 ? It's a 1 line change @sixcolors

@gaby Since he opened an issue to address error handling, I tried to help him with just that part to save him time so that he could focus on the other changes.

@renanbastos93
Copy link
Member Author

@gaby sorry, Did I make a mistake?

@gaby
Copy link
Member

gaby commented Jun 2, 2024

@renanbastos93 Might need to update the tests, the coverage dropped. Existing tests are passing though.

Copy link
Member

@sixcolors sixcolors left a comment

Choose a reason for hiding this comment

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

Docs need update if adding new sentinel errors.

@renanbastos93
Copy link
Member Author

@gaby and @sixcolors of course I will do it. Thanks

middleware/csrf/csrf.go Outdated Show resolved Hide resolved
@renanbastos93 renanbastos93 marked this pull request as draft June 5, 2024 16:47
@gaby gaby added the v3 label Jun 25, 2024
@gaby
Copy link
Member

gaby commented Jun 25, 2024

@renanbastos93 Any updates on this?

@renanbastos93
Copy link
Member Author

@renanbastos93 Any updates on this?

Hey @gaby , I am so sorry you were waiting for it. I've been sick for the last two weeks and need to finish the unit tests. I will focus on them this week. Do we have any other details to adjust?

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: f5933a6 Previous: 85a5fb8 Ratio
Benchmark_Compress_Levels/Zstd_LevelBestCompression - B/op 1 B/op 0 B/op
BenchmarkAppendMsgstorageManager 0.6301 ns/op 1586.98 MB/s 0 B/op 0 allocs/op 0.3186 ns/op 3139.20 MB/s 0 B/op 0 allocs/op 1.98
BenchmarkAppendMsgstorageManager - ns/op 0.6301 ns/op 0.3186 ns/op 1.98

This comment was automatically generated by workflow using github-action-benchmark.

@ReneWerner87
Copy link
Member

@renanbastos93 can you refresh the code with the last master

@renanbastos93
Copy link
Member Author

@renanbastos93 can you refresh the code with the last master

Of course, I've been in a rush around here and haven't been able to give it the attention it deserves. I'm thinking about closing the PR and opening a new one, what do you think?

@ReneWerner87
Copy link
Member

ok is also fine for me

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

Successfully merging this pull request may close these issues.

Improve Error Handling in CSRF Middleware Storage
4 participants