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

feat(middleware/csrf): TrustedOrigins using https://*.example.com style subdomains #2925

Merged
merged 13 commits into from
Mar 25, 2024

Conversation

sixcolors
Copy link
Member

@sixcolors sixcolors commented Mar 18, 2024

PR Description:

This PR updates the TrustedOrigins subdomain matching style to match the changes made in the CORS middleware. Here's a summary of the changes:

Changes Made:

  • Documentation Update:
    • Updated the documentation in docs/api/middleware/csrf.md to reflect the new subdomain matching style for TrustedOrigins.
    • Updated the TrustedOrigins section to include examples and cautionary notes regarding subdomain matching.
  • Code Changes:
    • Modified the csrf.go file to parse and handle TrustedOrigins with subdomain matching.
    • Added a new helpers.go file containing helper functions for normalizing origins and matching subdomains.
    • Updated corresponding tests in csrf_test.go and added new tests in helpers_test.go to ensure the correct behavior of subdomain matching.

Notes for Review:

  • Documentation Clarity: Please review the updated documentation in docs/api/middleware/csrf.md to ensure clarity and correctness.
  • Code Logic: Review the changes in the csrf.go file to confirm that the handling of TrustedOrigins with subdomain matching aligns with our requirements.
  • Test Coverage: Verify that the tests in csrf_test.go cover various scenarios related to subdomain matching and ensure they provide sufficient coverage.
  • Performance Impact: Consider any potential performance impact introduced by the changes in the helpers.go file and ensure it's acceptable.

Kindly review and provide feedback. Thank you!

Summary by CodeRabbit

  • Refactor
    • Improved CSRF protection by enhancing origin and referer matching to better handle subdomains.
  • Tests
    • Updated and added tests to ensure robust CSRF protection, including handling of wildcard domains and invalid origins.
  • Documentation
    • Updated TrustedOrigins configuration in CSRF middleware to support subdomain matching with wildcard characters. Added examples and security guidance in the documentation.

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

coderabbitai bot commented Mar 18, 2024

Walkthrough

The CSRF middleware has been updated to enhance security and flexibility by introducing wildcard support for subdomain matching in the TrustedOrigins configuration. This update simplifies specifying trusted origins across subdomains, comes with guidance for secure usage, and refines origin validation. Additionally, the codebase sees improvements in structure and testing, ensuring robust handling of CSRF protection mechanisms.

Changes

File(s) Summary
docs/api/middleware/csrf.md Updated to explain wildcard support for subdomain matching in TrustedOrigins.
middleware/csrf/csrf.go Imported log package, modified config field, updated trustedOrigins, and refactored origin matching.
middleware/csrf/csrf_test.go Adjusted and added tests for trusted origins and token deletion.
middleware/csrf/helpers.go,
middleware/csrf/helpers_test.go
Introduced functions for origin normalization and subdomain matching, along with tests and benchmarks.

🐇
In the land of code, where security's key,
A rabbit hopped in, changes to see.
With wildcards in hand, and tests all around,
Subdomains are safe, no danger found.
"Hop, skip, and a jump," it joyfully said,
"With CSRF fixed, we're ahead!"
🌟🛡️🐾

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-tests 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 tests 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 tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

codecov bot commented Mar 18, 2024

Codecov Report

Attention: Patch coverage is 98.41270% with 1 lines in your changes are missing coverage. Please review.

Project coverage is 82.76%. Comparing base (3209052) to head (793286f).
Report is 1 commits behind head on main.

Files Patch % Lines
middleware/csrf/csrf.go 98.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2925      +/-   ##
==========================================
+ Coverage   82.75%   82.76%   +0.01%     
==========================================
  Files         116      116              
  Lines        8396     8415      +19     
==========================================
+ Hits         6948     6965      +17     
- Misses       1108     1110       +2     
  Partials      340      340              
Flag Coverage Δ
unittests 82.76% <98.41%> (+0.01%) ⬆️

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.

Review Status

Actionable comments generated: 7

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 43dc60f and 2c80db9.
Files selected for processing (5)
  • docs/api/middleware/csrf.md (3 hunks)
  • middleware/csrf/csrf.go (9 hunks)
  • middleware/csrf/csrf_test.go (5 hunks)
  • middleware/csrf/helpers.go (2 hunks)
  • middleware/csrf/helpers_test.go (1 hunks)
