Skip to content

🔥 feat: Add cookie name authentication for EncryptCookie middleware#3788

Merged
ReneWerner87 merged 4 commits intomainfrom
extend-config.encryptor-for-cookie-name
Oct 7, 2025
Merged

🔥 feat: Add cookie name authentication for EncryptCookie middleware#3788
ReneWerner87 merged 4 commits intomainfrom
extend-config.encryptor-for-cookie-name

Conversation

@gaby
Copy link
Member

@gaby gaby commented Oct 7, 2025

Summary

  • pass the cookie name into custom encryptor/decryptor hooks in the encryptcookie middleware
  • bind the cookie name into AES-GCM additional authenticated data to prevent cross-cookie reuse and document the updated signature

Fixes #3777

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 7, 2025

Walkthrough

Public Encryptor/Decryptor function signatures now include the cookie name as the first parameter. Middleware and utils were updated to pass and use the name (as AES‑GCM additional authenticated data). Tests and docs were adjusted to the new API and added a test rejecting swapped cookie names.

Changes

Cohort / File(s) Summary of Changes
Docs
docs/middleware/encryptcookie.md, docs/whats_new.md
Updated documentation to show new Encryptor/Decryptor signatures with name as first param and explained default helpers bind cookie name as AES‑GCM AAD.
Config API
middleware/encryptcookie/config.go
Changed exported Config.Encryptor and Config.Decryptor types to func(name, value, key string) (string, error).
Middleware
middleware/encryptcookie/encryptcookie.go
Adjusted calls to Encryptor/Decryptor to pass cookie name as first argument; preserved existing control flow for decrypt failures and response encryption.
Crypto utils
middleware/encryptcookie/utils.go
Updated EncryptCookie/DecryptCookie signatures to EncryptCookie(name, value, key string) / DecryptCookie(name, value, key string) and use []byte(name) as AES‑GCM associated data.
Tests
middleware/encryptcookie/encryptcookie_test.go
Updated test call sites and custom Config function literals to accept name; added Test_EncryptCookie_Rejects_Swapped_Names verifying decryption fails when cookie name is swapped.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant App as Fiber App
  participant EC as EncryptCookie Middleware
  note right of EC #E6F4EA: Cookie name passed as first arg\nand used as AES‑GCM AAD

  Client->>App: HTTP Request with Cookie(name, encryptedValue)
  App->>EC: Run encryptcookie middleware
  EC->>EC: Decryptor(name, encryptedValue, key)
  alt Decryption OK
    EC->>App: Set Cookie(name, plaintextValue)
  else Decryption fails
    EC->>App: Remove Cookie(name)
  end
  App-->>EC: Handler returns (may set response cookies)
  loop For each response cookie
    EC->>EC: Encryptor(name, plaintextValue, key)
    alt Encryption OK
      EC->>App: Set Cookie(name, encryptedValue)
    else Encryption fails
      EC->>App: Remove Cookie(name)
    end
  end
  App-->>Client: HTTP Response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

I nibbled the bytes with whiskered delight,
A name on the cookie to keep it tight.
Bind the crumb with care, decrypt with grace,
Swapped crumbs bounce out—no wrong place.
Hop—secure and snug, my code's in place. 🐇🍪

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The title accurately summarizes the primary change of adding cookie name–based authentication to the EncryptCookie middleware but includes an emoji prefix that counts as unnecessary noise according to the repository’s title guidelines. Please remove the emoji prefix and any other non-essential symbols so the title reads something like “feat: Add cookie name authentication for EncryptCookie middleware.”
Description Check ⚠️ Warning The description provides a brief summary and references the linked issue but does not follow the repository’s required template sections such as “Description,” “Changes introduced,” “Type of change,” or the detailed checklist, leaving out key information about documentation updates, migration guidance, and test coverage. Please expand the description to include all template headings—“Description,” “Changes introduced,” “Type of change,” and the checklist items—detailing documentation updates, changelog notes, migration guidance, and test adjustments.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues Check ✅ Passed The implementation binds the cookie name into AES-GCM’s additional authenticated data, updates all Encryptor/Decryptor signatures to include the name parameter, and adds tests to verify mismatched names fail, fully satisfying the coding objectives of issue #3777.
Out of Scope Changes Check ✅ Passed All changes are confined to the encryptcookie middleware, its tests, and related documentation; there are no unrelated modifications outside the scope of adding cookie name authentication.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch extend-config.encryptor-for-cookie-name

📜 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 4febf2a and 0d15d8c.

