Skip to content

🧹 chore: Return error during EncryptCookie failure#3842

Merged
ReneWerner87 merged 4 commits intomainfrom
improve-test-coverage-for-limiter-middleware
Nov 8, 2025
Merged

🧹 chore: Return error during EncryptCookie failure#3842
ReneWerner87 merged 4 commits intomainfrom
improve-test-coverage-for-limiter-middleware

Conversation

@gaby
Copy link
Member

@gaby gaby commented Nov 5, 2025

Summary

  • Return error instead of throwing panic() during EncryptCookie middleware failure

Copilot AI review requested due to automatic review settings November 5, 2025 14:11
@gaby gaby requested a review from a team as a code owner November 5, 2025 14:11
@gemini-code-assist
Copy link
Contributor

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 refines the error handling mechanism within the encryptcookie middleware. Previously, an unhandled encryption error would lead to a program panic. The updated implementation now returns these errors, enabling the Fiber application's custom error handler to intercept and process them. This change improves the robustness and predictability of the middleware, complemented by a new dedicated test to ensure proper error propagation.

Highlights

  • Improved Error Handling: The encryptcookie middleware now gracefully handles encryption failures by returning an error instead of causing a panic, allowing the application's error handler to manage these situations.
  • Enhanced Test Coverage: A new test case, Test_Middleware_EncryptionErrorPropagates, has been added to specifically verify that encryption errors are correctly propagated through the middleware and caught by the Fiber application's error handler.
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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 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

Replaced panic on cookie encryption failure with propagated error (using errors.Join to combine handler and encryption errors). Added tests to verify encryption error propagation and that encryption errors do not mask downstream errors.

Changes

Cohort / File(s) Summary
Cookie encryption middleware
middleware/encryptcookie/encryptcookie.go
Replaced panic(encErr) with return errors.Join(err, encErr) to propagate encryption errors alongside any prior handler error; added errors import.
Middleware tests
middleware/encryptcookie/encryptcookie_test.go
Added errors import and two tests: Test_Middleware_EncryptionErrorPropagates (verifies encryption error reaches Fiber error handler => 418) and Test_Middleware_EncryptionErrorDoesNotMaskNextError (verifies downstream error is preserved when encryption fails).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant Encryptor
    participant ErrorHandler

    rect rgb(220, 220, 230)
    Note over Middleware,Client: Previous behavior (panic)
    Client->>Middleware: Request with response cookie
    Middleware->>Encryptor: Encrypt cookie
    Encryptor-->>Middleware: encErr
    Middleware->>Middleware: panic(encErr)
    Middleware-X Client: execution terminated
    end

    rect rgb(220, 230, 220)
    Note over Middleware,ErrorHandler: New behavior (propagate & join)
    Client->>Middleware: Request with response cookie
    Middleware->>Encryptor: Encrypt cookie
    Encryptor-->>Middleware: encErr
    Middleware->>ErrorHandler: return errors.Join(handlerErr?, encErr)
    ErrorHandler->>Client: HTTP error response (e.g., 418) with combined error info
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Small code change in middleware but alters error propagation semantics (use errors.Join).
  • Two new tests exercising error propagation and masking interactions.
  • Review attention points:
    • Correctness of errors.Join usage and nil-handling when handler error is absent.
    • Test assertions for preserved/combined error values and HTTP status expectations.

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐇 I hopped through code with careful paws,
No panic squeal, just joined-up cause.
When cookies trip and errors meet,
I bundle them and keep things neat.
Tiny hop — a graceful fix, applause! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description is minimal and lacks required template sections like Changes introduced, Type of change, and Checklist items. Expand the description to follow the template: add specific changes introduced, select appropriate change type (Code consistency or Enhancement), complete the checklist items, and detail any testing done.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title directly aligns with the main change: replacing panic() with error return in EncryptCookie middleware failure handling.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch improve-test-coverage-for-limiter-middleware

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.

@gaby gaby changed the title Revert limiter manager internal tests 🧹 refactor: Return error during EncryptCookie failure Nov 5, 2025
@gemini-code-assist
Copy link
Contributor

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 refines the error handling mechanism within the encryptcookie middleware. Previously, an encryption failure would lead to a program panic; now, it gracefully returns an error, enabling the application to handle such scenarios more effectively. A corresponding test case has been introduced to ensure this error propagation works as intended. Disclaimer: The pull request title and description mention reverting 'limiter manager internal tests', which contradicts the actual changes observed in the provided patch files related to the encryptcookie middleware.

Highlights

  • Error Handling Improvement: The encryptcookie middleware now returns encryption errors instead of causing a panic, allowing for more robust error management within the application.
  • New Test Case: A new test, Test_Middleware_EncryptionErrorPropagates, has been added to verify that encryption errors are correctly propagated and handled by the Fiber application's error handler.
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.

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 error handling in the encryptcookie middleware by replacing a panic with proper error propagation when cookie encryption fails.

  • Replaced panic(encErr) with return encErr in the encryption error path
  • Added comprehensive test coverage to verify error propagation through Fiber's error handler

Reviewed Changes

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

File Description
middleware/encryptcookie/encryptcookie.go Changed encryption error handling from panic to returning error
middleware/encryptcookie/encryptcookie_test.go Added test to verify encryption errors propagate correctly to error handler
Comments suppressed due to low confidence (1)

