-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
๐งน chore: Improve Cookie() validation #3546
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
Conversation
|
""" WalkthroughThe Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant DefaultCtx
participant http.Cookie
participant fasthttp.Cookie
participant ResponseHeader
Client->>DefaultCtx: Set Cookie(cookie)
DefaultCtx->>http.Cookie: Populate fields from input
http.Cookie->>http.Cookie: Validate()
alt Cookie invalid
http.Cookie-->>DefaultCtx: Invalid, return early
else Cookie valid
http.Cookie->>fasthttp.Cookie: Transfer validated fields
fasthttp.Cookie->>ResponseHeader: Set-Cookie
end
Suggested labels
Suggested reviewers
Poem
""" ๐ Recent review detailsConfiguration used: CodeRabbit UI ๐ Files selected for processing (2)
๐ง Files skipped from review as they are similar to previous changes (2)
โจ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. ๐ชง TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly improves the robustness and security of cookie handling by integrating Go's standard net/http.Cookie validation. By first validating custom cookie structs against the net/http package's strict rules, the system ensures that only properly formed cookies are set, preventing potential issues arising from malformed or invalid cookie data. The changes also include expanded test coverage to confirm the effectiveness of the new validation mechanisms.
Highlights
- Enhanced Cookie Validation: The
Cookiefunction inctx.gonow leverages thenet/http.Cookietype and itsValid()method to perform comprehensive validation of cookie attributes (such as name, value, domain, path, and expiry). This ensures that only well-formed and compliant cookies are processed and set. - Standard Library Integration: Cookie properties are first mapped to an
http.Cookiestruct, allowing the standard library's robust validation logic to be applied. After successful validation, the attributes are then used to populate afasthttp.Cookie. - Improved Cookie Defaults: The
Cookiefunction now automatically sets thePathto/if it's empty and explicitly clearsMaxAgeandExpires(by setting them to 0 and a zero time, respectively) whenSessionOnlyis true, aligning with standard cookie behavior. - Expanded Test Coverage: A new test suite,
Test_Ctx_Cookie_Invalid, has been added toctx_test.go. This suite includes a variety of invalid cookie scenarios, such as malformed names, values, domains (including IPv6 addresses which are not allowed for domains), and paths, ensuring the new validation logic correctly rejects them.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with ๐ and ๐ on @gemini-code-assist comments to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. โฉ
Codecov Reportโ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3546 +/- ##
==========================================
- Coverage 90.61% 90.61% -0.01%
==========================================
Files 110 110
Lines 10869 10907 +38
==========================================
+ Hits 9849 9883 +34
- Misses 769 773 +4
Partials 251 251
Flags with carried forward coverage won't be shown. Click here to find out more. โ View full report in Codecov by Sentry. ๐ New features to boost your workflow:
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
The pull request improves cookie validation by using net/http.Cookie for validation and expands invalid cookie test cases. The changes look good overall, but there are a few suggestions for improvement, such as handling the error from hc.Valid() and reducing redundancy in the sameSite switch statement.
There was a problem hiding this 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
๐ Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
๐ Files selected for processing (2)
ctx.go(1 hunks)ctx_test.go(1 hunks)
โฐ Context from checks skipped due to timeout of 90000ms (8)
- GitHub Check: lint
- GitHub Check: Compare
- GitHub Check: repeated
- GitHub Check: unit (1.24.x, macos-latest)
- GitHub Check: Analyse
- GitHub Check: unit (1.24.x, windows-latest)
- GitHub Check: unit (1.24.x, macos-13)
- GitHub Check: unit (1.24.x, ubuntu-latest)
๐ Additional comments (5)
ctx.go (4)
400-406: Cookie validation implementation looks good!The default path setting and SessionOnly handling are correctly implemented. This ensures cookies have a valid path and session-only cookies don't persist.
408-420: SameSite mapping is well-structured with secure defaults.The mapping correctly handles all SameSite modes and defaults to Lax mode for better security.
422-437: Excellent use of standard library validation!Using
http.Cookie.Valid()provides robust validation and early rejection of invalid cookies, which aligns perfectly with the PR objectives.
422-437: Verify if additional domain validation with utils.IsIPv4 is needed.The PR objectives mention validating cookie domains using
utils.IsIPv4, but the current implementation delegates all validation tohttp.Cookie.Valid(). Please verify if additional IP-based domain validation is required or if the standard library validation is sufficient.#!/bin/bash # Check if utils.IsIPv4 is used elsewhere for cookie domain validation rg -A 5 "IsIPv4.*[Dd]omain|[Dd]omain.*IsIPv4" --type go # Check the implementation of cookie domain validation in tests fd -e go -x grep -l "cookie.*domain\|domain.*cookie" {} | xargs grep -A 5 -B 5 "IsIPv4\|Invalid.*[Dd]omain" # Look for cookie validation test cases ast-grep --pattern 'func Test.*Cookie.*Invalid'ctx_test.go (1)
923-946: LGTM! Comprehensive cookie validation test.This test effectively validates the cookie rejection functionality with well-chosen edge cases. The test structure is clean and follows Go testing best practices:
- Covers critical invalid scenarios (empty names, invalid characters, domain/path violations, security requirements)
- Properly isolates each test case with header resets
- Uses clear, descriptive comments for each test case
- Follows the expected behavior of rejecting invalid cookies by ensuring no Set-Cookie header is set
The test cases are particularly well-selected, covering RFC violations, security requirements (partitioned cookies needing secure flag), and various malformed inputs.
There was a problem hiding this 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: a9d2ee9 | Previous: 0ebe65d | Ratio |
|---|---|---|---|
Benchmark_GenericParseTypeBytes/benchmark_genericParseTypeBytes#03 |
24.75 ns/op 0 B/op 0 allocs/op |
12.83 ns/op 0 B/op 0 allocs/op |
1.93 |
Benchmark_GenericParseTypeBytes/benchmark_genericParseTypeBytes#03 - ns/op |
24.75 ns/op |
12.83 ns/op |
1.93 |
This comment was automatically generated by workflow using github-action-benchmark.
|
@coderabbitai full review |
โ Actions performedFull review triggered. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR improves the RFC validation of cookies by validating cookies using the net/http.Cookie API before applying settings to a fasthttp.Cookie. It introduces additional test cases for partitioned secure cookies and checks for various invalid cookie parameters.
- Added new tests in ctx_test.go for partitioned secure cookies and invalid cookie validation.
- Refactored the Cookie() method in ctx.go to build a net/http.Cookie, validate it, and then set values on a fasthttp.Cookie.
- Enforced default cookie path and session-only behavior, and mapped SameSite string values to appropriate http.SameSite constants.
Reviewed Changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| ctx_test.go | Introduces tests that verify partitioned secure cookie formatting and invalid cookies. |
| ctx.go | Refactors cookie creation by validating against the net/http.Cookie API and mapping SameSite values. |
|
Note to myself, using
|
There was a problem hiding this 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
โป๏ธ Duplicate comments (2)
ctx.go (1)
441-444: Remove redundant SessionOnly check.This check is unnecessary since
MaxAgeandExpireswere already handled appropriately in lines 403-406 for session-only cookies.- if !cookie.SessionOnly { - fcookie.SetMaxAge(hc.MaxAge) - fcookie.SetExpire(hc.Expires) - } + fcookie.SetMaxAge(hc.MaxAge) + fcookie.SetExpire(hc.Expires)ctx_test.go (1)
923-938: LGTM! This test appropriately addresses the past review comment.This test correctly validates that partitioned cookies with the
Secureflag andSameSite=Noneare properly serialized, directly addressing the previous review feedback about testing this specific scenario.
๐ Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
๐ Files selected for processing (2)
ctx.go(1 hunks)ctx_test.go(1 hunks)
๐งฐ Additional context used
๐ช GitHub Check: codecov/patch
ctx.go
[warning] 416-416: ctx.go#L416
Added line #L416 was not covered by tests
[warning] 454-455: ctx.go#L454-L455
Added lines #L454 - L455 were not covered by tests
๐ช GitHub Check: lint
ctx.go
[failure] 408-408:
var-declaration: should omit type http.SameSite from declaration of var sameSite; it will be inferred from the right-hand side (revive)
๐ช GitHub Actions: golangci-lint
ctx.go
[error] 408-408: golangci-lint (revive): var-declaration: should omit type http.SameSite from declaration of var sameSite; it will be inferred from the right-hand side
๐ Additional comments (4)
ctx.go (3)
420-434: LGTM! Excellent RFC validation approach.Creating an
http.Cookiestruct and using itsValid()method is the right approach for ensuring RFC compliance. This addresses the PR objective of improving Cookie RFC validation by leveraging the standard library's validation logic.
416-416: Add test coverage for SameSite disabled case.The static analysis indicates this line is not covered by tests. Ensure there's a test case that exercises the
CookieSameSiteDisabledbranch.#!/bin/bash # Description: Search for existing test cases covering SameSite disabled scenario # Expected: Find test cases that set SameSite to disabled value rg -A 10 -B 5 "SameSiteDisabled|CookieSameSiteDisabled" --type go
454-455: Add test coverage for DefaultMode and Disabled SameSite cases.These lines handling
CookieSameSiteDefaultModeandCookieSameSiteDisabledare not covered by tests according to static analysis.#!/bin/bash # Description: Check test coverage for SameSite edge cases # Expected: Find or confirm missing test cases for default and disabled modes rg -A 15 -B 5 "Test.*Cookie.*SameSite|SameSite.*test" --type goctx_test.go (1)
940-963: Excellent comprehensive test coverage for invalid cookie scenarios.This test systematically validates multiple edge cases and invalid input scenarios, ensuring that the enhanced cookie validation properly rejects malformed cookies. The test structure with proper header reset between iterations and the comprehensive coverage of validation rules (including the important partitioned-without-secure case) demonstrates thorough testing practices.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Summary
net/http.Cookiethen setting values on afasthttp.CookieRelated #3383