-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
fix(session): correct fresh flag logic in getSession #3825
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
Conversation
Fixed a bug where the `fresh` flag was incorrectly set to `true` when a session ID was found in context locals during subsequent calls to `getSession()` in the same request. The previous logic was: ```go fresh := ok // Assume the session is fresh if the ID is found in locals ``` This was backwards. When the session ID is found in locals (ok == true), it means the session was already initialized in this request, so it should NOT be marked as fresh. The correct logic is: ```go fresh := false // Session is not fresh initially; only set to true if we generate a new ID ``` **Impact:** - The `Fresh()` method now correctly returns `false` for existing sessions - Fixes potential issues with absolute timeout calculations - Prevents confusion in middleware that checks if a session is new **Tests added:** - `Test_Session_Fresh_Flag_Bug`: Verifies fresh flag is correct across multiple getSession() calls - `Test_Session_CSRF_Scenario`: Simulates the user-reported CSRF + session scenario - `Test_Session_Multiple_GetSession_Calls`: Ensures consistency across multiple calls **Tests updated:** - `Test_Session_Cookie_In_Middleware_Chain`: Fixed to expect correct fresh flag behavior **Related to user-reported issue:** While investigating a user report about getting new session IDs on failed CSRF validation, we discovered this bug. The user's issue is actually expected behavior (sessions regenerate when data expires), but this bug needed fixing regardless.
|
Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughThe session middleware's fresh-flag initialization was changed so sessions are only marked fresh when a new ID is generated; previously an ID found in locals marked the session fresh. One existing test expectation was updated and three new tests were added to cover fresh-flag, CSRF, and repeated getSession call scenarios. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Handler as Request Handler
participant SessionMW as Session Middleware
participant Store as Session Store
Note over SessionMW,Store: Fresh flag now only true when Store generates a new ID
rect rgb(240,248,255)
Note over Client,Store: Existing session flow
Client->>Handler: Request with session cookie
Handler->>SessionMW: getSession(ctx)
SessionMW->>Store: check locals for ID
Store->>Store: ID found in locals
Store->>Store: set fresh := false
Store->>Store: load session data (if present & not expired)
Store-->>SessionMW: return session (fresh=false)
end
rect rgb(240,255,240)
Note over Client,Store: New session flow
Client->>Handler: Request without session
Handler->>SessionMW: getSession(ctx)
SessionMW->>Store: check locals for ID
Store->>Store: no ID -> generate new ID
Store->>Store: set fresh := true
Store-->>SessionMW: return session (fresh=true)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ 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 @sixcolors, 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 addresses a critical bug in the session middleware's Highlights
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
|
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 effectively addresses a logic bug in the fresh flag of the session middleware. The fix is straightforward and correct, ensuring that sessions are only marked as 'fresh' when a new session ID is generated. The addition of comprehensive tests is commendable, as they thoroughly verify the corrected behavior and cover various scenarios, including the user-reported CSRF issue. I have one minor suggestion to improve one of the new tests by removing an unnecessary delay.
| // Small delay to ensure save completes | ||
| time.Sleep(10 * time.Millisecond) |
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.
The memory.New() storage provider used in these tests operates synchronously. The Set operation completes before returning, so this time.Sleep is not necessary to ensure the save operation has finished. Removing it will make the test slightly faster and avoid potential confusion about the storage provider's behavior.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #3825 +/- ##
==========================================
- Coverage 92.20% 92.18% -0.03%
==========================================
Files 115 115
Lines 9671 9671
==========================================
- Hits 8917 8915 -2
- Misses 482 483 +1
- Partials 272 273 +1
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.
Pull Request Overview
This PR fixes a bug in the session middleware where the fresh flag was incorrectly set to true when getSession() was called multiple times within the same request. The bug occurred because the session ID stored in context locals was interpreted as a fresh session.
- Changed the
freshflag initialization fromfresh := oktofresh := falsein thegetSession()method - Updated an existing test assertion to reflect the correct behavior (session should not be fresh when it has existing data)
- Added three comprehensive test cases to verify the fix and prevent regression
Reviewed Changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| middleware/session/store.go | Fixed the fresh flag logic to only set it to true when a new session ID is generated |
| middleware/session/session_test.go | Updated one test assertion and added three new test cases to verify the fix |
Co-authored-by: Copilot <[email protected]>
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.
Actionable comments posted: 1
♻️ Duplicate comments (1)
middleware/session/session_test.go (1)
1633-1634: Remove unnecessary sleep.The
memory.New()storage provider operates synchronously - theSave()operation completes before returning. This sleep is unnecessary and can be removed.Apply this diff:
- // Small delay to ensure save completes - time.Sleep(10 * time.Millisecond) - // Simulate: POST request with valid session (before expiration)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
middleware/session/session_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/session/session_test.go
🧠 Learnings (1)
📚 Learning: 2024-06-30T00:38:06.580Z
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Applied to files:
middleware/session/session_test.go
🧬 Code graph analysis (1)
middleware/session/session_test.go (3)
middleware/session/store.go (1)
NewStore(46-64)middleware/csrf/csrf.go (1)
New(47-214)middleware/session/config.go (1)
Config(13-90)
🪛 GitHub Actions: golangci-lint
middleware/session/session_test.go
[error] 1071-1071: golangci-lint: File is not properly formatted (gofmt).
🪛 GitHub Check: lint
middleware/session/session_test.go
[failure] 1071-1071:
File is not properly formatted (gofmt)
⏰ 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: unit (1.25.x, windows-latest)
- GitHub Check: repeated
- GitHub Check: Compare
🔇 Additional comments (2)
middleware/session/session_test.go (2)
1557-1607: Excellent test coverage for the fresh flag bug.This test comprehensively validates the fix by covering all relevant scenarios: initial fresh session, existing non-fresh session, the critical bug case (multiple getSession calls in same request), and the expired session edge case.
1668-1718: Excellent targeted test for the bug scenario.This test precisely validates the fix by simulating the exact conditions that triggered the bug: multiple
getSession()calls within the same request where the session ID gets stored in context locals. The progressive verification across three calls ensures the fix is robust.
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.
Actionable comments posted: 0
🧹 Nitpick comments (1)
middleware/session/session_test.go (1)
1633-1634: Consider removing unnecessary sleep.The
memory.New()storage provider operates synchronously - theSetoperation completes beforeSave()returns. This sleep is not needed to ensure data persistence.Apply this diff to remove the unnecessary delay:
sess1.Release() app.ReleaseCtx(ctx1) - // Small delay to ensure save completes - time.Sleep(10 * time.Millisecond) - // Simulate: POST request with valid session (before expiration)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
middleware/session/session_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/session/session_test.go
🧠 Learnings (1)
📚 Learning: 2024-06-30T00:38:06.580Z
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Applied to files:
middleware/session/session_test.go
🧬 Code graph analysis (1)
middleware/session/session_test.go (2)
middleware/session/store.go (1)
NewStore(46-64)middleware/session/config.go (1)
Config(13-90)
⏰ 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
🔇 Additional comments (4)
middleware/session/session_test.go (4)
1071-1071: LGTM - Correct expectation after bug fix.The assertion correctly expects
Fresh()to returnfalsewhen the secondGet()call reuses the session ID from context locals. This aligns with the PR's fix that ensuresfreshis onlytruewhen a session is newly created via ID generation.
1557-1607: Well-structured test covering the fresh flag bug scenarios.This test thoroughly validates the fresh flag behavior across multiple scenarios:
- Fresh sessions on initial creation
- Non-fresh sessions when loading existing data
- Critical bug scenario: repeated
getSession()calls maintaining non-fresh state- Fresh sessions after expiration/missing data
The test properly manages context and session lifecycles with appropriate cleanup.
1609-1666: Solid CSRF scenario test with one minor optimization opportunity.The test effectively simulates the user-reported CSRF + session interaction, validating that sessions remain non-fresh when valid and become fresh after expiration with a new ID.
1668-1718: Excellent test for the core bug scenario.This test directly validates the fix for the fresh flag bug by calling
getSession()multiple times within the same request context. It ensures the session remains non-fresh across calls when the ID is found in context locals - the exact scenario that was broken before the fix.The test properly:
- Verifies session state persistence across calls
- Validates ID consistency
- Ensures data integrity
- Manages session and context lifecycle correctly
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Description
This PR fixes a bug in the session middleware's
freshflag logic that caused incorrectFresh()values whengetSession()was called multiple times for the same session within a single request.Problem
The bug was on line 130 of
middleware/session/store.go:This inverted logic meant that:
locals(cached),freshwas set totrue(incorrectly indicating new session)locals,freshwas set tofalse(incorrectly indicating existing session)Impact
The bug affected scenarios where:
getSession()calls happened in the same request (e.g., middleware chain + CSRF validation)Fresh()to detect truly new sessionsSolution
Changed line 130 to:
Now the
freshflag is only set totruein two legitimate cases:acquireSession()- when creating a brand new session (line 61 insession.go)refresh()- when regenerating an expired session (line 280 insession.go)Tests Added
Added 3 comprehensive tests to verify the fix:
Test_Session_Fresh_Flag_Bug- Verifies multiplegetSessioncalls return consistentfresh=falsefor existing sessionsTest_Session_CSRF_Scenario- Simulates the user-reported CSRF issue with session regenerationTest_Session_Multiple_GetSession_Calls- Ensures session ID consistency across multiple retrievalsUpdated 1 existing test:
Test_Session_Cookie_In_Middleware_Chain- Corrected expectation to match fixed behaviorTest Results
All 48 session middleware tests passing:
$ make test PASS coverage: 89.4% of statements ok github.com/gofiber/fiber/v3/middleware/session 2.345sBackwards Compatibility
This is a bug fix, not a breaking change. Applications relying on the buggy behavior (which was incorrect) will now receive the correct
freshflag values.Related Issues
Discovered during investigation of user-reported CSRF + session behavior.