Skip to content

Conversation

@dogukanoksuz
Copy link

Description

Any non-encrypted cookie that doesn't set in except list for EncryptCookie middleware crashes the application.

Fixes #3954

Changes introduced

Changes are non-breaking

@dogukanoksuz dogukanoksuz requested a review from a team as a code owner December 22, 2025 11:26
@dogukanoksuz dogukanoksuz requested review from ReneWerner87, Copilot, efectn, gaby and sixcolors and removed request for Copilot December 22, 2025 11:26
@welcome
Copy link

welcome bot commented Dec 22, 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

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @dogukanoksuz, 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 resolves a panic condition within the EncryptCookie middleware. Previously, if a cookie that was not explicitly excluded from encryption failed decryption, the application would crash. The fix gracefully handles such scenarios by clearing the cookie's value rather than causing a panic, thereby improving the robustness and stability of the middleware.

Highlights

  • Bug Fix: Addresses a critical bug in the EncryptCookie middleware where the application would panic if it encountered a non-encrypted cookie that was not in the except list and failed decryption.
  • Error Handling Improvement: Modifies the error handling logic for cookie decryption. Instead of attempting to delete the entire cookie header when decryption fails, the middleware now sets the problematic cookie's value to an empty string.
  • Non-Breaking Change: The introduced changes are non-breaking, ensuring compatibility with existing implementations.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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.

@ReneWerner87 ReneWerner87 added this to v3 Dec 22, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Dec 22, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 22, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

On decryption error, the encryptcookie middleware now keeps the cookie key present but sets its value to an empty string in the request/response instead of removing the cookie; successful decryption behavior is unchanged. A test was added to assert no panic for invalid cookie values.

Changes

Cohort / File(s) Summary
Cookie error handling
middleware/encryptcookie/encryptcookie.go
On decryption failure, replace deleting the cookie with setting the cookie value to an empty byte slice (preserve key, empty value) so the cookie remains present but cleared.
Tests
middleware/encryptcookie/encryptcookie_test.go
Add Test_Middleware_Decrypt_Invalid_Cookie_Does_Not_Panic to ensure invalid/unencrypted cookie values do not panic and result in a cleared (empty) cookie value.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Single logical change with one added test.
  • Review attention:
    • Verify downstream handlers' semantics when cookie is present-but-empty vs absent.
    • Ensure Set-Cookie header formatting and duplication are correct.
    • Confirm no regressions for cookies with unusual names/characters (e.g., containing ':').

Possibly related PRs

Suggested reviewers

  • gaby
  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 I nibbled headers in the night,
Found a crumb I could not bite.
Kept the key and emptied the treat,
No more panics — quiet and neat.
Hooray for calm servers and extra carrots 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ❓ Inconclusive The description identifies the problem and links to issue #3954, but lacks detail on the specific fix implemented and omits most checklist items from the template. Expand the description to explain the fix (changing from DelCookieBytes to SetCookie with empty value on decryption error) and complete relevant checklist items like test updates and breaking change confirmation.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the core issue: fixing a panic in the EncryptCookie middleware, matching the bug reported in #3954 and the changes made.
Linked Issues check ✅ Passed The code changes successfully address the core requirement from #3954: preventing the middleware from panicking when processing non-encrypted cookies by handling decryption errors gracefully instead of crashing.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the EncryptCookie middleware panic issue; test additions validate the fix and no unrelated modifications are present.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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 addresses a panic in the EncryptCookie middleware that occurs when it encounters a non-encrypted cookie. The fix replaces the call to c.Request().Header.DelCookieBytes(key), which was causing the panic, with c.Request().Header.SetCookie(string(key), ""). This change effectively neutralizes invalid cookies by setting their value to an empty string, preventing the application crash. The change is simple, effective, and correctly works around the underlying issue. I have provided one suggestion for a minor performance improvement, but the current change is correct and resolves the reported issue.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
middleware/encryptcookie/encryptcookie.go (1)

24-34: Add test coverage for cookies with special characters in the name.

The fix correctly replaces DelCookieBytes with SetCookie(string(key), "") on decryption failure, which resolves the panic when processing cookies with special characters like colons. The behavioral change—setting cookies to empty strings instead of deleting them—is partially tested.

However, the test suite lacks coverage for the specific scenario that triggered the panic: cookie names containing special characters (e.g., "sidebar:state"). Add a test case that sets a request cookie with special characters in the name and an invalid encrypted value to verify the middleware handles the error gracefully without panicking.

🧹 Nitpick comments (1)
middleware/encryptcookie/encryptcookie.go (1)

29-29: Use existing keyString variable to avoid redundant conversion.

Line 25 already converts the key to a string (keyString := string(key)). Consider using keyString here instead of converting again:

🔎 Proposed refactor
-					c.Request().Header.SetCookie(string(key), "")
+					c.Request().Header.SetCookie(keyString, "")
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 680f3c3 and 58db8e5.

📒 Files selected for processing (1)
  • middleware/encryptcookie/encryptcookie.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

