Skip to content

🩹 fix: Implement RFC 6265 Cookie Value Sanitization #3379

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

Open
wants to merge 18 commits into
base: main
Choose a base branch
from

Conversation

c00kie17
Copy link

@c00kie17 c00kie17 commented Mar 29, 2025

Description

Added cookie value sanitization according to RFC 6265 standards. The implementation validates and sanitizes cookie values by removing invalid characters ("",;, \), while intentionally allowing commas to maintain compatibility with Go's net/http package (see https://golang.org/issue/7243). Test cases have been updated accordingly to use RFC-compliant values.

Fixes #3176

Changes introduced

  • Implemented cookie value sanitization that ensures RFC 6265 compliance, removing invalid characters (", ;, ) from cookie values.
  • Modified test key string in keyAuth tests to be RFC 6265 compliant.

Breaking Change Notice

This change enforces RFC 6265 compliance for cookie values. If an existing application currently stores or relies on cookie values containing these characters, they will be silently removed when processed by Fiber.

Type of change

  • Enhancement (improvement to existing features and functionality)

Checklist

  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.

@c00kie17 c00kie17 requested a review from a team as a code owner March 29, 2025 17:47
@c00kie17 c00kie17 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team March 29, 2025 17:47
Copy link

welcome bot commented Mar 29, 2025

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Mar 29, 2025

Walkthrough

The changes introduce a new method parseCookieValue to the DefaultCtx struct in ctx.go, which parses cookie values according to RFC 6265. This method validates each character in the cookie value and returns an empty string for invalid characters. The existing Cookies method is updated to utilize this new parsing method. Additionally, ctx_test.go has been modified to include new test cases that check the handling of cookie values with commas, quotes, and backslashes, as well as changing the default return value for unknown cookies to an empty string. The redirect.go and redirect_test.go files have been updated to include base64 encoding and decoding for flash messages stored in cookies.

Changes

File(s) Change Summary
ctx.go Added parseCookieValue and validCookieValueByte methods to validate cookie characters per RFC 6265; updated Cookies method to use parsing.
ctx_test.go Updated Test_Ctx_Cookies with new test cases for cookies with commas, quotes, and backslashes; changed default value for unknown cookies to empty string.
middleware/keyauth/keyauth_test.go Updated CorrectKey constant to remove backslash from the expected API key format.
redirect.go Introduced base64 encoding and decoding for flash messages in cookies; updated parseAndClearFlashMessages and processFlashMessages methods.
redirect_test.go Modified flash message handling in tests to include base64 encoding/decoding; updated cookie retrieval and unmarshalling process.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Ctx as DefaultCtx (Cookies)
    participant Parser as parseCookieValue
    participant Validator as validCookieValueByte

    Client->>Ctx: Send request with Cookie header
    Ctx->>Parser: Call parseCookieValue(rawValue)
    loop For each character in rawValue
        Parser->>Validator: Validate character
        Validator-->>Parser: Return validity
    end
    Parser-->>Ctx: Return parsedValue
    Ctx-->>Client: Return cookie with parsedValue
Loading
sequenceDiagram
    participant Client as Client
    participant Redirect as Redirect
    participant Flash as Flash Messages

    Client->>Redirect: Request with Flash cookie
    Redirect->>Flash: Retrieve cookie value
    Flash->>Redirect: Check if cookie value is empty
    alt Not empty
        Flash->>Redirect: Decode base64 cookie value
        Redirect->>Flash: Unmarshal decoded value
    end
    Redirect-->>Client: Return flash messages
Loading

Poem

I hopped through lines of code today,
Parsing cookies in a sprightly way.
Valid bytes dance, invalid ones flee,
In clean cookie lands, I'm wild and free! 🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d32ffa8 and 541c99c.

📒 Files selected for processing (1)
  • redirect_test.go (15 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • redirect_test.go

Note

🎁 Summarized by CodeRabbit Free

Your organization has reached its limit of developer seats under the Pro Plan. For new users, CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please add seats to your subscription by visiting https://app.coderabbit.ai/login.If you believe this is a mistake and have available seats, please assign one to the pull request author through the subscription management page using the link above.

🪧 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.
    • Generate unit testing code 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 testing code 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 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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@gaby gaby requested a review from Copilot March 29, 2025 17:49
@gaby gaby added this to v3 Mar 29, 2025
@gaby gaby moved this to In Progress in v3 Mar 29, 2025
Copy link
Contributor

@Copilot 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 implements cookie value sanitization in accordance with RFC 6265 standards for cookie values by removing invalid characters (double quotes, semicolons, and backslashes) while allowing commas.

  • Implements a new helper function in ctx.go for sanitizing cookie values.
  • Updates test cases in both ctx_test.go and middleware/keyauth/keyauth_test.go to verify correct sanitization behavior.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
middleware/keyauth/keyauth_test.go Updates the expected cookie key to ensure it no longer contains disallowed chars.
ctx_test.go Adds test cases for sanitization of cookies with quotes, semicolons, and backslashes.
ctx.go Introduces cookie value sanitization and logs warnings on encountering invalid bytes.

@gaby gaby added this to the v3 milestone Mar 29, 2025
@gaby
Copy link
Member

gaby commented Mar 29, 2025

@c00kie17 csrf middleware may need to be updated?

@gaby gaby changed the title 🩹 Fix: Implement RFC 6265 Cookie Value Sanitization 🩹 fix: Implement RFC 6265 Cookie Value Sanitization Apr 1, 2025
@c00kie17
Copy link
Author

c00kie17 commented Apr 1, 2025

Im not sure how you want to handle the raw binary on headers, the current tests are failing due to that, looks like there is a redirectionMsg binary message that is being set on cookies, This will be rejected by the logic from net/http

We can convert them to base64 before storing so they are RFC 6265 compliant

@gaby
Copy link
Member

gaby commented Apr 9, 2025

@c00kie17 Where are we with this PR? Thanks!

@c00kie17
Copy link
Author

sorry for the delay, Ive updated the flash messages to be base64 encoded and decoded so that the cookie parser does not reject the the flash message as byte values

Copy link

codecov bot commented Apr 13, 2025

Codecov Report

Attention: Patch coverage is 90.62500% with 3 lines in your changes missing coverage. Please review.

Project coverage is 84.01%. Comparing base (b3e8486) to head (d32ffa8).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
ctx.go 85.71% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3379      +/-   ##
==========================================
+ Coverage   83.87%   84.01%   +0.13%     
==========================================
  Files         119      119              
  Lines       11892    11921      +29     
==========================================
+ Hits         9974    10015      +41     
+ Misses       1488     1479       -9     
+ Partials      430      427       -3     
Flag Coverage Δ
unittests 84.01% <90.62%> (+0.13%) ⬆️

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.

@ReneWerner87
Copy link
Member

@c00kie17 sorry for the late message
why are we putting this in fiber and not in fasthttp? wouldn't that help everyone if it was sanitized in fasthttp ?

@gaby
Copy link
Member

gaby commented May 13, 2025

@c00kie17 sorry for the late message why are we putting this in fiber and not in fasthttp? wouldn't that help everyone if it was sanitized in fasthttp ?

I was wondering that too, this should go in fasthttp, that way we inherit the fix

@efectn
Copy link
Member

efectn commented May 15, 2025

@c00kie17 sorry for the late message why are we putting this in fiber and not in fasthttp? wouldn't that help everyone if it was sanitized in fasthttp ?

I agree. This RFC check belongs to http server side, not framework. I think this PR should be opened in fasthttp repository for convenience

cookieValue := c.Cookies(FlashCookieName)
require.NotEmpty(t, cookieValue)

decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think hex is faster for this stuff as flash messages are mostly small.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: In Progress
Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: There is something weird with Fiber and the usage of Http lib for testing.
4 participants