Skip to content

🐛 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

Merged
merged 10 commits into from
Jul 17, 2025
Merged

🐛 bug: Fix CookieJar domain logic #3564

merged 10 commits into from
Jul 17, 2025

Conversation

gaby
Copy link
Member

@gaby gaby commented Jul 3, 2025

Summary

  • fix cookie copying directions in CookieJar
  • normalize domains without allocating extra strings
  • update domain matching logic
  • verify parsed cookies retain their values
  • regression test for port handling retrieves cookie using a different port
  • set domain when unset and compare paths exactly

Copy link
Contributor

coderabbitai bot commented Jul 3, 2025

Walkthrough

The CookieJar implementation was refactored to improve cookie domain, path, and secure flag handling, aligning with RFC 6265. Domain and path normalization, secure cookie filtering, and resource management were enhanced. Tests were updated and expanded to verify correct cookie retrieval across domains, ports, paths, and secure contexts.

Changes

Files Change Summary
client/cookiejar.go Refactored cookie retrieval/storage logic for correct domain/path/secure handling; added domainMatch/pathMatch helpers; improved expiration cleanup and resource management.
client/cookiejar_test.go Updated and added tests for host/port, domain, secure flag, and path matching behaviors in CookieJar; corrected URL path handling and assertions.

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)
Loading

Suggested reviewers

  • ReneWerner87

Poem

Hopping through the cookie jar,
Domains and paths both near and far,
Secure or not, we check with care,
Ports ignored, subdomains fair.
With every nibble, tests abound,
RFC rules now safe and sound!
🍪🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need 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)

  • @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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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
Contributor

@gemini-code-assist gemini-code-assist bot left a 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 the secure flag, and also handles the removal of expired cookies.
  • Enhanced Cookie Setting and Domain Normalization: Updated SetByHost and parseCookiesFromResp 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 new domainMatch 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

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

@gaby gaby added this to v3 Jul 3, 2025
@gaby gaby added this to the v3 milestone Jul 3, 2025
Copy link

codecov bot commented Jul 3, 2025

Codecov Report

Attention: Patch coverage is 93.10345% with 8 lines in your changes missing coverage. Please review.

Project coverage is 90.94%. Comparing base (2832ae3) to head (2c559a1).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
client/cookiejar.go 93.10% 6 Missing and 2 partials ⚠️
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     
Flag Coverage Δ
unittests 90.94% <93.10%> (-0.04%) ⬇️

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.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gaby gaby changed the title Fix CookieJar domain logic 🐛 bug: Fix CookieJar domain logic Jul 3, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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.

@gaby
Copy link
Member Author

gaby commented Jul 3, 2025

Will fix bot review later today

@efectn efectn moved this to In Progress in v3 Jul 4, 2025
@gaby
Copy link
Member Author

gaby commented Jul 4, 2025

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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.

@ReneWerner87
Copy link
Member

@gaby

Error: client/cookiejar.go:234:49: unused-parameter: parameter 'path' seems to be unused, consider removing or renaming it as _ (revive)

@gaby
Copy link
Member Author

gaby commented Jul 9, 2025

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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.

@gaby
Copy link
Member Author

gaby commented Jul 16, 2025

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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.

@gaby gaby marked this pull request as ready for review July 16, 2025 22:28
@gaby gaby requested a review from a team as a code owner July 16, 2025 22:28
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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a1a124 and 2c559a1.

📒 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 new domainMatch 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 to cookiesForRequest 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 with fasthttp.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

Copy link
Member

@ReneWerner87 ReneWerner87 left a 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

@ReneWerner87 ReneWerner87 merged commit 09eaaf3 into main Jul 17, 2025
14 checks passed
@ReneWerner87 ReneWerner87 deleted the 2025-07-03-15-08-43 branch July 17, 2025 12:48
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jul 17, 2025
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.

2 participants