Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Jun 25, 2025

Summary

  • expand invalid cookie cases in tests
  • validate cookies using net/http.Cookie then setting values on a fasthttp.Cookie

Related #3383

Copilot AI review requested due to automatic review settings June 25, 2025 00:33
@gaby gaby requested a review from a team as a code owner June 25, 2025 00:33

This comment was marked as outdated.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 25, 2025

"""

Walkthrough

The Cookie method in DefaultCtx was refactored to use http.Cookie for validation and attribute handling, introducing early rejection of invalid cookies and improved SameSite and Partitioned attribute processing. Multiple new test functions were added to verify correct handling of partitioned secure cookies, default path and SameSite behavior, MaxAge-only cookies, strict partitioned cookies, and to ensure invalid cookies are not set in the response.

Changes

File(s) Change Summary
ctx.go Refactored DefaultCtx.Cookie to use http.Cookie for validation, improved SameSite/Partitioned handling, and added early return for invalid cookies.
ctx_test.go Added five new tests covering partitioned secure cookies, invalid cookies rejection, default path and SameSite, MaxAge-only cookies, and strict partitioned cookies.

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
Loading

Suggested labels

๐Ÿงน Updates, v3

Suggested reviewers

  • sixcolors
  • efectn

Poem

๐Ÿช
A cookieโ€™s a treat, but it must be just rightโ€”
No sneaky bad bytes or a name full of fright.
Now tested and guarded, with standards in view,
Only valid delights make it safely to you.
Hooray for sweet rigor, and code rabbits too!

"""


๐Ÿ“œ Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

๐Ÿ“ฅ Commits

Reviewing files that changed from the base of the PR and between efb5571 and fdf2fd3.

๐Ÿ“’ Files selected for processing (2)
  • ctx.go (1 hunks)
  • ctx_test.go (1 hunks)
๐Ÿšง Files skipped from review as they are similar to previous changes (2)
  • ctx.go
  • ctx_test.go
โœจ 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 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 Cookie function in ctx.go now leverages the net/http.Cookie type and its Valid() 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.Cookie struct, allowing the standard library's robust validation logic to be applied. After successful validation, the attributes are then used to populate a fasthttp.Cookie.
  • Improved Cookie Defaults: The Cookie function now automatically sets the Path to / if it's empty and explicitly clears MaxAge and Expires (by setting them to 0 and a zero time, respectively) when SessionOnly is true, aligning with standard cookie behavior.
  • Expanded Test Coverage: A new test suite, Test_Ctx_Cookie_Invalid, has been added to ctx_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

  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 marked this pull request as draft June 25, 2025 00:34
@codecov
Copy link

codecov bot commented Jun 25, 2025

Codecov Report

โŒ Patch coverage is 92.72727% with 4 lines in your changes missing coverage. Please review.
โœ… Project coverage is 90.61%. Comparing base (0ebe65d) to head (fdf2fd3).
โš ๏ธ Report is 371 commits behind head on main.

Files with missing lines Patch % Lines
ctx.go 92.72% 4 Missing โš ๏ธ
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              
Flag Coverage ฮ”
unittests 90.61% <92.72%> (-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.

๐Ÿš€ New features to boost your workflow:
  • โ„๏ธ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

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

๐Ÿ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

๐Ÿ“ฅ Commits

Reviewing files that changed from the base of the PR and between 0ebe65d and d98863b.

๐Ÿ“’ 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 to http.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.

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

@gaby gaby added this to v3 Jun 25, 2025
@gaby gaby moved this to In Progress in v3 Jun 25, 2025
@gaby gaby added this to the v3 milestone Jun 25, 2025
@gaby gaby changed the title Improve cookie validation ๐Ÿ› bug: Improve Cookie() RFC validation Jun 25, 2025
@gaby gaby requested a review from Copilot June 25, 2025 03:24
@gaby
Copy link
Member Author

gaby commented Jun 25, 2025

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 25, 2025

โœ… Actions performed

Full review triggered.

Copy link
Contributor

Copilot AI left a 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.

@gaby
Copy link
Member Author

gaby commented Jun 25, 2025

Note to myself, using hc.String() will make performance really bad. The correct way is to:

  • create http.Cookie()
  • call Valid()
  • use fasthttp.Cookie setters to create the Cookie.

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

โ™ป๏ธ Duplicate comments (2)
ctx.go (1)

441-444: Remove redundant SessionOnly check.

This check is unnecessary since MaxAge and Expires were 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 Secure flag and SameSite=None are properly serialized, directly addressing the previous review feedback about testing this specific scenario.

๐Ÿ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

๐Ÿ“ฅ Commits

Reviewing files that changed from the base of the PR and between 0ebe65d and efb5571.

๐Ÿ“’ 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.Cookie struct and using its Valid() 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 CookieSameSiteDisabled branch.

#!/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 CookieSameSiteDefaultMode and CookieSameSiteDisabled are 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 go
ctx_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>
@gaby gaby changed the title ๐Ÿ› bug: Improve Cookie() RFC validation ๐Ÿ› bug: Improve Cookie() validation Jun 25, 2025
@gaby gaby changed the title ๐Ÿ› bug: Improve Cookie() validation ๐Ÿงน chore: Improve Cookie() validation Jun 25, 2025
@gaby gaby marked this pull request as ready for review June 25, 2025 13:19
@ReneWerner87 ReneWerner87 merged commit 8e2ab96 into main Jun 25, 2025
14 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jun 25, 2025
@gaby gaby deleted the 2025-06-25-00-33-51 branch June 25, 2025 22:42
@gaby gaby added the ๐Ÿ“œ RFC Compliance Feature, implementation, or contribution adheres to relevant RFC standards. label Nov 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex ๐Ÿ“œ RFC Compliance Feature, implementation, or contribution adheres to relevant RFC standards. ๐Ÿงน Updates v3

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants