-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
🐛 bug: Fix CookieJar domain logic #3564
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 CookieJar
participant Server
Client->>Server: Send HTTP(S) request
Server-->>Client: Respond with Set-Cookie headers
Client->>CookieJar: parseCookiesFromResp(host, resp)
CookieJar->>CookieJar: Normalize domain/path, store cookies
Client->>CookieJar: Get(host, path, scheme)
CookieJar->>CookieJar: cookiesForRequest(host, path, secure)
CookieJar-->>Client: Return matching cookies (by domain, path, secure, not expired)
Suggested reviewers
Poem
✨ 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 refines the CookieJar
implementation to align more closely with standard cookie behavior, particularly concerning domain and path matching, secure flag handling, and cookie lifecycle management. The changes aim to improve the accuracy and robustness of how cookies are stored, retrieved, and validated, ensuring more predictable and correct interactions with web services.
Highlights
- Improved Cookie Retrieval Logic: Refactored cookie retrieval to centralize logic in a new
cookiesForRequest
function, which now correctly filters cookies based on host, path, and thesecure
flag, and also handles the removal of expired cookies. - Enhanced Cookie Setting and Domain Normalization: Updated
SetByHost
andparseCookiesFromResp
to consistently normalize host and cookie domain strings (e.g., lowercasing, removing ports, trimming leading dots) and to correctly set a cookie's domain to the host if it's initially unset. - Precise Path and Domain Matching: Modified
searchCookieByKeyAndPath
to enforce exact path matching for non-root paths and introduced a newdomainMatch
helper function to implement more accurate and case-insensitive domain matching rules. - Resource Management for Parsed Cookies: Ensured that temporary
fasthttp.Cookie
objects acquired during cookie parsing from responses are properly released to prevent memory leaks. - Comprehensive Test Coverage: Added new test cases to validate correct behavior for host/port handling, subdomain matching, and the
Secure
cookie attribute, addressing potential regressions and improving overall reliability.
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 ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3564 +/- ##
==========================================
- Coverage 90.97% 90.94% -0.04%
==========================================
Files 111 111
Lines 11125 11198 +73
==========================================
+ Hits 10121 10184 +63
- Misses 754 761 +7
- Partials 250 253 +3
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 handling in the CookieJar
by normalizing domains and handling secure cookies. However, there are potential issues with cookie path matching, state exposure due to direct cookie pointer returns, and memory management related to unsafe strings. Addressing these concerns will enhance the correctness and robustness of the CookieJar
.
Will fix bot review later today |
/gemini review |
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 code changes fix cookie copying directions, normalize domains, update domain matching logic, verify parsed cookies retain their values, add a regression test for port handling, and set domain when unset and compare paths exactly.
Error: client/cookiejar.go:234:49: unused-parameter: parameter 'path' seems to be unused, consider removing or renaming it as _ (revive) |
/gemini review |
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 fixes several bugs in the CookieJar domain logic, including cookie copying directions, domain normalization, and domain matching logic. It also adds a regression test for port handling and updates the path comparison to be exact. The changes improve the correctness and reliability of the CookieJar implementation.
Fix cookiejar key handling and cleanup
/gemini review |
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
This pull request provides a significant and much-needed fix to the CookieJar
's domain and path matching logic, bringing it more in line with RFC 6265. The changes are well-structured, and the addition of comprehensive regression tests for domain, path, port, and secure cookie handling is excellent. I've found one minor area for improvement regarding redundant code, but overall, this is a high-quality contribution that greatly improves the correctness of cookie handling.
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
🧹 Nitpick comments (1)
client/cookiejar.go (1)
325-333
: Domain matching logic is correct with minor optimization opportunity.The
domainMatch
function correctly implements RFC 6265 domain matching rules. However, the host normalization might be redundant since callers may have already normalized the domain.Consider optimizing by accepting pre-normalized domain parameters:
-func domainMatch(host, domain string) bool { - host = utils.ToLower(host) +func domainMatch(host, domain string) bool { + // Assume host and domain are already normalized by callers
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
client/cookiejar.go
(9 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the Fiber framework tests, using `ctx.Response.Header.Cookie` may not be suitable for parsing cookies from the response header, as it requires a `*Cookie` and fills it rather than returning a string value; thus, manual parsing of the `Set-Cookie` header may be necessary.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-09-25T15:57:10.221Z
Learning: In the Fiber framework tests, using `ctx.Response.Header.Cookie` may not be suitable for parsing cookies from the response header, as it requires a `*Cookie` and fills it rather than returning a string value; thus, manual parsing of the `Set-Cookie` header may be necessary.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:51-54
Timestamp: 2024-07-01T03:33:22.283Z
Learning: Unit tests for key length enforcement in `DecryptCookie` have been added to ensure consistency and security in the encryption processes.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:51-54
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in `DecryptCookie` have been added to ensure consistency and security in the encryption processes.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in both `EncryptCookie` and `DecryptCookie` functions have been added to ensure robust validation and prevent potential runtime errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-07-01T03:44:03.672Z
Learning: Unit tests for key length enforcement in both `EncryptCookie` and `DecryptCookie` functions have been added to ensure robust validation and prevent potential runtime errors.
client/cookiejar.go (5)
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the Fiber framework tests, using `ctx.Response.Header.Cookie` may not be suitable for parsing cookies from the response header, as it requires a `*Cookie` and fills it rather than returning a string value; thus, manual parsing of the `Set-Cookie` header may be necessary.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-09-25T15:57:10.221Z
Learning: In the Fiber framework tests, using `ctx.Response.Header.Cookie` may not be suitable for parsing cookies from the response header, as it requires a `*Cookie` and fills it rather than returning a string value; thus, manual parsing of the `Set-Cookie` header may be necessary.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.
🧬 Code Graph Analysis (1)
client/cookiejar.go (1)
ctx.go (1)
Cookie
(185-197)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: unit (1.24.x, windows-latest)
- GitHub Check: repeated
- GitHub Check: Compare
🔇 Additional comments (10)
client/cookiejar.go (10)
8-8
: Import addition looks good.The
strings
import is needed for the newdomainMatch
function implementation.
54-55
: Excellent security enhancement for secure cookie handling.The implementation correctly detects HTTPS requests and passes the secure flag to ensure secure cookies are only sent over encrypted connections, which aligns with RFC 6265 security requirements.
59-59
: Function signature update is appropriate.Adding the
secure
parameter enables proper filtering of secure cookies, and delegating tocookiesForRequest
improves code organization.Also applies to: 74-74
85-97
: Excellent refactoring of expired cookie removal.The slice filtering pattern using
kept := cookies[:0]
is cleaner and more idiomatic than manual index management. Proper resource management is maintained withfasthttp.ReleaseCookie
.
109-127
: Cookie filtering logic is well implemented.The domain matching, path matching, and secure cookie filtering correctly implement RFC 6265 requirements. The cleanup of expired cookies using slice filtering is efficient and proper.
Also applies to: 131-135
155-188
: Excellent domain normalization and key management improvements.The changes properly address memory leak concerns by:
- Stripping ports from host names
- Normalizing domain names (lowercase, trim leading dots)
- Using
utils.CopyString
to ensure map keys don't reference response buffers- Setting domain on cookies when unset
These improvements align with RFC 6265 and prevent memory leaks.
216-217
: Good resource management and security improvements.Adding secure flag detection ensures proper cookie filtering, and releasing cookies after use prevents resource leaks.
Also applies to: 220-220
225-261
: Excellent improvements to cookie parsing and resource management.The host normalization, domain handling, and proper cleanup of expired cookies are well implemented. The resource management with
fasthttp.ReleaseCookie(tmp)
prevents memory leaks.Also applies to: 263-276
296-296
: Consistent path matching implementation.Using
pathMatch
ensures consistent RFC 6265 compliant path matching throughout the codebase.
304-323
: Excellent RFC 6265 compliant path matching implementation.The
pathMatch
function correctly implements RFC 6265 section 5.1.4 with proper handling of:
- Empty paths defaulting to "/"
- Exact path equality
- Prefix matching with correct slash boundary logic
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.
LGTM
ai found interesting lines -> pls check copy direction
Summary