🐛 bug: harden session middleware lifecycle and error handling#4059
🐛 bug: harden session middleware lifecycle and error handling#4059
Conversation
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Summary of ChangesHello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the reliability and resource management of the session middleware. It focuses on preventing session object leaks and application panics by ensuring that session objects are always properly released back to their pool, even when errors occur during initialization or session lifecycle events. The changes centralize session finalization logic and harden error paths within the session store, leading to a more stable and predictable session management system. Highlights
🧠 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. Changelog
Activity
Using Gemini Code AssistThe 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
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 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
|
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #4059 +/- ##
==========================================
+ Coverage 91.18% 91.29% +0.11%
==========================================
Files 129 129
Lines 12749 12788 +39
==========================================
+ Hits 11625 11675 +50
+ Misses 709 701 -8
+ Partials 415 412 -3
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Code Review
This pull request significantly hardens the session middleware by improving error handling and fixing several potential resource leaks. While the changes are well-implemented, replacing panics with proper error propagation and ensuring session objects are always released back to the pool, a high-severity issue remains. The middleware instance is returned to the pool while a reference to it still exists in the request context's locals, which can lead to cross-request session data leakage if other middlewares access the session after the main handler chain has completed. It is recommended to clear the context local reference before releasing the middleware instance. Additionally, consider improving context propagation during session destruction in middleware/session/store.go.
There was a problem hiding this comment.
Pull request overview
This PR hardens the session middleware/store lifecycle to prevent pooled Session/Middleware objects from leaking across request/error paths, and adds regression tests around those paths.
Changes:
- Convert
(*Middleware).initializeto return an error and route init failures through the configuredErrorHandler/DefaultErrorHandlerinstead of panicking. - Ensure sessions are always released back to the pool on terminal/error paths (
finalizeSession, extraRelease()calls in store error branches). - Add regression tests for initialization, context-local cleanup, and store expiry/destroy behaviors.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| middleware/session/middleware.go | Switch init to error-return and add finalizeSession() to guarantee session release and locals cleanup. |
| middleware/session/session.go | Add a stored context (gctx) so Destroy() can honor GetByID’s context; clear it on release. |
| middleware/session/store.go | Release sessions on absolute-expiry reset failure; ensure GetByID releases sessions on expiry destroy path and uses gctx. |
| middleware/session/middleware_test.go | Add tests for locals cleanup, init error handling, and finalize lifecycle behavior. |
| middleware/session/store_test.go | Add tests for expiry/reset failure release, expiry destroy release, and destroy context propagation. |
Updated session middleware to store context in Fiber.
There was a problem hiding this comment.
⚠️ 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: a5953ea | Previous: 92ada8a | Ratio |
|---|---|---|---|
BenchmarkDecoderedirectionMsgs - MB/s |
118.68 MB/s |
47.86 MB/s |
2.48 |
This comment was automatically generated by workflow using github-action-benchmark.
|
…anics Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
🐛 bug: harden session middleware lifecycle and error handling
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request significantly hardens the session middleware by improving its lifecycle management and error handling. Key changes include preventing session object leaks by ensuring sessions are always returned to the pool, handling middleware initialization failures gracefully instead of panicking, and adding robust validation for session IDs as a security measure. The introduction of finalizeSession clarifies the session cleanup logic and fixes a potential resource leak when a session was destroyed. The changes from panicking to returning errors in initialize and acquire* functions make the middleware more robust and align better with Go's error handling practices. The pull request is well-structured and includes a comprehensive set of regression tests that cover the new behaviors and protect against future regressions. Overall, these are excellent improvements that enhance the stability and security of the session middleware.
There was a problem hiding this comment.
Code Review
This pull request significantly hardens the session middleware by improving its lifecycle management and error handling. Key improvements include replacing panics with returned errors in initialization paths, ensuring session objects are consistently released to prevent leaks (especially on error paths), and adding validation for session IDs as a security measure. The introduction of finalizeSession centralizes cleanup logic, making it more robust. The added regression tests are comprehensive and cover the new behaviors well.
I've found a couple of minor opportunities for improvement to make the hardening even more consistent across the codebase. Overall, this is an excellent set of changes that improves the stability and security of the session middleware.
There was a problem hiding this comment.
Code Review
The pull request significantly improves the robustness of the session middleware by ensuring proper lifecycle management and error handling. The transition from panicking to returning errors during initialization, along with the addition of session ID validation and better pooling safety, are excellent improvements. I have a few suggestions to further 'harden' the lifecycle against panics and ensure consistency in context usage across all session operations.
|
@copilot fix merge conflicts |
Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/eff91f95-869e-4599-b693-49f2755131b9 Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
|
@copilot resolve the merge conflicts in this pull request |
Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/eff91f95-869e-4599-b693-49f2755131b9 Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/eff91f95-869e-4599-b693-49f2755131b9 Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Addressed in 19d91e3: session IDs now use the shared Fiber context helpers consistently, extracted IDs are validated before any storage lookup and preferred over cached request values, and session-load/init failures stay on the safe error-handling path instead of panicking.
The branch is conflict-free now; the merge-from-main resolution is in c972b14, and the follow-up session fixes are on top in 19d91e3. |
Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
|
@claude[agent] audit the security of these changes and fix any issues you find. |
…middleware Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/33423df8-7c18-40e3-8707-d9994ef91a2f Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Security audit completed (commit eb43a5c). Fixed critical vulnerability where configuration errors could panic and crash the application during middleware initialization. All other security aspects verified: Fixed:
Verified Secure:
All tests pass with race detection enabled. |
Motivation
Sessionobjects are always returned to the pool on every terminal/error path.Description
(*Middleware).initializereturnerrorand updateNewWithStoreto invoke the configuredErrorHandlerorDefaultErrorHandleron init failures while releasing the middleware and returning the original error only when no response status was written.finalizeSession()which conditionally callssaveSession()(skips when destroyed) and always callsreleaseSession(m.Session)exactly once to guarantee object lifecycle cleanup.Store.getSessionto callsess.Release()before returning whensess.Reset()fails on absolute-expiry, and changeStore.GetByIDto alwayssess.Release()before returningErrSessionIDNotFoundInStoreafter attemptingsess.Destroy().acquireSession()for balancedRelease()calls and add targeted tests for the new behaviors inmiddleware/session/middleware_test.goandmiddleware/session/store_test.go.