📒 Files selected for processing (1)
  • docs/whats_new.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/**

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Review and update the contents of the docs folder if necessary when modifying code

Files:

  • docs/whats_new.md
🧠 Learnings (1)
📓 Common learnings
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.
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: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.
⏰ 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: Compare
  • GitHub Check: unit (1.25.x, macos-13)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: repeated
  • GitHub Check: unit (1.25.x, windows-latest)

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

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 adds cookie name authentication to the encryptcookie middleware to prevent cross-cookie reuse by binding the cookie name into AES-GCM additional authenticated data. This enhances security by ensuring encrypted cookies cannot be swapped between different cookie names.

  • Updated function signatures to include cookie name parameter in encrypt/decrypt operations
  • Modified AES-GCM encryption to use cookie name as additional authenticated data
  • Added comprehensive test coverage for the new functionality

Reviewed Changes

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

Show a summary per file
File Description
middleware/encryptcookie/utils.go Added cookie name parameter to EncryptCookie and DecryptCookie functions and bound it to AES-GCM AAD
middleware/encryptcookie/config.go Updated Encryptor and Decryptor function signatures to include cookie name parameter
middleware/encryptcookie/encryptcookie.go Modified middleware to pass cookie names to encrypt/decrypt functions
middleware/encryptcookie/encryptcookie_test.go Updated all test calls and added new test for cross-cookie reuse prevention
docs/middleware/encryptcookie.md Updated documentation to reflect new function signatures

@gaby gaby added this to v3 Oct 7, 2025
@gaby gaby added this to the v3 milestone Oct 7, 2025
@gaby gaby moved this to In Progress in v3 Oct 7, 2025
@codecov
Copy link

codecov bot commented Oct 7, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.65%. Comparing base (6f81d52) to head (0d15d8c).
⚠️ Report is 132 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3788      +/-   ##
==========================================
- Coverage   91.67%   91.65%   -0.03%     
==========================================
  Files         113      113              
  Lines       11959    11959              
==========================================
- Hits        10964    10961       -3     
- Misses        731      733       +2     
- Partials      264      265       +1     
Flag Coverage Δ
unittests 91.65% <100.00%> (-0.03%) ⬇️

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 Add cookie name authentication for encryptcookie middleware 🔥 feat: Add cookie name authentication for EncryptCookie middleware Oct 7, 2025
@gaby gaby marked this pull request as ready for review October 7, 2025 04:41
@gaby gaby requested a review from a team as a code owner October 7, 2025 04:41
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: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6f81d52 and b803bff.

📒 Files selected for processing (5)
  • docs/middleware/encryptcookie.md (1 hunks)
  • middleware/encryptcookie/config.go (1 hunks)
  • middleware/encryptcookie/encryptcookie.go (2 hunks)
  • middleware/encryptcookie/encryptcookie_test.go (9 hunks)
  • middleware/encryptcookie/utils.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Format Go code using gofumpt (enforced via make format)
Ensure code passes golangci-lint checks (enforced via make lint)
Optimize struct field alignment using betteralign (enforced via make betteralign)
Modernize Go code using gopls modernize (enforced via make modernize)

Files:

  • middleware/encryptcookie/config.go
  • middleware/encryptcookie/encryptcookie_test.go
  • middleware/encryptcookie/encryptcookie.go
  • middleware/encryptcookie/utils.go
docs/**

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Review and update the contents of the docs folder if necessary when modifying code

Files:

  • docs/middleware/encryptcookie.md
🧠 Learnings (4)
📓 Common learnings
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.
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: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.
📚 Learning: 2024-10-08T19:06:06.583Z
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.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
  • middleware/encryptcookie/encryptcookie.go
📚 Learning: 2024-07-01T03:44:03.672Z
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.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
📚 Learning: 2024-07-01T03:33:22.283Z
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.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
🧬 Code graph analysis (1)
middleware/encryptcookie/encryptcookie_test.go (1)
middleware/encryptcookie/utils.go (3)
  • EncryptCookie (39-62)
  • DecryptCookie (65-99)
  • GenerateKey (104-116)
🪛 GitHub Actions: golangci-lint
middleware/encryptcookie/encryptcookie_test.go

[error] 252-252: golangci-lint: File is not properly formatted (gofumpt). Run 'gofumpt -w' to fix formatting.

🪛 GitHub Check: lint
middleware/encryptcookie/encryptcookie_test.go

[failure] 252-252:
File is not properly formatted (gofumpt)


[failure] 447-447:
File is not properly formatted (gofumpt)


[failure] 630-630:
File is not properly formatted (gofumpt)

⏰ 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). (2)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (14)
middleware/encryptcookie/utils.go (2)

39-61: LGTM! Cookie name correctly bound to ciphertext.

The implementation correctly uses the cookie name as additional authenticated data (AAD) in AES-GCM. This prevents cross-cookie reuse attacks by cryptographically binding the ciphertext to its intended cookie name.


65-98: LGTM! Cookie name validation during decryption.

The implementation correctly validates the cookie name during decryption using GCM's AAD verification. Any attempt to use a ciphertext with a different cookie name will fail authentication.

middleware/encryptcookie/config.go (1)

17-22: LGTM! Public API updated to expose cookie name.

The function signatures for Encryptor and Decryptor now correctly include the cookie name as the first parameter, enabling custom implementations to perform their own validation.

docs/middleware/encryptcookie.md (1)

70-71: LGTM! Documentation accurately reflects API changes.

The function signatures are correctly documented with the cookie name as the first parameter for both Encryptor and Decryptor.

middleware/encryptcookie/encryptcookie.go (2)

24-24: LGTM! Decryptor correctly invoked with cookie name.

The middleware correctly passes the cookie name as the first parameter to the Decryptor function.


43-43: LGTM! Encryptor correctly invoked with cookie name.

The middleware correctly passes the cookie name as the first parameter to the Encryptor function.

middleware/encryptcookie/encryptcookie_test.go (8)

54-54: LGTM! Test updated with cookie name parameter.

The test correctly passes the cookie name as the first parameter to EncryptCookie.


65-65: LGTM! Test updated with cookie name parameter.

The test correctly passes the cookie name as the first parameter to DecryptCookie.


77-77: LGTM! Test updated with cookie name parameter.

The test correctly passes the cookie name as the first parameter to EncryptCookie.


84-84: LGTM! Test updated with cookie name parameter.

The test correctly passes the cookie name as the first parameter to DecryptCookie.


91-91: LGTM! Test updated with cookie name parameter.

The test correctly passes the cookie name as the first parameter to DecryptCookie.


147-147: LGTM! Test updated with cookie name parameter.

The test correctly passes the cookie name as the first parameter to DecryptCookie.


159-173: Excellent security test! Validates cross-cookie reuse prevention.

This test correctly verifies that an encrypted cookie value cannot be decrypted using a different cookie name, confirming the security property introduced by this PR.


240-240: LGTM! Test updated with cookie name parameter.

The test correctly passes the cookie name as the first parameter to DecryptCookie.

@ReneWerner87
Copy link
Member

@gaby pls extend the what´s new.md
and I think we need to extend the migration script https://github.com/gofiber/cli

@gaby
Copy link
Member Author

gaby commented Oct 7, 2025

@gaby pls extend the what´s new.md and I think we need to extend the migration script https://github.com/gofiber/cli

@ReneWerner87 Docs updated

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)
docs/middleware/encryptcookie.md (1)

77-79: Clarify the payload parameter name in the new bullet list.

The second bullet labels the argument as string, which doesn’t match any parameter name and reads like a type placeholder. Naming it (e.g. payload string or explicitly mentioning decryptedString/encryptedString) will keep the docs aligned with the actual signature. A quick tweak like the diff below would remove the ambiguity:

-- `string`: The cookie payload. `EncryptCookie` accepts the decrypted value and returns ciphertext, while `DecryptCookie` receives ciphertext and must return the decrypted value.
+- `payload string`: The cookie payload. `EncryptCookie` accepts the decrypted value and returns ciphertext, while `DecryptCookie` receives ciphertext and must return the decrypted value.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3a03ab and 4febf2a.

📒 Files selected for processing (2)
  • docs/middleware/encryptcookie.md (1 hunks)
  • docs/whats_new.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/whats_new.md
🧰 Additional context used
📓 Path-based instructions (1)
docs/**

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Review and update the contents of the docs folder if necessary when modifying code

Files:

  • docs/middleware/encryptcookie.md
🧠 Learnings (1)
📓 Common learnings
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.
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: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.
⏰ 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: Compare
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: repeated

@ReneWerner87 ReneWerner87 merged commit 2ebd143 into main Oct 7, 2025
15 checks passed
@ReneWerner87 ReneWerner87 deleted the extend-config.encryptor-for-cookie-name branch October 7, 2025 11:59
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Oct 7, 2025
@ReneWerner87
Copy link
Member

@gaby can you create the migrator

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

Labels

codex ✏️ Feature 📜 RFC Compliance Feature, implementation, or contribution adheres to relevant RFC standards. v3

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

📝 [Proposal]: Additional Cookie Validation

3 participants