Prefer github.com/gofiber/utils/v2 helpers (for example, utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Files:

  • middleware/encryptcookie/encryptcookie.go
🧠 Learnings (5)
📓 Common learnings
Learnt from: gaby
Repo: gofiber/fiber PR: 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.
Learnt from: gaby
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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: gaby
Repo: gofiber/fiber PR: 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.
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-07-01T03:44:03.672Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-09-25T15:57:10.221Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
🧬 Code graph analysis (1)
middleware/encryptcookie/encryptcookie.go (1)
client/request.go (2)
  • Request (46-73)
  • Header (708-710)

@gaby gaby changed the title fix: encryptcookie middleware panic #3954 fix: EncryptCookie middleware panic Dec 22, 2025
@gaby gaby changed the title fix: EncryptCookie middleware panic 🐛 bug: Fix EncryptCookie middleware panic Dec 22, 2025
@codecov
Copy link

codecov bot commented Dec 22, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.56%. Comparing base (680f3c3) to head (4f575ba).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3958      +/-   ##
==========================================
- Coverage   91.62%   91.56%   -0.06%     
==========================================
  Files         119      119              
  Lines       10187    10187              
==========================================
- Hits         9334     9328       -6     
- Misses        540      545       +5     
- Partials      313      314       +1     
Flag Coverage Δ
unittests 91.56% <100.00%> (-0.06%) ⬇️

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.

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Copilot AI review requested due to automatic review settings December 22, 2025 12:36
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 fixes a panic in the EncryptCookie middleware that occurred when non-encrypted cookies (not in the exception list) were encountered during request processing. The fix changes the error handling behavior from attempting to delete the cookie to setting it to an empty value.

  • Replaces DelCookieBytes with SetCookieBytes to safely handle decryption failures
  • Prevents application crashes when encountering invalid or unencrypted cookies

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
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

📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af8ad8a and 1043a36.

📒 Files selected for processing (1)
  • middleware/encryptcookie/encryptcookie.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

Prefer github.com/gofiber/utils/v2 helpers (for example, utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Files:

  • middleware/encryptcookie/encryptcookie.go
🧠 Learnings (5)
📓 Common learnings
Learnt from: gaby
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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.
Learnt from: gaby
Repo: gofiber/fiber PR: 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.
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-07-01T03:44:03.672Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-09-25T15:57:10.221Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
🪛 GitHub Actions: Modernize Lint
middleware/encryptcookie/encryptcookie.go

[error] 29-29: Go compile error: c.Request().Header.SetCookieBytes undefined (type fasthttp.RequestHeader has no field or method SetCookieBytes).

🪛 GitHub Actions: Run govulncheck
middleware/encryptcookie/encryptcookie.go

[error] 29-29: govulncheck: loading packages: There are errors with the provided package patterns: /home/runner/work/fiber/fiber/middleware/encryptcookie/encryptcookie.go:29:25: c.Request().Header.SetCookieBytes undefined (type fasthttp.RequestHeader has no field or method SetCookieBytes)

🪛 GitHub Check: govulncheck-check
middleware/encryptcookie/encryptcookie.go

[failure] 29-29:
c.Request().Header.SetCookieBytes undefined (type fasthttp.RequestHeader has no field or method SetCookieBytes)

🪛 GitHub Check: modernize
middleware/encryptcookie/encryptcookie.go

[failure] 29-29:
c.Request().Header.SetCookieBytes undefined (type fasthttp.RequestHeader has no field or method SetCookieBytes)

🪛 GitHub Check: unit (1.25.x, ubuntu-latest)
middleware/encryptcookie/encryptcookie.go

[failure] 29-29:
c.Request().Header.SetCookieBytes undefined (type fasthttp.RequestHeader has no field or method SetCookieBytes)


[failure] 29-29:
c.Request().Header.SetCookieBytes undefined (type fasthttp.RequestHeader has no field or method SetCookieBytes)

⏰ 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). (4)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: repeated
  • GitHub Check: lint
  • GitHub Check: Compare

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 0

🧹 Nitpick comments (3)
middleware/encryptcookie/encryptcookie.go (3)

29-29: Reuse keyString to avoid duplicate string conversion.

Line 25 already converts key to keyString, but line 29 performs the conversion again with string(key). Reuse the existing variable for better efficiency.

🔎 Proposed fix
-					c.Request().Header.SetCookie(string(key), "")
+					c.Request().Header.SetCookie(keyString, "")

27-29: Consider logging or tracking decryption failures for security and debugging.

Decryption errors are currently silently ignored, which could hide important issues such as cookie tampering attempts, key rotation problems, or malformed cookies. Unlike encryption errors (lines 47-48), which are properly returned, decryption failures provide no visibility.

Consider adding at minimum debug-level logging when decryption fails, or expose a metric/counter for monitoring. This would aid in debugging and security monitoring without breaking the current error handling flow.

Example implementation (add logging):

decryptedValue, err := cfg.Decryptor(keyString, string(value), cfg.Key)
if err != nil {
    // Log decryption failure for debugging/security monitoring
    // Example: log.Debug().Err(err).Str("cookie", keyString).Msg("cookie decryption failed")
    c.Request().Header.SetCookie(keyString, "")
} else {
    c.Request().Header.SetCookie(keyString, decryptedValue)
}

31-31: Apply the same optimization here: reuse keyString.

Similar to line 29, this line also performs a duplicate string conversion. For consistency and efficiency, use keyString here as well.

🔎 Proposed fix
-					c.Request().Header.SetCookie(string(key), decryptedValue)
+					c.Request().Header.SetCookie(keyString, decryptedValue)
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1043a36 and b475dc9.

📒 Files selected for processing (1)
  • middleware/encryptcookie/encryptcookie.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

Prefer github.com/gofiber/utils/v2 helpers (for example, utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Files:

  • middleware/encryptcookie/encryptcookie.go
🧠 Learnings (5)
📓 Common learnings
Learnt from: gaby
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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.
Learnt from: gaby
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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: gaby
Repo: gofiber/fiber PR: 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.
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-07-01T03:44:03.672Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-09-25T15:57:10.221Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie.go
🧬 Code graph analysis (1)
middleware/encryptcookie/encryptcookie.go (1)
client/request.go (2)
  • Request (46-73)
  • Header (708-710)
⏰ 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). (5)
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: lint
  • GitHub Check: Compare
🔇 Additional comments (1)
middleware/encryptcookie/encryptcookie.go (1)

28-32: Consider reusing the keyString variable to avoid redundant string conversion.

On line 29, string(key) is converted to a string for the second time; keyString is already created on line 25 and should be reused here.

Also note that setting failed decryption cookies to an empty string (rather than removing them) is intentional behavior per the middleware design—as confirmed by the comprehensive test coverage in encryptcookie_test.go, which validates that invalid/malformed cookies result in empty values.

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

🧹 Nitpick comments (1)
middleware/encryptcookie/encryptcookie_test.go (1)

110-140: LGTM! Test correctly validates the panic fix.

The test properly verifies that invalid/unencrypted cookies don't crash the middleware and that the cookie value is cleared as expected. The test follows coding guidelines by calling t.Parallel() at the start.

Optional: Minor improvements to error handling and test robustness

Consider these small refinements:

  1. Handle the error from resp.Body.Read instead of ignoring it:
-	body := make([]byte, 64)
-	n, _ := resp.Body.Read(body)
-	require.Equal(t, "value=", string(body[:n]))
+	body, err := io.ReadAll(resp.Body)
+	require.NoError(t, err)
+	require.Equal(t, "value=", string(body))

Add io to the imports if using this approach.

  1. Optionally, test with the specific cookie name from issue #3954 to demonstrate the exact scenario is fixed:
 	req.AddCookie(&http.Cookie{
-		Name:  "test",
+		Name:  "sidebar:state",
 		Value: "plaintext-unencrypted-value",
 	})

And update the handler to read the corresponding cookie:

 	app.Get("/", func(c fiber.Ctx) error {
-		return c.SendString("value=" + c.Cookies("test"))
+		return c.SendString("value=" + c.Cookies("sidebar:state"))
 	})
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b475dc9 and 4f575ba.

📒 Files selected for processing (1)
  • middleware/encryptcookie/encryptcookie_test.go
🧰 Additional context used
📓 Path-based instructions (2)
**/*_test.go

📄 CodeRabbit inference engine (AGENTS.md)

When adding Go tests, always invoke t.Parallel() at the start of each test and subtest to maximize concurrency

Files:

  • middleware/encryptcookie/encryptcookie_test.go
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

Prefer github.com/gofiber/utils/v2 helpers (for example, utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Files:

  • middleware/encryptcookie/encryptcookie_test.go
🧠 Learnings (4)
📓 Common learnings
Learnt from: gaby
Repo: gofiber/fiber PR: 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.
Learnt from: gaby
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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
Repo: gofiber/fiber PR: 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: gaby
Repo: gofiber/fiber PR: 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.
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
📚 Learning: 2024-07-01T03:44:03.672Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
🧬 Code graph analysis (1)
middleware/encryptcookie/encryptcookie_test.go (2)
middleware/encryptcookie/utils.go (1)
  • GenerateKey (98-110)
middleware/encryptcookie/encryptcookie.go (1)
  • New (12-59)

app := fiber.New()

app.Use(New(Config{
Key: testKey,
Copy link
Member

Choose a reason for hiding this comment

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

This should be "sidebar:state"

Copy link
Author

Choose a reason for hiding this comment

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

the mentioned problem has no relation with sidebar:state key. it is happening on every unexpected and non encrypted cookie.

@gaby
Copy link
Member

gaby commented Dec 23, 2025

While this works, it also means we try to decrypt every cookie. Even the ones not encrypted.

@dogukanoksuz
Copy link
Author

dogukanoksuz commented Dec 24, 2025

@gaby maybe completely changing the middleware solves the root cause. middleware by itself tries every single cookie that exists in request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: EncryptCookie middleware panics the app with index out of range error

3 participants