Additional comments: 8
middleware/csrf/helpers.go (1)
  • 17-48: Consider adding more detailed comments within the normalizeOrigin function to explain the rationale behind each validation check. This will improve maintainability and understanding for future contributors.
middleware/csrf/helpers_test.go (1)
  • 115-130: The benchmark test for subdomain.match is well-implemented and provides valuable insights into the method's performance. It's a good practice to assess the performance impact of changes, such as making the matching case-insensitive.
middleware/csrf/csrf.go (2)
  • 28-28: Changing the config field in the Handler struct from a pointer to a value type is a good practice, as it ensures the configuration's immutability once the handler is created. This prevents accidental modifications and enhances safety.
  • 60-81: The updates to the initialization of trustedOrigins and trustedSubOrigins to support wildcard subdomain matching are well-implemented. This enhancement significantly improves the flexibility and security of the CSRF middleware by allowing more granular control over trusted origins.
docs/api/middleware/csrf.md (3)
  • 119-119: The documentation update to specify the use of wildcard characters (e.g., https://*.example.com) for subdomain matching in the TrustedOrigins configuration is clear and correctly reflects the new functionality. This change allows for a more flexible and convenient way to specify trusted origins, especially for applications that operate across multiple subdomains.
  • 159-159: The explanation of the TrustedOrigins option and its support for matching subdomains at any level is well-documented. The inclusion of an example using "https://*.example.com" to allow any subdomain of example.com to submit requests enhances the clarity of this feature. This section effectively communicates the new capability and its potential use cases.
  • 182-182: The caution note regarding the use of TrustedOrigins with subdomain matching is an important inclusion. It rightly emphasizes the security considerations that users must be aware of when configuring trusted origins with wildcard subdomains. This helps ensure that users understand the implications and use the feature securely.
middleware/csrf/csrf_test.go (1)
  • 999-1010: The logic for deleting the CSRF token and removing the cookie in Test_CSRF_DeleteToken is a valuable addition. It's important to ensure that the CSRF protection mechanism can handle token deletion securely and correctly. This test case helps verify that behavior. However, consider adding a comment explaining the purpose of deleting all cookies in line 1005 and its relevance to CSRF protection, as it might not be immediately clear to future maintainers.

middleware/csrf/csrf_test.go Show resolved Hide resolved
middleware/csrf/csrf_test.go Show resolved Hide resolved
middleware/csrf/helpers.go Show resolved Hide resolved
middleware/csrf/helpers_test.go Outdated Show resolved Hide resolved
middleware/csrf/helpers_test.go Outdated Show resolved Hide resolved
middleware/csrf/csrf.go Outdated Show resolved Hide resolved
middleware/csrf/csrf.go 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.

Review Status

Actionable comments generated: 5

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 2c80db9 and e27d047.
Files selected for processing (2)
  • middleware/csrf/csrf.go (8 hunks)
  • middleware/csrf/csrf_test.go (5 hunks)
Additional comments: 2
middleware/csrf/csrf.go (2)
  • 27-27: The change from a pointer to a value type for the config field in the Handler struct is a significant alteration. This change ensures that the config is not nil, potentially improving the safety and reliability of the middleware. However, it's important to consider the impact on memory usage, especially if the Config struct is large or contains many fields. In most cases, the benefits of avoiding nil pointer dereferences outweigh the slight increase in memory usage.
  • 117-122: The implementation of origin and referer matching functions to handle subdomains is a key enhancement. It correctly enforces origin checks for unsafe requests and falls back to referer checks for HTTPS connections when the origin is not available. This approach aligns with security best practices by prioritizing the Origin header over the Referer header due to the latter's less reliable nature. The logic appears sound and well-integrated with the existing CSRF protection mechanisms.

middleware/csrf/csrf.go Show resolved Hide resolved
middleware/csrf/csrf.go Show resolved Hide resolved
middleware/csrf/csrf_test.go Show resolved Hide resolved
middleware/csrf/csrf_test.go Outdated Show resolved Hide resolved
middleware/csrf/csrf_test.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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between e27d047 and 9d1fee1.
Files selected for processing (3)
  • docs/api/middleware/csrf.md (3 hunks)
  • middleware/csrf/csrf_test.go (7 hunks)
  • middleware/csrf/helpers_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • middleware/csrf/csrf_test.go
  • middleware/csrf/helpers_test.go
Additional comments: 3
docs/api/middleware/csrf.md (3)
  • 119-119: The update to the TrustedOrigins configuration description to include wildcard subdomain matching (https://*.example.com) is clear and accurately reflects the new functionality. This change enhances the flexibility and usability of the CSRF middleware by allowing developers to specify a range of trusted subdomains in a concise manner.
  • 159-161: The explanation of the TrustedOrigins option and its ability to match subdomains at any level is well-detailed and informative. It correctly emphasizes the utility of the feature in allowing requests from any subdomain of a specified domain, enhancing the middleware's flexibility for applications with multiple subdomains.
  • 183-185: The caution note regarding the use of TrustedOrigins with subdomain matching is crucial for security. It rightly warns users to ensure control and trust over all subdomains, including all subdomain levels, to prevent potential misuse by attackers. This is an important security consideration that helps guide users in safely utilizing the new feature.

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

@ReneWerner87 ReneWerner87 added this to the v3 milestone Mar 24, 2024
middleware/csrf/helpers.go Show resolved Hide resolved
middleware/csrf/csrf.go Show resolved Hide resolved
middleware/csrf/csrf.go Show resolved Hide resolved
@sixcolors
Copy link
Member Author

sixcolors commented Mar 25, 2024

@ReneWerner87

Benchmark ns/op (avg) B/op (avg) allocs/op (avg)
strings.ToLower()
Benchmark_Middleware_CSRF_Check-24 3913.25 412 9
utils.ToLower()
Benchmark_Middleware_CSRF_Check-24 4006.625 436 10

I'd like to note that the benchmark Benchmark_Middleware_CSRF_Check is testing a best-case scenario for strings.ToLower(), where the Referer header is already in lowercase and does not contain any non-ASCII characters, which is typically the general case for web browsers as clients.

Also, I found a bug in the CSRF benchmark, and I'll push a fix shortly.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9d1fee1 and 793286f.
Files selected for processing (1)
  • middleware/csrf/csrf_test.go (11 hunks)
Additional comments: 7
middleware/csrf/csrf_test.go (7)
  • 758-759: The addition of wildcard domain support in Test_CSRF_TrustedOrigins is a significant enhancement. It's crucial to ensure that the implementation correctly handles various subdomain patterns and edge cases. Consider adding more comprehensive tests to cover scenarios such as deeply nested subdomains (e.g., https://a.b.c.domain-1.com) and subdomains with special characters or hyphens to ensure robustness.
  • 892-892: The Test_CSRF_TrustedOrigins_InvalidOrigins test function correctly identifies invalid origin formats. However, it's recommended to call t.Parallel() at the beginning of each subtest to allow parallel execution and improve test suite performance. This change can significantly reduce the overall test execution time, especially as the number of tests grows.
  • 1030-1041: Adding logic for deleting the CSRF token and removing the cookie in Test_CSRF_DeleteToken is a good practice to ensure the middleware behaves correctly in scenarios where the token needs to be invalidated. This addition enhances the test coverage for token management within the CSRF middleware.
  • 1343-1369: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1333-1366]

The benchmark test Benchmark_Middleware_CSRF_Check is well-structured and provides a good measure of the middleware's performance under load. However, ensure that the CSRF token generation and validation logic are optimized to minimize performance overhead, especially in high-traffic applications.

  • 1387-1391: The benchmark test Benchmark_Middleware_CSRF_GenerateToken focuses on measuring the performance of CSRF token generation. It's important to ensure that the token generation process is both secure and efficient, as it directly impacts the user experience and the application's security posture.
  • 1392-1392: The test Test_CSRF_InvalidURLHeaders is crucial for ensuring that the CSRF middleware correctly handles invalid Origin and Referer headers, preventing potential security vulnerabilities. It's good practice to include such tests to cover edge cases and malformed inputs.
  • 1393-1393: The tests Test_CSRF_TokenFromContext, Test_CSRF_FromContextMethods, and Test_CSRF_FromContextMethods_Invalid are valuable for verifying the utility functions related to CSRF token management within the application context. These tests ensure that the middleware's API is reliable and behaves as expected in various scenarios.

@ReneWerner87 ReneWerner87 merged commit 643b4b3 into gofiber:main Mar 25, 2024
14 of 15 checks passed
@sixcolors sixcolors deleted the csrf-subdomain-style branch March 27, 2024 01:17
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.

3 participants