middleware/encryptcookie/encryptcookie.go:54

  • When an encryption error occurs (line 45), the middleware returns encErr but discards the error from c.Next() stored in err (line 34). This means if both the handler and encryption fail, only the encryption error is returned. Consider returning both errors or at least logging the original error before returning the encryption error.
		err := c.Next()

		// Encrypt response cookies
		for key := range c.Response().Header.Cookies() {
			keyString := string(key)
			if !isDisabled(keyString, cfg.Except) {
				cookieValue := fasthttp.Cookie{}
				cookieValue.SetKeyBytes(key)
				if c.Response().Header.Cookie(&cookieValue) {
					encryptedValue, encErr := cfg.Encryptor(keyString, string(cookieValue.Value()), cfg.Key)
					if encErr != nil {
						return encErr
					}

					cookieValue.SetValue(encryptedValue)
					c.Response().Header.SetCookie(&cookieValue)
				}
			}
		}

		return err

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 significantly improves error handling within the encryptcookie middleware by replacing a panic with a returned error when cookie encryption fails. This change enhances server stability by preventing crashes. A corresponding test has been added to validate this new behavior. However, the pull request title and description are inaccurate and do not describe the changes made; they should be updated to reflect the work done on the encryptcookie middleware. I have also included a comment regarding a potential for error information to be lost in a specific edge case.

@codecov
Copy link

codecov bot commented Nov 5, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.10%. Comparing base (7ce1722) to head (9989903).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3842      +/-   ##
==========================================
- Coverage   92.14%   92.10%   -0.05%     
==========================================
  Files         115      115              
  Lines        9754     9754              
==========================================
- Hits         8988     8984       -4     
- Misses        486      490       +4     
  Partials      280      280              
Flag Coverage Δ
unittests 92.10% <100.00%> (-0.05%) ⬇️

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

This pull request is a good refactoring that replaces a panic with a returned error in the encryptcookie middleware, making it more robust. The new test case validates this change effectively.

However, I've identified a potential issue where an error from the handler chain could be hidden by a subsequent cookie encryption error. I've left a comment with a suggested refactoring to address this by prioritizing the handler error. I've also suggested an additional test case to cover this scenario.

Also, the pull request description seems to be from a different change and should be updated to reflect the actual changes in this PR.

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 ff04aa0 and ae302a5.

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

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Apply formatting using gofumpt (Make target: format)
Optimize struct field alignment using betteralign (Make target: betteralign)
Modernize code using gopls modernize (Make target: modernize)

Files:

  • middleware/encryptcookie/encryptcookie.go
  • middleware/encryptcookie/encryptcookie_test.go
🧠 Learnings (7)
📓 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-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: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:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
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: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:19:52.418Z
Learning: In the Fiber codebase, the linter does not allow `require` assertions from within HTTP handlers (including net/http-style handlers). Use `t.Fatalf`, `t.Errorf`, or similar `testing.T` methods for error handling inside handler functions instead.
📚 Learning: 2024-07-02T13:29:56.992Z
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.

Applied to files:

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

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
📚 Learning: 2025-10-16T07:19:52.418Z
Learnt from: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:19:52.418Z
Learning: In the Fiber codebase, the linter does not allow `require` assertions from within HTTP handlers (including net/http-style handlers). Use `t.Fatalf`, `t.Errorf`, or similar `testing.T` methods for error handling inside handler functions instead.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
📚 Learning: 2024-07-26T21:00:12.902Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Applied to files:

  • middleware/encryptcookie/encryptcookie_test.go
🧬 Code graph analysis (1)
middleware/encryptcookie/encryptcookie_test.go (5)
middleware/encryptcookie/utils.go (1)
  • GenerateKey (104-116)
middleware/encryptcookie/encryptcookie.go (1)
  • New (9-56)
app.go (3)
  • New (521-634)
  • Config (113-424)
  • ErrorHandler (59-59)
middleware/encryptcookie/config.go (1)
  • Config (8-35)
constants.go (1)
  • StatusTeapot (91-91)
🪛 GitHub Actions: golangci-lint
middleware/encryptcookie/encryptcookie_test.go

[error] 114-114: golangci-lint: unused-parameter: parameter 'key' seems to be unused, consider removing or renaming it as _ (revive)

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

[failure] 114-114:
unused-parameter: parameter 'key' seems to be unused, consider removing or renaming it as _ (revive)

⏰ 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-13)
  • GitHub Check: repeated
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: Compare
🔇 Additional comments (2)
middleware/encryptcookie/encryptcookie.go (1)

45-45: Excellent improvement to error handling.

Changing from panic(encErr) to return encErr is the correct approach. This enables graceful error handling through Fiber's error handler instead of crashing the application, making the middleware more robust and production-ready.

middleware/encryptcookie/encryptcookie_test.go (1)

6-6: LGTM!

The errors import is appropriately added for the new test.

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: 34462e6 Previous: ff04aa0 Ratio
BenchmarkDecodeitem-4_middleware_cache 343.1 ns/op 201.12 MB/s 0 B/op 0 allocs/op 186.5 ns/op 369.91 MB/s 0 B/op 0 allocs/op 1.84
BenchmarkDecodeitem-4_middleware_cache - ns/op 343.1 ns/op 186.5 ns/op 1.84

This comment was automatically generated by workflow using github-action-benchmark.

@gaby gaby changed the title 🧹 refactor: Return error during EncryptCookie failure 🧹 chore: Return error during EncryptCookie failure Nov 6, 2025
@ReneWerner87 ReneWerner87 added v3 and removed v3 labels Nov 8, 2025
@ReneWerner87 ReneWerner87 merged commit 71841e4 into main Nov 8, 2025
16 checks passed
@ReneWerner87 ReneWerner87 deleted the improve-test-coverage-for-limiter-middleware branch November 8, 2025 14:54
@ReneWerner87 ReneWerner87 added this to the v3 milestone Nov 8, 2025
@ReneWerner87 ReneWerner87 added this to v3 Nov 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants