-
-
Notifications
You must be signed in to change notification settings - Fork 2k
🐛 bug: harden session middleware lifecycle and error handling #4059
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the
✨ 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.09% 91.16% +0.06%
==========================================
Files 119 119
Lines 11184 11224 +40
==========================================
+ Hits 10188 10232 +44
+ Misses 630 628 -2
+ Partials 366 364 -2
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.
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 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.
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 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. |
| reused := acquireSession() | ||
| require.Nil(t, reused.ctx) | ||
| require.Nil(t, reused.config) | ||
| require.Empty(t, reused.id) | ||
| reused.Release() |
Copilot
AI
Feb 7, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These assertions don’t actually verify that the session involved in the failing store.Get path was released back to the pool: sync.Pool may return a different (or newly allocated) Session that already has zero values, so the test can pass even if the original session leaked. Consider making the test deterministic (e.g., temporarily swapping sessionPool with a test pool and disabling t.Parallel() for this test, or adding explicit instrumentation/counters around release paths).
| reused := acquireSession() | ||
| require.Nil(t, reused.ctx) | ||
| require.Nil(t, reused.config) | ||
| require.Empty(t, reused.id) | ||
| reused.Release() |
Copilot
AI
Feb 7, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same issue as above: acquiring a session from sync.Pool and checking for zero-values doesn’t prove the expired GetByID path released the specific session it allocated, since sync.Pool can return a different/new object. Consider a deterministic approach (test pool swap, counters, or pointer identity under controlled conditions) so this test fails if the session isn’t released.
| m := acquireMiddleware() | ||
| require.Nil(t, m.Session) | ||
| require.Nil(t, m.ctx) | ||
| require.Nil(t, m.config.Store) | ||
| releaseMiddleware(m) |
Copilot
AI
Feb 7, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This pool check isn’t a reliable assertion that the middleware instance used during the request was released: sync.Pool may return a different (or newly allocated) Middleware with nil fields, so the test can pass even if the original middleware wasn’t released on init error. Consider asserting observable behavior instead (e.g., that the request doesn’t leave a middleware in c.Locals, or adding deterministic pooling instrumentation in tests).
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.