Skip to content
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

feat!(middleware/session): re-write session middleware with handler #3016

Merged
merged 93 commits into from
Oct 25, 2024

Conversation

sixcolors
Copy link
Member

@sixcolors sixcolors commented May 28, 2024

Feature: Re-write Session Middleware with Handler

Summary

This pull request introduces significant changes to the session middleware, enhancing its functionality and improving its robustness. The primary focus is on the re-write of the session middleware with a new handler.

Status

  • Initial PR for concept
  • Optimize Performance
  • Migrate to Middleware Style (session.New() returns middleware handler)
  • Add new tests for the middleware handler to cover various scenarios including error handling, session retrieval, and data manipulation.
  • Improve test coverage.
  • Update Documentation
  • Update Migration Guide
  • Update CSRF Middleware
  • Update CSRF Middleware Tests to cover Middleware-style sessions.

Changelog

Middleware Changes

  • Re-write session middleware: The session middleware has been re-written to use a handler for better session management.
  • New Middleware File: Added middleware/session/middleware.go to define the session middleware and its configuration.
  • Enhanced Session Management:
    • Introduced a middleware pool for efficient session handling.
    • Added methods for setting, getting, and deleting session data within the middleware.
    • Improved error handling during session operations.

CSRF Session Manager Changes

  • Improved Session Handling:
    • Modified getRaw, setRaw, and delRaw methods to use the session from the context first before falling back to the store.
    • Removed logging dependency (log) from the session manager.

Configuration Changes

  • Config Struct Update:
    • Renamed Expiration to IdleTimeout to better reflect the session idle duration.
    • Updated default values and their usage in the configuration.

Session Struct Changes

  • Renamed Fields:
    • exp is now idleTimeout to indicate the idle timeout duration for sessions.
  • Session Methods Update:
    • Updated methods to use idleTimeout instead of exp.
    • Improved the Save method to handle idle timeout correctly.

Changes From This PR

This is an new middleware approach. Changes have been made to:

  • Update session.New to return the Middleware handler instead of the old session.Store struct.

A suggested standard use for the session might look something like this after these modifications:

func main() {
	app := fiber.New()

	// Middleware
	app.Use(logger.New())
	app.Use(limiter.New())
	sessionMiddleware, sessionStore := session.NewWithStore()
	app.Use(sessionMiddleware)
	 app.Use(csrf.New(
		csrf.Config{
			Store: sessionStore,
		},
	))

	// Routes
	app.Get("/", func(c *fiber.Ctx) error {
		ses := session.FromContext(c)
		if ses == nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"message": "Internal Server Error",
			})
		}
		user, ok := sess.Get("user").(User)
		if !ok {
			return c.Redirect("/login")
		}

		return c.SendString(fmt.Sprintf("Welcome %s!", user.Username))

	})

	app.Get("/session", func(c *fiber.Ctx) error {
		ses := session.FromContext(c)
		if ses == nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"message": "Internal Server Error",
			})
		}
		// In this proposal, we will return the session ID
		// which we will always have, because we always have a session
		// even if it's empty. It's generated on the first request.
		_, sessionHasUser := sess.Get("user").(User)
		return c.JSON(fiber.Map{
			"session":        sess.ID(),
			"sessionHasUser": sessionHasUser,
		})
	})

	app.Get("/login", func(c *fiber.Ctx) error {
		return c.SendFile("login.html")
	})

	app.Post("/auth/login", func(c *fiber.Ctx) error {
		type LoginInput struct {
			Username string `json:"username"`
			Password string `json:"password"`
		}
		var input LoginInput
		if err := c.BodyParser(&input); err != nil {
			return err
		}
		// Check username and password
		usr, err := repo.Login(input.Username, input.Password)
		if err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"message": "Unauthorized",
			})
		}
		// Create session
		ses := session.FromContext(c)
		if ses == nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"message": "Internal Server Error",
			})
		}
		// Since this is a login, we should regenerate the session
		sess.Regenerate()
		// Set user in session
		sess.Set("user", usr)
		// Return message
		return c.JSON(fiber.Map{
			"message": "Login successful",
		})
		// Save session is automatic when middleware handler is used
		// it will happen after the handler has returned.
	})

	app.Post("/auth/logout", func(c *fiber.Ctx) error {
		ses := session.FromContext(c)
		if ses == nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"message": "Internal Server Error",
			})
		}
		// Destroy session
		sess.Destroy()
		// a new session will be created automatically on the next request
		// by the session middleware
		return c.JSON(fiber.Map{
			"message": "Logout successful",
		})
	})

	app.Get("/auth/timeout", func(c *fiber.Ctx) error {
		ses := session.FromContext(c)
		if ses == nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"message": "Internal Server Error",
			})
		}
		// Calling any route where the session middleware is
		// used will extend the idle timeout.
		return c.JSON(fiber.Map{
			"message":     "Session extended",
			"idleTimeout": sess.IdleTimeout(),
		})
	})

	// Start server
	app.Listen(":3000")
}

Testing

  • Ensure all existing tests pass.
  • Add new tests for the middleware handler to cover various scenarios including error handling, session retrieval, and data manipulation.

Notes

  • This update introduces breaking changes due to the renaming of configuration fields and changes in session handling methods. Ensure to update the dependent code accordingly.
  • The re-write aims to improve performance and maintainability of the session management logic.

Please review the changes and provide feedback or approval for merging.


Fixes #2741

@sixcolors sixcolors requested a review from a team as a code owner May 28, 2024 20:46
@sixcolors sixcolors requested review from gaby, ReneWerner87 and efectn and removed request for a team May 28, 2024 20:46
Copy link
Contributor

coderabbitai bot commented May 28, 2024

Walkthrough

The recent changes enhance the test coverage and functionality of session management within the middleware. The New() function has been renamed to NewStore(), affecting multiple test cases. New tests have been introduced to validate session retrieval and error handling, specifically addressing scenarios for session loading and deletion. Additionally, resource management has been improved with the inclusion of defer statements in context acquisition, ensuring proper cleanup after tests.

Changes

Files Change Summary
middleware/session/store.go Renamed New to NewStore, added GetByID method for session retrieval, and improved error handling.
middleware/session/store_test.go Renamed test cases to reflect NewStore(), added tests for session loading, deletion scenarios, and improved coverage.

Assessment against linked issues

Objective Addressed Explanation
Evaluate Session middleware for consistency with NIST guidelines (#2741) Changes do not address the inconsistencies in session expiration and timeout handling.
Evaluate CSRF middleware for alignment with NIST standards (#2741) No modifications were made to the CSRF middleware as part of these changes.
Update middleware documentation for clarity on expiration and timeout (#2741) While changes were made, it is unclear if documentation updates were included in this PR.

Poem

In the realm of sessions, we hop and play,
With NewStore() guiding the way.
Sessions now fresh, with timeouts in sight,
A rabbit's joy in the code feels just right.
Resource management, a leap so grand,
In the world of Fiber, we take a stand! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 2

Outside diff range and nitpick comments (3)
middleware/csrf/session_manager.go (1)

74-84: Consider adding logging for error scenarios in session deletion.

if err != nil {
    log.Errorf("Failed to retrieve session for deletion: %v", err)
}
middleware/session/middleware.go (1)

51-94: Add detailed documentation for the middleware lifecycle.

// NewMiddleware creates and manages the lifecycle of session middleware.
// It retrieves a middleware instance from the pool, attaches it to the context,
// and ensures it is properly released after the request is processed.
middleware/session/session.go (1)

Line range hint 170-192: Improve error handling in the Save method to handle potential encoding failures more gracefully.

if err != nil {
    log.Errorf("Session encoding failed: %v", err)
    return err
}
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between ed9d7cf and 6e76847.
Files selected for processing (4)
  • middleware/csrf/session_manager.go (3 hunks)
  • middleware/session/config.go (3 hunks)
  • middleware/session/middleware.go (1 hunks)
  • middleware/session/session.go (7 hunks)
Additional comments not posted (4)
middleware/csrf/session_manager.go (1)

57-68: Ensure thread safety when setting session tokens.

Verification successful

The Set method implementations found in the codebase indicate that thread safety measures are in place. Specifically:

  • In middleware/session/middleware.go, the Set method uses a mutex (m.mu.Lock() and m.mu.Unlock()) to ensure thread safety.
  • In middleware/session/data.go, the Set method also uses a lock (d.Lock() and d.Unlock()) to ensure thread safety.

These implementations confirm that the session management operations are thread-safe.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for potential data races when setting session tokens.
# Command: Run your Go data race detector tool on this section.

Length of output: 0



Script:

#!/bin/bash
# Description: Check if the session management library used in the codebase provides thread-safe operations.
# Command: Search for the session management library and inspect its documentation or implementation for thread safety.

# Find the session management library used in the codebase
session_lib=$(rg --files-with-matches 'session.FromContext' | head -n 1)

# Check if the session management library provides thread-safe operations
if [ -n "$session_lib" ]; then
  rg 'thread-safe' "$session_lib"
else
  echo "Session management library not found."
fi

Length of output: 208



Script:

#!/bin/bash
# Description: Extract and inspect the implementation of the `Set` method in the session management library to verify thread safety.

# Find the implementation of the `Set` method in the session management library
ast-grep --lang go --pattern 'func ($_ $_) Set($_, $_) $_' middleware/csrf/session_manager.go

Length of output: 95



Script:

#!/bin/bash
# Description: Search the entire codebase for the implementation of the `Set` method to verify thread safety.

# Find the implementation of the `Set` method in the entire codebase
ast-grep --lang go --pattern 'func ($_ $_) Set($_, $_) $_'

Length of output: 1417

middleware/session/config.go (1)

13-15: Renaming Expiration to IdleTimeout clarifies the purpose and aligns with best practices.

middleware/session/middleware.go (1)

31-37: Well-structured Middleware struct with appropriate use of synchronization for thread safety.

middleware/session/session.go (1)

16-22: The addition of idleTimeout in the Session struct is a positive change for better session management.

middleware/session/config.go Outdated Show resolved Hide resolved
@sixcolors
Copy link
Member Author

Known Issues

Storage Adapter UPSERT Behavior

There is an issue with the way Fiber's storage adapters handle setting keys. The current operation for setting a key is an UPSERT, which means it will insert a new key if it does not exist or update it if it does. This can lead to issues in scenarios with simultaneous requests altering the same session. For example:

  • One request destroys the session.
  • Another request makes an inconsequential change to the session.

If the session destruction completes first, the inconsequential change could recreate the session, potentially preventing actions like logging out and posing security risks.

Since this PR changes the session behavior to save and update on every request, it amplifies the problem if not addressed.

@sixcolors
Copy link
Member Author

sixcolors commented May 28, 2024

See: https://github.com/gofiber/recipes/tree/v3-csrf-with-session-PR-3016-update/csrf-with-session for usage example of this PR in current state.

@gaby
Copy link
Member

gaby commented May 29, 2024

Those new sequence diagrams are awesome

Copy link
Member

@renanbastos93 renanbastos93 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, you've been doing a good job. I commented on a few details. Thanks for contributing here.

middleware/csrf/session_manager.go Show resolved Hide resolved
middleware/csrf/session_manager.go Show resolved Hide resolved
middleware/csrf/session_manager.go Show resolved Hide resolved
middleware/session/middleware.go Outdated Show resolved Hide resolved
middleware/session/middleware.go Outdated Show resolved Hide resolved
middleware/session/middleware.go Outdated Show resolved Hide resolved
sixcolors and others added 2 commits May 30, 2024 13:51
Co-authored-by: Renan Bastos <renanbastos.tec@gmail.com>
Copy link

codecov bot commented May 30, 2024

Codecov Report

Attention: Patch coverage is 83.81503% with 56 lines in your changes missing coverage. Please review.

Project coverage is 82.76%. Comparing base (0b6a26f) to head (b54c954).
Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
middleware/csrf/session_manager.go 57.14% 14 Missing and 7 partials ⚠️
middleware/session/middleware.go 90.65% 7 Missing and 3 partials ⚠️
middleware/session/store.go 84.61% 7 Missing and 3 partials ⚠️
middleware/session/session.go 87.83% 7 Missing and 2 partials ⚠️
middleware/session/config.go 64.28% 3 Missing and 2 partials ⚠️
middleware/session/data.go 95.23% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3016      +/-   ##
==========================================
+ Coverage   80.11%   82.76%   +2.65%     
==========================================
  Files         117      114       -3     
  Lines        9044    11149    +2105     
==========================================
+ Hits         7246     9228    +1982     
- Misses       1364     1521     +157     
+ Partials      434      400      -34     
Flag Coverage Δ
unittests 82.76% <83.81%> (+2.65%) ⬆️

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.

Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 20

🧹 Outside diff range and nitpick comments (32)
middleware/csrf/session_manager.go (4)

21-32: Improved session manager initialization

The changes to newSessionManager are well-implemented:

  1. Removing the k string parameter simplifies the function.
  2. Registering sessionKeyType and Token with the session store ensures proper serialization/deserialization.

These changes align well with the new session key management approach.

However, consider adding error handling for the type registration:

if err := s.RegisterType(sessionKeyType(0)); err != nil {
    // Handle or log the error
}
if err := s.RegisterType(Token{}); err != nil {
    // Handle or log the error
}

This would make the function more robust against potential registration failures.


37-52: Improved session retrieval logic with suggestions

The changes to getRaw method are well-implemented:

  1. Prioritizing context-based session retrieval can improve performance.
  2. Fallback to store retrieval ensures compatibility with various session management scenarios.

However, there are a few areas for improvement:

  1. Error handling: The error from m.session.Get(c) is silently ignored. Consider logging this error or returning it to the caller.

  2. Potential refactoring: The token retrieval logic is duplicated. Consider refactoring to reduce duplication:

func (m *sessionManager) getToken(s fiber.Session) (Token, bool) {
    token, ok := s.Get(sessionKey).(Token)
    return token, ok
}

// In getRaw:
var token Token
var ok bool

if sess := session.FromContext(c); sess != nil {
    token, ok = m.getToken(sess)
} else {
    storeSess, err := m.session.Get(c)
    if err != nil {
        log.Warn("csrf: failed to get session from store: ", err)
        return nil
    }
    token, ok = m.getToken(storeSess)
}

This refactoring would make the code more maintainable and reduce the risk of inconsistencies.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 48-48: middleware/csrf/session_manager.go#L48
Added line #L48 was not covered by tests


65-80: Improved session setting logic with suggestions

The changes to setRaw method are well-implemented:

  1. Prioritizing context-based session aligns with the changes in getRaw.
  2. The use of sessionKey constant improves consistency and type safety.

However, there are areas for improvement:

  1. Error handling: Errors from m.session.Get(c) and storeSess.Save() are logged but not returned. Consider propagating these errors to the caller for better error management.

  2. Potential refactoring: The token setting logic is duplicated. Consider refactoring to reduce duplication:

func (m *sessionManager) setToken(s fiber.Session, token Token) error {
    s.Set(sessionKey, token)
    if store, ok := s.(*session.Store); ok {
        return store.Save()
    }
    return nil
}

// In setRaw:
token := Token{Key: key, Raw: raw, Expiration: time.Now().Add(exp)}
var err error

if sess := session.FromContext(c); sess != nil {
    err = m.setToken(sess, token)
} else {
    storeSess, getErr := m.session.Get(c)
    if getErr != nil {
        return fmt.Errorf("csrf: failed to get session from store: %w", getErr)
    }
    err = m.setToken(storeSess, token)
}

if err != nil {
    log.Warn("csrf: failed to save session: ", err)
}

This refactoring would make the code more maintainable and reduce the risk of inconsistencies.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 74-74: middleware/csrf/session_manager.go#L74
Added line #L74 was not covered by tests


[warning] 78-78: middleware/csrf/session_manager.go#L78
Added line #L78 was not covered by tests


85-99: Improved session deletion logic with suggestions

The changes to delRaw method are well-implemented:

  1. Prioritizing context-based session aligns with the changes in getRaw and setRaw.
  2. The use of sessionKey constant improves consistency and type safety.

However, there are areas for improvement:

  1. Error handling: Errors from m.session.Get(c) and storeSess.Save() are logged but not returned. Consider propagating these errors to the caller for better error management.

  2. Potential refactoring: The token deletion logic is duplicated. Consider refactoring to reduce duplication:

func (m *sessionManager) deleteToken(s fiber.Session) error {
    s.Delete(sessionKey)
    if store, ok := s.(*session.Store); ok {
        return store.Save()
    }
    return nil
}

// In delRaw:
var err error

if sess := session.FromContext(c); sess != nil {
    err = m.deleteToken(sess)
} else {
    storeSess, getErr := m.session.Get(c)
    if getErr != nil {
        return fmt.Errorf("csrf: failed to get session from store: %w", getErr)
    }
    err = m.deleteToken(storeSess)
}

if err != nil {
    log.Warn("csrf: failed to save session: ", err)
}

This refactoring would make the code more maintainable and reduce the risk of inconsistencies.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 87-87: middleware/csrf/session_manager.go#L87
Added line #L87 was not covered by tests


[warning] 93-93: middleware/csrf/session_manager.go#L93
Added line #L93 was not covered by tests


[warning] 97-97: middleware/csrf/session_manager.go#L97
Added line #L97 was not covered by tests

middleware/session/config.go (2)

12-95: LGTM: Enhanced Config struct with improved session management

The changes to the Config struct significantly improve session management capabilities:

  1. The addition of Next, ErrorHandler, IdleTimeout, and AbsoluteTimeout fields enhances configurability and error handling.
  2. Replacing Expiration with IdleTimeout and AbsoluteTimeout provides more granular control over session expiration.
  3. The improved documentation for all fields enhances code readability and usability.

These changes align well with the PR objectives of improving session management and addressing inconsistencies in timeout handling.

Consider adding a note to the AbsoluteTimeout documentation to clarify its relationship with IdleTimeout. For example:

// AbsoluteTimeout defines the maximum duration of the session before it expires.
//
// If set to 0, the session will not have an absolute timeout, and will expire after the idle timeout.
// Note: This value should be greater than or equal to IdleTimeout.
//
// Optional. Default: 0
AbsoluteTimeout time.Duration

This addition would help prevent potential configuration errors.


Line range hint 135-190: LGTM: Improved configDefault with enhanced error handling

The updates to configDefault function are well-aligned with the changes made to the Config struct:

  1. Proper handling of new fields like IdleTimeout and AbsoluteTimeout.
  2. Addition of a safeguard to ensure AbsoluteTimeout is always greater than or equal to IdleTimeout.
  3. Improved error messages for better debuggability.

These changes contribute to more robust session configuration.

Consider using log.Panic instead of panic for consistency with the error handling approach used elsewhere in the package. This would allow for better error logging and potential recovery in production environments. For example:

if cfg.AbsoluteTimeout > 0 && cfg.AbsoluteTimeout < cfg.IdleTimeout {
    log.Panic("[session] AbsoluteTimeout must be greater than or equal to IdleTimeout")
}
if len(selectors) != numSelectors {
    log.Panic("[session] KeyLookup must be in the format '<source>:<name>'")
}
default:
    log.Panic("[session] unsupported source in KeyLookup")

This change would provide more consistent error handling throughout the package.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 130-130: middleware/session/config.go#L130
Added line #L130 was not covered by tests


[warning] 162-162: middleware/session/config.go#L162
Added line #L162 was not covered by tests

middleware/csrf/config.go (2)

125-125: Approve IdleTimeout in ConfigDefault, suggest documenting rationale.

The change from Expiration to IdleTimeout in ConfigDefault is consistent with the struct modification. The default value of 30 minutes is reasonable for CSRF token validity.

Consider adding a comment explaining the rationale for choosing 30 minutes as the default IdleTimeout. This would provide valuable context for developers using or maintaining the middleware.


150-151: Approve IdleTimeout check, suggest minor improvement.

The change from Expiration to IdleTimeout in the configDefault function is consistent with the previous modifications. The logic correctly ensures that a default value is set if IdleTimeout is not properly configured.

Consider changing the condition to explicitly check for negative values:

-if cfg.IdleTimeout <= 0 {
+if cfg.IdleTimeout < 0 {

This change would allow users to set IdleTimeout to 0 if they want to disable the timeout feature. If this is not the intended behavior, please add a comment explaining why 0 is not a valid value.

middleware/session/middleware.go (4)

12-39: LGTM: Well-structured Middleware type with proper concurrency considerations.

The Middleware struct and related constants are well-designed. The use of sync.RWMutex for concurrency safety and sync.Pool for instance reuse are good practices.

Consider adding a brief comment explaining the purpose of the destroyed field in the Middleware struct for better clarity.


41-108: LGTM: Well-implemented initialization functions with proper session lifecycle management.

The New and NewWithStore functions provide a flexible way to initialize the session middleware. The handler correctly manages the session lifecycle, including initialization and cleanup.

Consider adding error handling for the case where NewWithStore fails to create a store. Currently, if NewStore(cfg) were to return an error (which it doesn't in the current implementation), it would be silently ignored.


235-289: LGTM: Well-implemented session management methods.

The Destroy, Fresh, ID, and Reset methods provide necessary session management operations and are correctly implemented.

Consider adding a brief comment explaining the purpose of the destroyed flag in the Destroy method, and how it interacts with other parts of the middleware (e.g., in the handler function).


1-301: Overall assessment: Well-implemented session middleware with room for minor improvements.

This new session middleware implementation for Fiber is robust and well-structured. Key strengths include:

  1. Proper use of sync.Pool for performance optimization.
  2. Good concurrency safety with appropriate use of mutexes.
  3. Flexible configuration options.
  4. Comprehensive session management operations.

Areas for improvement:

  1. Error handling in the initialize and acquireMiddleware methods could be more graceful to avoid potential panics in production.
  2. Test coverage could be increased, particularly for error handling paths.
  3. Some additional documentation would improve code clarity, especially regarding the destroyed flag and its implications.

These improvements would further enhance the reliability and maintainability of the middleware. Overall, this is a solid implementation that provides a strong foundation for session management in Fiber applications.

Consider adding a middleware-specific logger or integrating with Fiber's logging system. This would allow for more granular control over log levels and could help with debugging in production environments without relying on panics for error reporting.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 117-117: middleware/session/middleware.go#L117
Added line #L117 was not covered by tests


[warning] 130-133: middleware/session/middleware.go#L130-L133
Added lines #L130 - L133 were not covered by tests


[warning] 144-144: middleware/session/middleware.go#L144
Added line #L144 was not covered by tests

middleware/csrf/csrf.go (1)

Line range hint 1-353: Overall assessment: Successful implementation of CSRF middleware improvements

The changes in this file successfully address the objectives outlined in the PR and issue #2741. Key improvements include:

  1. Simplified session manager initialization.
  2. Consistent replacement of Expiration with IdleTimeout throughout the CSRF middleware.
  3. Better alignment with NIST guidelines on distinguishing between timeout and expiration.

These modifications enhance the security and consistency of the CSRF protection mechanism. The code is now more maintainable and adheres to best practices for session management.

Consider the following for future improvements:

  1. Implement the absolute timeout mechanism mentioned in the PR comments.
  2. Update the documentation to reflect these changes, especially regarding the new IdleTimeout usage.
  3. Ensure that all related tests are updated to use IdleTimeout instead of Expiration.
middleware/session/session.go (3)

59-81: Approved: New Release method enhances session management

The addition of the Release method is a valuable improvement for efficient session management. It aligns well with the PR objectives by providing a clear mechanism for returning sessions to the pool.

Consider adding a note in the documentation about the thread-safety of this method. For example:

 // Release releases the session back to the pool.
+//
+// This method is safe to call concurrently from multiple goroutines.

This addition would provide clarity on the method's behavior in concurrent scenarios.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 78-78: middleware/session/session.go#L78
Added line #L78 was not covered by tests


Line range hint 295-326: Approved: New saveSession method enhances session management

The addition of the saveSession method is a good improvement in code organization and aligns well with the PR objectives. It centralizes the logic for saving session data and ensures consistent handling of the idleTimeout.

Consider adding more granular error handling:

 func (s *Session) saveSession() error {
 	if s.data == nil {
 		return nil
 	}

 	s.mu.Lock()
 	defer s.mu.Unlock()

 	// Set idleTimeout if not already set
 	if s.idleTimeout <= 0 {
 		s.idleTimeout = s.config.IdleTimeout
 	}

 	// Update client cookie
 	s.setSession()

 	// Encode session data
 	encCache := gob.NewEncoder(s.byteBuffer)
 	s.data.RLock()
 	err := encCache.Encode(&s.data.Data)
 	s.data.RUnlock()
 	if err != nil {
 		return fmt.Errorf("failed to encode data: %w", err)
 	}

 	// Copy the data in buffer
 	encodedBytes := make([]byte, s.byteBuffer.Len())
 	copy(encodedBytes, s.byteBuffer.Bytes())

 	// Pass copied bytes with session id to provider
-	return s.config.Storage.Set(s.id, encodedBytes, s.idleTimeout)
+	if err := s.config.Storage.Set(s.id, encodedBytes, s.idleTimeout); err != nil {
+		return fmt.Errorf("failed to store session data: %w", err)
+	}
+	return nil
 }

This change would provide more context in case of a storage error, making debugging easier.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 286-286: middleware/session/session.go#L286
Added line #L286 was not covered by tests


[warning] 288-288: middleware/session/session.go#L288
Added line #L288 was not covered by tests


441-479: Approved: New methods for absolute session expiration

The addition of absExpiration, isAbsExpired, and setAbsExpiration methods is a valuable improvement to the session management system. These methods provide an additional layer of control over session lifetimes, aligning well with the PR objectives.

Consider adding a brief explanation in the package documentation about the difference between idle timeout and absolute expiration. For example:

/*
Package session provides session management for Fiber applications.

This package uses two types of session expiration:
1. Idle Timeout: The session expires after a period of inactivity.
2. Absolute Expiration: The session expires at a fixed point in time, regardless of activity.

Idle Timeout is managed automatically, while Absolute Expiration can be set manually using the setAbsExpiration method.
*/
package session

This addition would provide clarity on the two expiration mechanisms and how they differ.

docs/middleware/session.md (5)

59-59: Consider clarifying IdleTimeout behavior in the legacy approach

The note about IdleTimeout behavior in the legacy approach is helpful. To further improve clarity, consider expanding this note to explain how the IdleTimeout behaves differently in the middleware handler approach. This will help users understand the key differences between the two approaches.

Consider adding the following information:

 When using the legacy approach, the IdleTimeout will be updated when the session is saved.
+When using the middleware handler approach, the IdleTimeout is automatically updated on each request.

132-148: Enhance Config struct documentation

The Config struct documentation is comprehensive, but it could benefit from additional context for the new timeout fields. This would help users understand the difference between IdleTimeout and AbsoluteTimeout and how they affect session behavior.

Consider adding brief descriptions to the IdleTimeout and AbsoluteTimeout fields:

 type Config struct {
     // ... other fields ...
-    IdleTimeout       time.Duration
-    AbsoluteTimeout   time.Duration
+    IdleTimeout       time.Duration // Maximum duration of inactivity before session expires
+    AbsoluteTimeout   time.Duration // Maximum total duration of a session, regardless of activity
     // ... other fields ...
 }

207-218: Ensure consistent formatting for method signatures

The method signatures in the Session Methods section are not consistently formatted. Some methods are on separate lines, while others are on the same line. Consistent formatting would improve readability.

Consider applying the following changes to ensure consistent formatting:

 func (s *Session) Fresh() bool
 func (s *Session) ID() string
-func (s *Session) Get(key string) any
-func (s *Session) Set(key string, val any)
-func (s *Session) Destroy() error
-func (s *Session) Regenerate() error
+func (s *Session) Get(key string) any
+func (s *Session) Set(key string, val any)
+func (s *Session) Destroy() error
+func (s *Session) Regenerate() error
 func (s *Session) Release()
 func (s *Session) Reset() error
-func (s *Session) Save() error
-func (s *Session) Keys() []string
+func (s *Session) Save() error
+func (s *Session) Keys() []string
 func (s *Session) SetIdleTimeout(idleTimeout time.Duration)

397-418: Enhance custom types example

The example for registering custom types is helpful, but it could be more informative by demonstrating how to actually use the custom type in a session. This would provide a complete picture of how to work with custom types in sessions.

Consider expanding the example to show how to set and get a custom type in a session:

 func main() {
     app := fiber.New()

     sessionMiddleware, sessionStore := session.NewWithStore()
     sessionStore.RegisterType(User{})

     app.Use(sessionMiddleware)

+    app.Get("/", func(c fiber.Ctx) error {
+        sess := session.FromContext(c)
+        if sess == nil {
+            return c.SendStatus(fiber.StatusInternalServerError)
+        }
+
+        // Set custom type in session
+        sess.Set("user", User{Name: "John Doe", Age: 30})
+
+        // Get custom type from session
+        if user, ok := sess.Get("user").(User); ok {
+            return c.SendString(fmt.Sprintf("User: %s, Age: %d", user.Name, user.Age))
+        }
+
+        return c.SendString("User not found in session")
+    })

     app.Listen(":3000")
 }

This enhancement demonstrates how to set and retrieve a custom type in a session, providing a more complete example for users.


423-437: Ensure consistent formatting for property descriptions

The property descriptions in the Config table are not consistently formatted. Some end with periods, while others don't. Consistent formatting would improve readability and professionalism.

Consider applying the following changes to ensure consistent formatting:

-| **Storage**           | `fiber.Storage`                | Defines where session data is stored.                                                      | `nil` (in-memory storage) |
-| **Next**              | `func(c fiber.Ctx) bool`       | Function to skip this middleware under certain conditions.                                 | `nil`                     |
-| **ErrorHandler**      | `func(c fiber.Ctx, err error)` | Custom error handler for session middleware errors.                                        | `nil`                     |
-| **KeyGenerator**      | `func() string`                | Function to generate session IDs.                                                          | `UUID()`                  |
-| **KeyLookup**         | `string`                       | Key used to store session ID in cookie or header.                                          | `"cookie:session_id"`     |
-| **CookieDomain**      | `string`                       | The domain scope of the session cookie.                                                    | `""`                      |
-| **CookiePath**        | `string`                       | The path scope of the session cookie.                                                      | `"/"`                     |
-| **CookieSameSite**    | `string`                       | The SameSite attribute of the session cookie.                                              | `"Lax"`                   |
-| **IdleTimeout**       | `time.Duration`                | Maximum duration of inactivity before session expires.                                     | `30 * time.Minute`        |
-| **AbsoluteTimeout**   | `time.Duration`                | Maximum duration before session expires.                                                   | `0` (no expiration)       |
-| **CookieSecure**      | `bool`                         | Ensures session cookie is only sent over HTTPS.                                            | `false`                   |
-| **CookieHTTPOnly**    | `bool`                         | Ensures session cookie is not accessible to JavaScript (HTTP only).                        | `true`                    |
-| **CookieSessionOnly** | `bool`                         | Prevents session cookie from being saved after the session ends (cookie expires on close). | `false`                   |
+| **Storage**           | `fiber.Storage`                | Defines where session data is stored                                                       | `nil` (in-memory storage) |
+| **Next**              | `func(c fiber.Ctx) bool`       | Function to skip this middleware under certain conditions                                  | `nil`                     |
+| **ErrorHandler**      | `func(c fiber.Ctx, err error)` | Custom error handler for session middleware errors                                         | `nil`                     |
+| **KeyGenerator**      | `func() string`                | Function to generate session IDs                                                           | `UUID()`                  |
+| **KeyLookup**         | `string`                       | Key used to store session ID in cookie or header                                           | `"cookie:session_id"`     |
+| **CookieDomain**      | `string`                       | The domain scope of the session cookie                                                     | `""`                      |
+| **CookiePath**        | `string`                       | The path scope of the session cookie                                                       | `"/"`                     |
+| **CookieSameSite**    | `string`                       | The SameSite attribute of the session cookie                                               | `"Lax"`                   |
+| **IdleTimeout**       | `time.Duration`                | Maximum duration of inactivity before session expires                                      | `30 * time.Minute`        |
+| **AbsoluteTimeout**   | `time.Duration`                | Maximum duration before session expires                                                    | `0` (no expiration)       |
+| **CookieSecure**      | `bool`                         | Ensures session cookie is only sent over HTTPS                                             | `false`                   |
+| **CookieHTTPOnly**    | `bool`                         | Ensures session cookie is not accessible to JavaScript (HTTP only)                         | `true`                    |
+| **CookieSessionOnly** | `bool`                         | Prevents session cookie from being saved after the session ends (cookie expires on close)  | `false`                   |

This change ensures all descriptions are consistently formatted without periods at the end.

🧰 Tools
🪛 LanguageTool

[style] ~436-~436: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

docs/whats_new.md (7)

318-330: Consider enhancing the Session middleware documentation.

The Session middleware section provides a good overview of the key changes in v3. However, consider the following improvements:

  1. Add a brief example demonstrating how to use the new middleware handler, including how to access the session store and manually release sessions.
  2. Clarify the behavior of IdleTimeout and AbsoluteTimeout when both are set. Do they work in conjunction, or does one take precedence?
  3. Explain the implications of manual session release on performance and potential memory leaks if not handled correctly.

These additions would provide a more comprehensive guide for users migrating from v2 to v3.


508-525: Address security implications of CSRF middleware changes.

The CSRF middleware changes are well-documented. However, consider addressing the following points:

  1. Explain the security implications of reducing the default IdleTimeout from 1 hour to 30 minutes. How does this affect the balance between security and user experience?
  2. Clarify whether the removal of the SessionKey field affects existing implementations and if any migration steps are needed.
  3. Provide guidance on best practices for setting the IdleTimeout value in different scenarios (e.g., for highly sensitive operations vs. general use cases).

Adding this information would help users understand the security impact of these changes and how to implement them safely.


Line range hint 527-562: Enhance Filesystem to Static middleware migration guide.

The migration instructions from Filesystem to Static middleware are clear. However, consider adding the following information:

  1. Explain the rationale behind removing the Filesystem middleware and consolidating its functionality into the Static middleware.
  2. Highlight any potential differences in behavior or performance between the old Filesystem middleware and the new Static middleware.
  3. Provide guidance on how to handle more complex scenarios that might have been using specific features of the Filesystem middleware.

This additional context would help users understand the reasons for the change and ensure a smooth migration process.


Line range hint 564-610: Expand on Healthcheck middleware changes and best practices.

The Healthcheck middleware changes are well-documented. To further improve this section, consider:

  1. Explaining the benefits of separating the configuration for each health check endpoint (e.g., improved flexibility, easier maintenance).
  2. Providing guidance on when to use custom endpoints vs. default endpoints.
  3. Adding examples of common use cases for the new startup endpoint.
  4. Discussing best practices for implementing health check probes, including what to check and how to handle dependencies.

This additional information would help users leverage the full potential of the new Healthcheck middleware configuration.


Line range hint 63-148: Enhance Router changes documentation with additional context.

The Router changes are well-documented with clear examples. To further improve this section, consider:

  1. Explaining the rationale behind the changes to the HTTP method registration signatures (e.g., improved type safety, clearer API).
  2. Discussing any performance implications of the new route chaining method compared to the old approach.
  3. Providing guidance on when to use the new route chaining method vs. the traditional approach.
  4. Adding a note about backwards compatibility and any migration steps for existing applications using the old Router methods.

This additional context would help users understand the benefits of the new Router interface and how to best utilize it in their applications.


Line range hint 150-196: Expand the Context section with detailed explanations and examples.

The Context section provides a good overview of the changes, but it's currently marked as a draft. To improve this section:

  1. For each new feature (e.g., Partitioned cookies for CHIPS), provide a brief explanation of its purpose and a code example demonstrating its usage.
  2. For new methods, include short code snippets showing how to use them and when they might be beneficial.
  3. For removed methods, explain the rationale behind their removal and provide guidance on alternatives or migration paths.
  4. For changed methods, clearly explain how the changes affect existing code and provide migration examples.

Adding this level of detail would greatly enhance the usefulness of this section for developers migrating to v3.


Line range hint 612-614: Enhance the overall structure and completeness of the migration guide.

The migration guide covers many important aspects of the transition from v2 to v3. To further improve its usefulness:

  1. Ensure consistency in the level of detail across all sections. Some sections (e.g., Router, Middlewares) are quite detailed, while others (e.g., Parser, Redirect) lack information.
  2. Consider adding a "Breaking Changes" section at the beginning, summarizing all major changes that might affect existing applications.
  3. Include a "Deprecations" section, if applicable, listing features that are deprecated in v3 and will be removed in future versions.
  4. Add a "Best Practices" section, providing guidance on how to best leverage the new features and changes in v3.
  5. Consider adding a "Troubleshooting" section, addressing common issues that users might encounter during migration.

These enhancements would provide a more comprehensive and user-friendly migration guide, helping developers transition smoothly from v2 to v3.

docs/middleware/csrf.md (2)

109-110: LGTM with a minor suggestion

The addition of IdleTimeout in the configuration table is correct. However, consider enhancing the description to provide more context:

- IdleTimeout       | `time.Duration`                    | IdleTimeout is the duration of inactivity before the CSRF token will expire.                                                                                                                                                                                                                 | 30 * time.Minute             |
+ IdleTimeout       | `time.Duration`                    | IdleTimeout is the duration of inactivity before the CSRF token will expire. The token's expiration is extended by this duration with each request.                                                                                                                                         | 30 * time.Minute             |

This additional information helps users understand the dynamic nature of the token expiration.


304-304: LGTM with a minor suggestion for clarity

The explanation of the token lifecycle accurately reflects the new behavior introduced by the IdleTimeout configuration. However, consider a small adjustment for even better clarity:

- Tokens are valid until they expire or until they are deleted. By default, tokens are valid for 30 minutes, and each subsequent request extends the expiration by the idle timeout. The token only expires if the user doesn't make a request for the duration of the idle timeout.
+ Tokens are valid until they expire or until they are deleted. By default, tokens have an idle timeout of 30 minutes. Each request resets this timeout, extending the token's validity. The token only expires if no requests are made for the duration of the idle timeout.

This adjustment more explicitly ties the concept to the IdleTimeout configuration and clarifies the reset behavior.

middleware/session/store_test.go (2)

128-129: Ensure middleware is properly initialized in the test

Lines 128-129 create a new Middleware instance with middleware := &Middleware{} and set it in the context's locals. To accurately simulate the middleware's behavior, ensure that the middleware is properly configured as it would be in a real application. This might involve initializing any necessary fields or using a constructor function if available.


144-155: Include context release in TestStore_Delete subtests

Within the TestStore_Delete function, contexts are not acquired, but if any are introduced in future modifications, remember to release them after use to maintain resource integrity during testing.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8716c95 and f3c4e8e.

📒 Files selected for processing (17)
  • docs/middleware/csrf.md (5 hunks)
  • docs/middleware/session.md (1 hunks)
  • docs/whats_new.md (3 hunks)
  • middleware/csrf/config.go (3 hunks)
  • middleware/csrf/csrf.go (3 hunks)
  • middleware/csrf/csrf_test.go (5 hunks)
  • middleware/csrf/session_manager.go (2 hunks)
  • middleware/session/config.go (4 hunks)
  • middleware/session/config_test.go (1 hunks)
  • middleware/session/data.go (1 hunks)
  • middleware/session/data_msgp.go (2 hunks)
  • middleware/session/data_test.go (1 hunks)
  • middleware/session/middleware.go (1 hunks)
  • middleware/session/session.go (10 hunks)
  • middleware/session/session_test.go (47 hunks)
  • middleware/session/store.go (4 hunks)
  • middleware/session/store_test.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • middleware/csrf/csrf_test.go
  • middleware/session/config_test.go
  • middleware/session/data_test.go
🧰 Additional context used
📓 Learnings (1)
middleware/session/config.go (1)
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/config.go:16-26
Timestamp: 2024-09-25T16:17:00.969Z
Learning: In the session middleware `Config` struct, `Store` is backed by `fiber.Storage`; they are different entities serving distinct purposes in session management.
🪛 LanguageTool
docs/middleware/session.md

[style] ~436-~436: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

🪛 GitHub Check: codecov/patch
middleware/csrf/session_manager.go

[warning] 48-48: middleware/csrf/session_manager.go#L48
Added line #L48 was not covered by tests


[warning] 74-74: middleware/csrf/session_manager.go#L74
Added line #L74 was not covered by tests


[warning] 78-78: middleware/csrf/session_manager.go#L78
Added line #L78 was not covered by tests


[warning] 87-87: middleware/csrf/session_manager.go#L87
Added line #L87 was not covered by tests


[warning] 93-93: middleware/csrf/session_manager.go#L93
Added line #L93 was not covered by tests


[warning] 97-97: middleware/csrf/session_manager.go#L97
Added line #L97 was not covered by tests

middleware/session/config.go

[warning] 130-130: middleware/session/config.go#L130
Added line #L130 was not covered by tests


[warning] 162-162: middleware/session/config.go#L162
Added line #L162 was not covered by tests

middleware/session/data.go

[warning] 37-37: middleware/session/data.go#L37
Added line #L37 was not covered by tests

middleware/session/middleware.go

[warning] 117-117: middleware/session/middleware.go#L117
Added line #L117 was not covered by tests


[warning] 130-133: middleware/session/middleware.go#L130-L133
Added lines #L130 - L133 were not covered by tests


[warning] 144-144: middleware/session/middleware.go#L144
Added line #L144 was not covered by tests

middleware/session/session.go

[warning] 78-78: middleware/session/session.go#L78
Added line #L78 was not covered by tests


[warning] 286-286: middleware/session/session.go#L286
Added line #L286 was not covered by tests


[warning] 288-288: middleware/session/session.go#L288
Added line #L288 was not covered by tests


[warning] 339-339: middleware/session/session.go#L339
Added line #L339 was not covered by tests

middleware/session/store.go

[warning] 167-167: middleware/session/store.go#L167
Added line #L167 was not covered by tests


[warning] 177-178: middleware/session/store.go#L177-L178
Added lines #L177 - L178 were not covered by tests


[warning] 289-289: middleware/session/store.go#L289
Added line #L289 was not covered by tests


[warning] 306-307: middleware/session/store.go#L306-L307
Added lines #L306 - L307 were not covered by tests


[warning] 312-314: middleware/session/store.go#L312-L314
Added lines #L312 - L314 were not covered by tests


[warning] 316-316: middleware/session/store.go#L316
Added line #L316 was not covered by tests

🔇 Additional comments (37)
middleware/csrf/session_manager.go (1)

15-20: Improved type safety for session key management

The introduction of sessionKeyType and the sessionKey constant enhances type safety in session key management. This change aligns with Go best practices and helps prevent potential type-related errors.

middleware/session/config.go (3)

8-8: LGTM: Added log package for error handling

The addition of the log package from github.com/gofiber/fiber/v3/log is appropriate for the new error handling functionality introduced in this update.


108-115: LGTM: Updated ConfigDefault to align with new Config structure

The changes to ConfigDefault correctly reflect the updates made to the Config struct:

  1. Removal of the Expiration field.
  2. Addition of IdleTimeout with a sensible default of 30 minutes.
  3. Explicit setting of source to SourceCookie.

These changes ensure consistency with the new session management approach introduced in this update.


Line range hint 1-190: Summary: Comprehensive improvements to session middleware configuration

This update to middleware/session/config.go successfully addresses the objectives outlined in the PR and the linked GitHub issue:

  1. The session middleware has been re-written with improved configuration options, including IdleTimeout and AbsoluteTimeout, which provide more granular control over session expiration.
  2. Error handling has been enhanced with the introduction of DefaultErrorHandler and improved error messages.
  3. The changes align well with NIST guidelines on distinguishing between timeout and expiration.

The code quality is high, with thorough documentation and thoughtful error handling. The suggested minor improvements, if implemented, will further enhance the robustness and consistency of the package.

Overall, these changes significantly improve the session management capabilities of the Fiber framework.

middleware/csrf/config.go (1)

Line range hint 1-201: Summary of CSRF middleware configuration changes

The changes in this file align well with the PR objectives to address inconsistencies in session and CSRF middleware handling. Key modifications include:

  1. Replacing Expiration with IdleTimeout in the Config struct and ConfigDefault.
  2. Removing the SessionKey field from the Config struct.
  3. Updating the configDefault function to use IdleTimeout.

These changes improve the consistency and clarity of the CSRF middleware configuration. However, they introduce breaking changes that may affect existing implementations, particularly the removal of SessionKey.

To ensure a smooth transition for users of this middleware, consider the following:

  1. Update the package documentation to highlight these breaking changes.
  2. Provide migration guidelines for users updating from the previous version.
  3. Run the following script to identify any internal usages that might need updating:
#!/bin/bash
# Search for usages of Expiration and SessionKey in the codebase
rg --type go '(Expiration|SessionKey)'

This will help ensure that all related code is updated to reflect these changes.

middleware/session/middleware.go (7)

1-10: LGTM: Package declaration and imports are appropriate.

The package name and imports are well-suited for a session middleware implementation in Fiber.


167-184: LGTM: Well-implemented FromContext function.

The FromContext function correctly retrieves the Middleware from the Fiber context and gracefully handles the case where the middleware is not found.


186-233: LGTM: Well-implemented Set, Get, and Delete methods with proper concurrency safety.

These methods provide CRUD operations for session data and use appropriate locking mechanisms to ensure thread safety.


291-301: LGTM: Correctly implemented Store method.

The Store method simply returns the session store from the config, which is the expected behavior.


127-138: Increase test coverage for the saveSession method.

The saveSession method has good error handling, but static analysis indicates that the error handling paths are not covered by tests.

Consider adding test cases that trigger the error handling paths:

  1. Test with a custom ErrorHandler
  2. Test with the DefaultErrorHandler

To verify the current test coverage and identify gaps, run:

#!/bin/bash
# Check test coverage for the saveSession method
go test -v -coverprofile=coverage.out ./middleware/session
go tool cover -func=coverage.out | grep saveSession

This will help identify which parts of the saveSession method need additional test coverage.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 130-133: middleware/session/middleware.go#L130-L133
Added lines #L130 - L133 were not covered by tests


140-165: ⚠️ Potential issue

Improve error handling in acquireMiddleware and increase test coverage.

While using sync.Pool is good for performance, the panic in acquireMiddleware could lead to application crashes.

Consider handling the type assertion error more gracefully:

 func acquireMiddleware() *Middleware {
     m, ok := middlewarePool.Get().(*Middleware)
     if !ok {
-        panic(ErrTypeAssertionFailed.Error())
+        // Log the error and return a new instance
+        log.Printf("Type assertion failed in acquireMiddleware: %v", ErrTypeAssertionFailed)
+        return &Middleware{}
     }
     return m
 }

Increase test coverage for both acquireMiddleware and releaseMiddleware, especially for error cases.

To check the current test coverage and identify gaps:

This will help ensure that all paths in these functions are properly tested.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 144-144: middleware/session/middleware.go#L144
Added line #L144 was not covered by tests


110-125: ⚠️ Potential issue

Improve error handling in the initialize method.

The current implementation panics if there's an error getting the session. This could lead to application crashes in production.

Consider handling the error more gracefully:

 func (m *Middleware) initialize(c fiber.Ctx, cfg Config) {
     m.mu.Lock()
     defer m.mu.Unlock()

     session, err := cfg.Store.getSession(c)
     if err != nil {
-        panic(err) // handle or log this error appropriately in production
+        if cfg.ErrorHandler != nil {
+            cfg.ErrorHandler(c, err)
+        } else {
+            DefaultErrorHandler(c, err)
+        }
+        return
     }

     m.config = cfg
     m.Session = session
     m.ctx = c

     c.Locals(middlewareContextKey, m)
 }

This change ensures that errors are handled consistently with the rest of the middleware.

To ensure this change doesn't introduce new issues, please run the following test:

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 117-117: middleware/session/middleware.go#L117
Added line #L117 was not covered by tests

middleware/csrf/csrf.go (3)

52-52: LGTM: Simplified session manager initialization

This change aligns with the PR objective of re-writing the session middleware. The simplified initialization improves code readability and maintainability.


237-237: LGTM: Consistent use of IdleTimeout in CSRF cookie update

This change is consistent with the previous modification in createOrExtendTokenInStorage. It further aligns the CSRF implementation with NIST guidelines and addresses issue #2741.


220-222: LGTM: Updated token storage with IdleTimeout

This change addresses issue #2741 by replacing Expiration with IdleTimeout, aligning with NIST guidelines on distinguishing between timeout and expiration.

To ensure consistency, let's verify if this change has been applied throughout the codebase:

✅ Verification successful

To ensure that all instances of Expiration have been appropriately replaced with IdleTimeout in the production codebase, let's verify that no such instances remain outside of test files:


Verified: 'Expiration' correctly replaced with 'IdleTimeout' in CSRF middleware

The change addresses issue #2741 by replacing Expiration with IdleTimeout within the CSRF middleware, aligning with NIST guidelines on distinguishing between timeout and expiration. Remaining instances of Expiration in other components like caching and rate limiting are contextually appropriate and do not affect the CSRF functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instances of 'Expiration' related to session or CSRF
# Test: Search for 'Expiration' in Go files. Expect: No occurrences related to session or CSRF timeout/expiration.
rg --type go 'Expiration' -C 3

Length of output: 27282


Script:

#!/bin/bash
# Description: Check for any remaining instances of 'Expiration' in non-test Go files.
# Test: Search for 'Expiration' in Go files excluding test files. Expect: No occurrences related to session or CSRF timeout/expiration.
rg --type go 'Expiration' -g '!*.test.go' -C 3

Length of output: 27298

middleware/session/session.go (4)

15-24: Approved: Session struct changes align with PR objectives

The renaming of exp to idleTimeout and the addition of the fresh field improve session management and align with the PR objectives. These changes address the inconsistencies in session handling and provide better clarity on the session state.


Line range hint 357-387: Approved: Improved setSession method with consistent timeout handling

The changes in the setSession method align well with the PR objectives. The use of idleTimeout instead of Expiration provides consistency with the rest of the session management logic. Setting both MaxAge and Expire for the cookie is a good practice that ensures better compatibility across different browsers.

These modifications contribute to a more robust and consistent session management system.


Line range hint 1-479: Summary: Significant improvements in session management

This PR introduces substantial enhancements to the session middleware, effectively addressing the inconsistencies highlighted in issue #2741. The changes include:

  1. Renaming exp to idleTimeout for clarity.
  2. Adding a fresh field to track new sessions.
  3. Implementing a Release method for efficient session pool management.
  4. Improving the Save method to prevent unnecessary saves.
  5. Adding absolute expiration functionality.

These modifications align well with NIST guidelines and provide a more robust session management system. The suggested improvements, if implemented, will further enhance the code quality and maintainability.

To fully realize the benefits of these changes:

  1. Consider implementing the suggested error handling improvements.
  2. Enhance the documentation as proposed to clarify the different expiration mechanisms.
  3. Improve test coverage for the identified uncovered lines.

Overall, this PR represents a significant step forward in addressing the session management inconsistencies and improving the overall quality of the middleware.


78-78: Consider improving test coverage

Static analysis has identified several lines that are not covered by tests:

  • Line 78 in the Release method
  • Lines 286 and 288 in the Save method
  • Line 339 in the Keys method

While 100% test coverage isn't always necessary or practical, consider adding tests for these cases if feasible. This could improve the robustness of the codebase and catch potential edge case bugs.

To help identify which tests might be missing, you can run the following command:

This will generate an HTML report of the test coverage, which can help visualize which parts of the code need additional testing.

Also applies to: 286-286, 288-288, 339-339

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 78-78: middleware/session/session.go#L78
Added line #L78 was not covered by tests

docs/middleware/session.md (1)

Line range hint 1-458: Overall documentation quality is excellent with minor improvement opportunities

The updated session middleware documentation is comprehensive, well-structured, and informative. It effectively covers the changes introduced in v3 and provides clear guidance for users upgrading from v2. The addition of a migration guide, detailed type descriptions, and various usage examples significantly enhances the documentation's value.

To further improve this already high-quality documentation, consider the following suggestions:

  1. Ensure consistent formatting throughout the document, particularly in method signatures and configuration property descriptions.
  2. Expand examples to demonstrate more real-world scenarios, such as using custom types in sessions.
  3. Add more context to new features like IdleTimeout and AbsoluteTimeout to help users understand their impact on session behavior.
  4. Review the document for any remaining inconsistencies in terminology or explanations.

Overall, this documentation provides an excellent resource for users of the Fiber session middleware.

🧰 Tools
🪛 LanguageTool

[style] ~436-~436: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

docs/middleware/csrf.md (4)

37-37: LGTM: IdleTimeout configuration added correctly

The addition of IdleTimeout set to 30 minutes is consistent with the PR objectives and accurately reflects the new configuration option for the CSRF middleware.


126-126: LGTM: Default configuration updated correctly

The update to use IdleTimeout in the default configuration is consistent with the PR objectives and previous changes in the document. The 30-minute default value is correctly set.


145-145: LGTM: Recommended configuration updated correctly

The update to use IdleTimeout in the recommended configuration is consistent with the PR objectives and previous changes in the document. The 30-minute value is correctly set.


Line range hint 1-324: Overall documentation update is comprehensive and accurate

The changes to this documentation file are consistent and align well with the PR objectives. Key points:

  1. Expiration has been replaced with IdleTimeout throughout the document.
  2. The new default value of 30 minutes is correctly reflected in all relevant sections.
  3. The token lifecycle explanation has been updated to accurately describe the new behavior.

These updates provide clear and accurate information about the new IdleTimeout feature in the CSRF middleware. The documentation now correctly reflects the changes in the middleware's behavior, which will help users understand and implement the CSRF protection effectively.

middleware/session/session_test.go (10)

Line range hint 20-35: Improved session management and resource handling

The changes in this segment enhance the test setup and teardown:

  1. Using NewStore() instead of New() improves naming consistency.
  2. Adding sess.Release() ensures proper resource management.
  3. Releasing and reacquiring the context simulates a new request scenario.

These modifications contribute to more robust and realistic testing of the session middleware.


Line range hint 49-74: Enhanced key type flexibility and consistent resource management

  1. The change from []string{} to []any{} for the keys expectation indicates improved flexibility in key types supported by the session.
  2. The addition of sess.Release() at the end of the test ensures consistent resource cleanup.

These changes improve the robustness of the tests and reflect enhancements in the session implementation.


Line range hint 84-100: Improved resource management and test documentation

The changes in this segment enhance the test in several ways:

  1. Adding sess.Release() ensures proper cleanup of session resources.
  2. Releasing and reacquiring the context helps simulate a fresh request scenario.
  3. The added comments improve the readability and clarity of the test flow.

These modifications contribute to more maintainable and understandable tests.


Line range hint 110-114: Enhanced error handling and test structure

The modifications in this segment improve the test robustness:

  1. Adding defer sess.Release() ensures session cleanup even if the test fails.
  2. Moving the freshness check after the error check improves the logical flow of the test.

These changes contribute to more reliable and structured testing of the session middleware.


Line range hint 121-195: Comprehensive improvements in session testing

This segment demonstrates several enhancements to the session type tests:

  1. Consistent use of NewStore() aligns with earlier changes.
  2. Multiple sess.Release() calls ensure proper resource management throughout the test.
  3. Repeated release and reacquire of the context simulate multiple request scenarios, improving test coverage.
  4. The change from []string{} to []any{} for keys expectation reflects increased flexibility in key types.

These modifications result in more thorough and realistic testing of the session middleware across various data types and scenarios.


330-503: Excellent addition of comprehensive key type testing

The new Test_Session_KeyTypes function greatly enhances the test suite:

  1. It tests a wide range of key and value types, ensuring the session can handle various data types correctly.
  2. The inclusion of checks for unregistered key types verifies the type safety of the session implementation.
  3. The test covers both setting and retrieving values, ensuring consistency across operations.

This addition significantly improves the robustness and reliability of the session middleware by thoroughly testing its type handling capabilities.


Line range hint 557-616: Updated terminology and improved resource management

This segment shows important updates to the session timeout testing:

  1. The function rename from Test_Session_Save_Expiration to Test_Session_Save_IdleTimeout reflects a change in terminology, likely aligning with updated session management concepts.
  2. Replacing SetExpiry with SetIdleTimeout is consistent with this terminology change.
  3. The addition of multiple sess.Release() calls ensures proper resource cleanup throughout the test.

These changes improve the clarity of the test's purpose and maintain consistent resource management practices.


617-681: Valuable addition of absolute timeout testing

The new Test_Session_Save_AbsoluteTimeout function is a significant enhancement to the test suite:

  1. It introduces testing for absolute timeout functionality, complementing the existing idle timeout tests.
  2. The test verifies that sessions expire correctly after the absolute timeout period.
  3. The inclusion of a check for retrieving an expired session by ID covers an important edge case.

This addition ensures more comprehensive coverage of session timeout behaviors, contributing to a more robust and reliable session management system.


Line range hint 690-1260: Consistent application of improved resource management

The remaining changes in the file demonstrate a thorough and consistent approach to resource management:

  1. Multiple instances of sess.Release() and defer sess.Release() have been added across various test and benchmark functions.
  2. The use of defer in appropriate places ensures that sessions are properly released even if a test or benchmark fails.
  3. These changes have been applied consistently throughout the file, including in complex scenarios like concurrency tests.

This systematic improvement in resource handling enhances the reliability and cleanliness of the test suite, reducing the risk of resource leaks and improving overall test stability.


Line range hint 1-1260: Comprehensive enhancements to session middleware testing

The changes in this file represent a significant improvement to the session middleware test suite:

  1. Consistent resource management: The addition of sess.Release() calls throughout the file ensures proper cleanup of session resources.
  2. Improved test coverage: New tests for various key types and absolute timeouts enhance the comprehensiveness of the suite.
  3. Updated terminology: The shift from "expiration" to "idle timeout" reflects evolving session management concepts.
  4. Enhanced error handling: The use of defer for session release improves the robustness of tests.
  5. Better simulation of real-world scenarios: Releasing and reacquiring contexts mimics multiple request lifecycles.

These improvements contribute to a more reliable, thorough, and maintainable test suite, which in turn supports the development of a more robust session middleware.

middleware/session/data_msgp.go (3)

39-42: Ensure correct MessagePack encoding for empty maps.

The EncodeMsg method writes a fixed byte 0x80, which represents an empty map in MessagePack format. Since the data struct appears to have no fields to serialize, this is appropriate. However, confirm that writing an empty map aligns with the expected behavior of the session serialization.

Consider verifying that the data struct has no fields and that clients can correctly deserialize an empty map without errors.


50-50: Consistency in handling empty maps during marshaling.

Similar to EncodeMsg, the MarshalMsg method appends 0x80 to represent an empty map. Ensure that this approach is consistent with the rest of the codebase and that deserialization on the receiving end handles this correctly.

Also applies to: 52-54


89-90: Confirm the Msgsize calculation is accurate.

The Msgsize method now returns a constant value s = 1, which corresponds to the size of an empty map in MessagePack (1 byte for 0x80). Verify that this accurately reflects the serialized size of the data struct.

storeSess, err := m.session.Get(c)
if err != nil {
// Handle error
return nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve test coverage for error handling paths

The static analysis tool has identified several lines that are not covered by tests, primarily in error handling paths. This lack of coverage could lead to undetected issues in error scenarios. Consider adding test cases that exercise these error paths:

  1. Failure to get session from store (lines 48, 74, 93)
  2. Failure to save session (lines 78, 97)
  3. Session deletion (line 87)

Improving test coverage for these scenarios will enhance the reliability of the CSRF middleware and ensure that error handling behaves as expected in various situations.

Would you like assistance in generating test cases for these error handling paths?

Also applies to: 74-74, 78-78, 87-87, 93-93, 97-97

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 48-48: middleware/csrf/session_manager.go#L48
Added line #L48 was not covered by tests

middleware/session/config.go Outdated Show resolved Hide resolved
middleware/csrf/config.go Show resolved Hide resolved
middleware/session/session.go Show resolved Hide resolved
middleware/session/session.go Outdated Show resolved Hide resolved
middleware/session/store.go Show resolved Hide resolved
middleware/session/store.go Outdated Show resolved Hide resolved
middleware/session/store.go Show resolved Hide resolved
middleware/session/store.go Outdated Show resolved Hide resolved
middleware/session/store.go Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (5)
middleware/session/session.go (5)

33-43: Approved: Simplified sessionPool initialization

The change to sessionPool is a good optimization, directly returning a new Session instance. This simplifies the code and potentially improves performance by reducing the need for additional checks or initializations when acquiring a session from the pool.

For consistency, consider updating the byteBufferPool in a similar manner:

 var byteBufferPool = sync.Pool{
 	New: func() any {
-		return new(bytes.Buffer)
+		return &bytes.Buffer{}
 	},
 }

This change would make both pool initializations consistent in their approach.


46-61: Approved: Simplified acquireSession function with minor suggestion

The changes to the acquireSession function are appropriate and align well with the modifications to the Session struct. The removal of the byteBuffer check and setting fresh to true for newly acquired sessions are correct improvements.

Consider improving error handling in the type assertion:

-s := sessionPool.Get().(*Session) //nolint:forcetypeassert,errcheck // We store nothing else in the pool
+s, ok := sessionPool.Get().(*Session)
+if !ok {
+	panic("invalid type in session pool")
+}

This change would make the code more robust against potential future modifications to the pool.


63-85: Approved: New Release method with clear documentation

The addition of the Release method is an excellent improvement for efficient resource management. The detailed documentation clearly explains its purpose and usage, which is crucial for preventing misuse.

For consistency with other methods in the file, consider adding a usage example in the documentation:

// Usage:
//
//	sess := session.Get(ctx)
//	defer sess.Release()

This addition would make the documentation style consistent across all methods.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 82-82: middleware/session/session.go#L82
Added line #L82 was not covered by tests


292-318: Approved: Well-structured saveSession method with suggestion

The new saveSession method is a great addition, providing a clear separation of concerns from the Save method. It handles the core logic of saving the session, including setting the idleTimeout and encoding the data, which aligns well with the PR objectives of improving session management.

Consider enhancing error handling by wrapping the error returned from s.config.Storage.Set:

- return s.config.Storage.Set(s.id, encodedBytes, s.idleTimeout)
+ if err := s.config.Storage.Set(s.id, encodedBytes, s.idleTimeout); err != nil {
+     return fmt.Errorf("failed to save session: %w", err)
+ }
+ return nil

This change would provide more context in case of a storage error, making debugging easier.


463-501: Approved: Enhanced session expiration management with suggestion

The addition of absExpiration, isAbsExpired, and setAbsExpiration methods is an excellent improvement to the session management capabilities. These methods allow for more granular control over session expiration, supporting both idle timeout and absolute (hard) expiration policies. This aligns well with the PR objectives and follows best practices in session management.

For consistency with other methods in the file, consider renaming setAbsExpiration to setAbsoluteExpiration:

-func (s *Session) setAbsExpiration(absExpiration time.Time) {
+func (s *Session) setAbsoluteExpiration(absExpiration time.Time) {

This change would make the method name more explicit and consistent with the full terminology used in the comments.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f3c4e8e and e41ee74.

📒 Files selected for processing (2)
  • middleware/session/session.go (7 hunks)
  • middleware/session/session_test.go (48 hunks)
🧰 Additional context used
📓 Learnings (1)
middleware/session/session.go (1)
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/session.go:272-293
Timestamp: 2024-10-02T15:16:39.868Z
Learning: In the `middleware/session/session.go` file, the `saveSession()` method returns either `nil` or an error, so additional error wrapping in the `Save()` method is unnecessary.
🪛 GitHub Check: codecov/patch
middleware/session/session.go

[warning] 82-82: middleware/session/session.go#L82
Added line #L82 was not covered by tests


[warning] 283-283: middleware/session/session.go#L283
Added line #L283 was not covered by tests


[warning] 285-285: middleware/session/session.go#L285
Added line #L285 was not covered by tests


[warning] 331-331: middleware/session/session.go#L331
Added line #L331 was not covered by tests

🪛 GitHub Check: lint
middleware/session/session_test.go

[failure] 1267-1267:
Duplicate words (app) found (dupword)

🔇 Additional comments (13)
middleware/session/session.go (4)

15-24: Approved: Session struct improvements align with PR objectives

The changes to the Session struct are well-aligned with the PR objectives:

  1. Renaming exp to idleTimeout improves clarity and consistency with NIST guidelines on session management.
  2. The addition of the fresh field allows for better tracking of newly created sessions.

These modifications enhance the overall session management capabilities and readability of the code.


269-290: Approved: Improved Save method with handler-aware logic

The changes to the Save method are well-thought-out and align with the PR objectives. The check for whether the session is being used in the handler prevents unnecessary saves, improving efficiency and potentially avoiding race conditions.

The separation of concerns by introducing a saveSession method is a good practice, enhancing code readability and maintainability.

Note: The static analysis tool indicates that lines 283 and 285 are not covered by tests. Consider adding test cases to cover these new code paths:

  1. When the session is being used in the handler.
  2. When the session is not being used in the handler.

This will ensure the new logic is thoroughly tested and maintain high code coverage.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 283-283: middleware/session/session.go#L283
Added line #L283 was not covered by tests


[warning] 285-285: middleware/session/session.go#L285
Added line #L285 was not covered by tests


336-347: Approved: Consistent renaming of SetIdleTimeout method

The renaming of SetExpiry to SetIdleTimeout is a positive change that aligns well with the PR objectives. This modification:

  1. Improves clarity by using more precise terminology.
  2. Enhances consistency with the new idleTimeout field in the Session struct.
  3. Better reflects the method's purpose in the context of session management.

The updated documentation accurately describes the method's new name and purpose, which is crucial for maintaining clear and usable APIs.


Line range hint 1-501: Summary: Comprehensive improvements to session management

This PR introduces significant enhancements to the session management capabilities:

  1. Improved terminology consistency (e.g., idleTimeout instead of exp).
  2. Enhanced session lifecycle management with the new Release method.
  3. More efficient saving mechanism that avoids unnecessary operations.
  4. Introduction of absolute expiration alongside idle timeout.
  5. Better alignment with NIST guidelines on session management.

These changes effectively address the issues raised in #2741 and improve the overall robustness of the session middleware.

Suggestions for minor improvements have been provided in individual comments, mainly focusing on consistency and error handling. Consider addressing these to further refine the implementation.

Great work on this comprehensive update to the session management system!

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 82-82: middleware/session/session.go#L82
Added line #L82 was not covered by tests

middleware/session/session_test.go (9)

Line range hint 20-35: Improved session store initialization and resource management

The changes in this segment look good. The use of NewStore() aligns with the refactoring mentioned in the PR objectives. Additionally, the introduction of sess.Release() and app.ReleaseCtx(ctx) calls improves resource management by ensuring that resources are properly released after use.


Line range hint 49-74: Enhanced flexibility in session key types

The changes in this segment improve the flexibility of the session middleware by allowing keys of any type, not just strings. This is evident from the change of []string{} to []any{} for the empty keys slice. This enhancement aligns well with the PR objectives of improving session management.


Line range hint 84-110: Improved resource management and error handling

The additions in this segment further enhance resource management. The use of defer sess.Release() ensures that the session is properly released even if an error occurs during the test execution. This is a good practice that improves the robustness of the tests.


Line range hint 121-287: Consistent refactoring applied to test setup

The changes in this large segment are consistent with the overall refactoring of the session middleware. The use of NewStore() and additional Release() calls maintain the improved resource management seen in earlier changes. The core test logic remains unchanged, which is good for preserving test coverage.


330-503: Comprehensive test added for session key types

Excellent addition of the Test_Session_KeyTypes function. This new test significantly enhances the coverage of the session middleware by testing various key types, including both primitive and custom types. The inclusion of checks for unregistered key types is particularly valuable, as it verifies the robustness of the type handling system. This addition aligns well with the PR objectives of improving session management and enhances the overall quality of the test suite.


Line range hint 557-616: Aligned test with new IdleTimeout terminology

The changes in this segment successfully update the test to use the new IdleTimeout terminology instead of Expiration. This includes renaming the test function to Test_Session_Save_IdleTimeout and using SetIdleTimeout instead of SetExpiry. These modifications accurately reflect the changes described in the PR objectives and ensure that the tests remain consistent with the updated session middleware implementation.


617-681: Crucial test added for AbsoluteTimeout functionality

The addition of Test_Session_Save_AbsoluteTimeout is a valuable enhancement to the test suite. This new test function verifies the behavior of sessions with absolute timeout settings, which is an important aspect of session management. The test comprehensively checks for session expiration and ensures that expired sessions cannot be retrieved by ID. This addition significantly improves the test coverage for timeout-related functionality and aligns perfectly with the PR objectives of enhancing session management.


Line range hint 984-1060: Consistent refactoring and improved resource management in benchmarks

The changes in the benchmark functions are consistent with the refactoring seen throughout the file. The use of NewStore() instead of New() aligns with earlier modifications. Importantly, the addition of sess.Release() calls after each benchmark iteration improves resource management, ensuring that sessions are properly cleaned up. These changes contribute to more accurate and reliable benchmark results by preventing resource leaks during testing.


Line range hint 1157-1260: Enhanced concurrency testing with improved resource management

The updates to the concurrency test are well-implemented and improve its robustness. The use of NewStore() is consistent with earlier changes, while the addition of sess.Release() calls ensures proper resource cleanup in concurrent scenarios. The introduction of a buffered channel for collecting errors is a smart improvement that prevents potential goroutine leaks. These changes collectively enhance the reliability of the concurrency test and align well with the overall improvements in resource management throughout the file.

middleware/session/session_test.go Outdated Show resolved Hide resolved
@sixcolors
Copy link
Member Author

Just a reminder: The change to the New() function is a breaking change. It was made to emphasize that the Middleware handler style API is the preferred way to handle sessions. The legacy approach NewStore() is still available for users who do not wish to modify their code to use sessions in a new way. What do you think?

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

🧹 Outside diff range and nitpick comments (2)
middleware/session/session_test.go (2)

764-764: Improved session resource management and updated cookie format check

The changes in the Test_Session_Cookie function demonstrate continued improvements:

  1. Addition of sess.Release() maintains consistent resource management.
  2. The updated cookie format check using a regular expression allows for more flexible validation of the session cookie.

These modifications contribute to better resource handling and more robust cookie validation.

Consider making the regular expression more specific if possible. For example, you could use [a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12} for the UUID part if it follows the standard UUID v4 format. This would provide stricter validation while still allowing for flexibility in other parts of the cookie string.

Also applies to: 776-777, 779-781


1263-1290: Valuable addition of error handling test

The new Test_Session_StoreGetDecodeSessionDataError function is a welcome addition to the test suite:

  1. It verifies the middleware's behavior when encountering invalid or corrupt session data, which is crucial for robust error handling.
  2. The test uses the uuid package to generate a fake session ID, consistent with other changes in the file.
  3. It follows established patterns for store creation and context management.

This test enhances the overall reliability of the session middleware by ensuring proper handling of decode errors.

Consider adding a check to verify that the session was not created or retrieved despite the error. This could be done by attempting to get a value from the session after the error occurs, expecting it to fail or return nil. This would ensure that the middleware doesn't create a new session when it encounters invalid data.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e41ee74 and 07092c8.

📒 Files selected for processing (1)
  • middleware/session/session_test.go (49 hunks)
🔇 Additional comments (15)
middleware/session/session_test.go (15)

11-11: Improved session management and resource handling

The changes in this section demonstrate better resource management practices:

  1. Use of NewStore() instead of New() for creating stores, which likely provides more flexibility or features.
  2. Addition of sess.Release() calls ensures proper cleanup of session resources.
  3. The import of the uuid package suggests enhanced functionality related to unique identifiers.

These modifications contribute to more robust and efficient session handling.

Also applies to: 21-21, 36-37, 89-89, 100-101


50-50: Enhanced type flexibility in session data handling

The modifications in the Test_Session_Types function demonstrate improved type handling:

  1. Session keys are now managed using []any instead of []string, allowing for more flexible data types in sessions.
  2. Consistent with earlier changes, sess.Release() calls have been added to ensure proper resource cleanup.

These changes contribute to more versatile session data management and maintain the improved resource handling pattern.

Also applies to: 64-64, 75-75, 196-196


297-297: Consistent improvements in resource management

The changes in the Test_Session_Store_Reset function maintain the pattern of improvements seen throughout the file:

  1. Use of NewStore() for store creation.
  2. Addition of sess.Release() for proper session cleanup.
  3. Use of defer app.ReleaseCtx(ctx) ensures context release even in case of panics or early returns.

These modifications contribute to more robust and consistent resource management across different test scenarios.

Also applies to: 317-325


331-504: Comprehensive new test for session key types

The addition of the Test_Session_KeyTypes function significantly enhances the test suite:

  1. It verifies the behavior of various key types in session data, including standard types and custom structs.
  2. The test includes both positive cases (registered types) and negative cases (unregistered types), ensuring robust type handling.
  3. It follows the established patterns of using NewStore(), sess.Release(), and deferred context release, maintaining consistency with other tests.

This new test function greatly improves the coverage and reliability of the session middleware's type handling capabilities.


558-558: Improved session timeout handling and consistent resource management

The changes in the Test_Session_Save_IdleTimeout function (previously Test_Session_Save_Expiration) demonstrate important improvements:

  1. The renaming of the function and the change from SetExpiry to SetIdleTimeout indicate a more precise conceptualization of session timeouts, likely aligning better with real-world usage patterns.
  2. The addition of sess.Release() calls maintains the consistent pattern of improved resource management seen throughout the file.

These modifications contribute to more accurate session timeout testing and maintain the improved resource handling pattern.

Also applies to: 583-583, 589-603


618-682: Comprehensive new test for absolute session timeouts

The addition of the Test_Session_Save_AbsoluteTimeout function significantly enhances the test suite:

  1. It verifies the behavior of sessions with absolute timeout settings, a crucial aspect of session management.
  2. The test covers both the validity of the session before expiration and the proper handling of expired sessions.
  3. It includes an important check for the inability to retrieve an expired session by ID, ensuring proper security measures.
  4. The function follows the established patterns of using NewStore(), sess.Release(), and deferred context release, maintaining consistency with other tests.

This new test function greatly improves the coverage and reliability of the session middleware's timeout handling capabilities, particularly for absolute timeouts.


691-691: Consistent improvement in session resource management

The changes in the Test_Session_Destroy function maintain the pattern of improved resource handling:

  1. Addition of sess.Release() calls ensures proper cleanup of session resources.
  2. Use of defer sess.Release() in the second part of the test guarantees session cleanup even in case of test failures.

These modifications contribute to more robust and consistent resource management, aligning with the improvements seen throughout the file.

Also applies to: 700-700, 730-730, 739-739


752-753: Consistent updates to session configuration testing

The changes in the Test_Session_Custom_Config function align with updates seen elsewhere in the file:

  1. Use of NewStore() instead of New() for creating session stores.
  2. Testing of IdleTimeout instead of Expiration, reflecting the shift in timeout handling terminology and functionality.

These modifications ensure that the custom configuration tests remain consistent with the updated session middleware API and concepts.

Also applies to: 756-757


788-788: Consistent improvement in session resource management

The changes in the Test_Session_Cookie_In_Middleware_Chain function maintain the pattern of improved resource handling:

  1. Addition of sess.Release() calls ensures proper cleanup of session resources.
  2. Use of defer sess.Release() guarantees session cleanup even in case of test failures.

These modifications contribute to more robust and consistent resource management, aligning with the improvements seen throughout the file.

Also applies to: 803-804, 807-807


820-820: Consistent improvement in session resource management

The changes in the Test_Session_Deletes_Single_Key function maintain the pattern of improved resource handling:

  1. Addition of sess.Release() calls ensures proper cleanup of session resources.
  2. Use of defer sess.Release() guarantees session cleanup even in case of test failures.

These modifications contribute to more robust and consistent resource management, aligning with the improvements seen throughout the file.

Also applies to: 831-831, 841-841, 847-847


862-862: Consistent updates and improvements in session handling

The changes in the Test_Session_Reset function align with improvements seen throughout the file:

  1. Use of NewStore() instead of New() for creating session stores.
  2. Addition of sess.Release() calls for proper resource management.
  3. Updated check for empty keys using []any{} instead of []string{}, consistent with the improved type flexibility in session data handling.

These modifications ensure that the session reset tests remain consistent with the updated session middleware API and concepts, while also improving resource management.

Also applies to: 884-884, 906-906, 917-918


936-936: Consistent improvements in session handling and resource management

The changes in the Test_Session_Regenerate function align with improvements seen throughout the file:

  1. Use of NewStore() instead of New() for creating session stores.
  2. Addition of sess.Release() calls for proper resource management.
  3. Use of defer sess.Release() ensures session cleanup even in case of test failures.

These modifications contribute to more robust and consistent resource management, while keeping the test aligned with the updated session middleware API.

Also applies to: 952-953, 966-966


985-985: Improved resource management in benchmark functions

The changes in all benchmark functions demonstrate a consistent improvement in resource handling:

  1. Addition of sess.Release() calls ensures proper cleanup of session resources after each benchmark iteration.
  2. Consistent use of NewStore() instead of New() for creating session stores.

These modifications are crucial for several reasons:

  • They ensure that the benchmarks accurately reflect the true performance characteristics of the session middleware, including resource cleanup.
  • They prevent potential resource leaks during benchmarking, which could skew results.
  • They maintain consistency with the improvements made in the test functions, ensuring that benchmarks and tests use the middleware in the same way.

By implementing these changes, the benchmarks now provide a more accurate representation of the session middleware's performance and resource usage.

Also applies to: 996-997, 1003-1003, 1016-1017, 1025-1025, 1036-1038, 1046-1046, 1059-1061, 1071-1071, 1084-1084, 1090-1090, 1105-1105, 1113-1113, 1125-1125, 1133-1133, 1147-1147


Line range hint 1158-1262: Excellent addition of comprehensive concurrency test

The new Test_Session_Concurrency function is a significant and valuable addition to the test suite:

  1. It verifies the thread-safety of the session middleware by simulating concurrent access using goroutines.
  2. The test covers crucial aspects of session handling in a concurrent environment:
    • Session creation and retrieval
    • Data persistence across requests
    • Proper handling of session freshness
    • Correct functioning of session destruction
  3. It employs good concurrent programming practices:
    • Use of sync.WaitGroup for synchronization
    • Buffered channel for collecting errors from goroutines
    • Proper resource management with deferred releases

This test greatly enhances the reliability of the session middleware by ensuring its correct behavior under concurrent access, which is crucial for real-world web applications.


Line range hint 1-1290: Summary of improvements in session middleware tests

The changes in this file represent a significant enhancement to the session middleware test suite:

  1. Consistent improvement in resource management:

    • Addition of sess.Release() calls throughout all tests and benchmarks.
    • Use of defer for ensuring cleanup in various scenarios.
  2. API updates:

    • Consistent use of NewStore() instead of New() for store creation.
    • Shift from Expiration to IdleTimeout in configuration and testing.
  3. Enhanced type handling:

    • Use of []any instead of []string for session keys, allowing more flexible data types.
  4. New comprehensive tests:

    • Addition of Test_Session_KeyTypes for thorough type handling verification.
    • Introduction of Test_Session_Save_AbsoluteTimeout for testing absolute timeout behavior.
    • Implementation of Test_Session_Concurrency for verifying thread-safety.
    • Addition of Test_Session_StoreGetDecodeSessionDataError for robust error handling checks.
  5. Improved benchmark accuracy:

    • Inclusion of resource cleanup in benchmarks for more realistic performance measurements.

These changes collectively contribute to a more robust, reliable, and comprehensive test suite for the session middleware. The improvements in resource management and the addition of new test scenarios will likely lead to increased stability and accuracy in test results, as well as better coverage of real-world usage patterns and edge cases.

- Update absolute timeout handling in getSession function
- Set absolute expiration time in getSession function
- Delete expired session in GetByID function
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

🧹 Outside diff range and nitpick comments (8)
middleware/session/store.go (4)

35-45: Improved function naming and documentation

The renaming of New to NewStore and the addition of detailed documentation enhance the clarity and usability of the function.

Consider updating the usage example to reflect the new function name:

-	store := session.New()
+	store := session.NewStore()

164-169: Improved error handling in getSession method

The addition of error handling for session data decoding enhances the robustness of the method. The mutex is properly unlocked before returning the error, which is a good practice.

Consider using errors.Join for cleaner error wrapping:

-			return nil, fmt.Errorf("failed to decode session data: %w", err)
+			return nil, errors.Join(errors.New("failed to decode session data"), err)

172-182: Enhanced session expiration handling

The addition of absolute session expiration handling improves the overall session management. The logic for resetting expired sessions and setting new expiration times is well-implemented.

Consider using errors.Join for cleaner error wrapping in the session reset error:

-			return nil, fmt.Errorf("failed to reset session: %w", err)
+			return nil, errors.Join(errors.New("failed to reset session"), err)

256-324: New GetByID method with comprehensive implementation

The addition of the GetByID method provides a useful way to retrieve sessions directly by ID. The implementation includes proper error handling, session expiration checks, and cleanup of expired sessions. The detailed documentation clearly explains the method's behavior and potential pitfalls.

Consider using errors.Join for cleaner error wrapping in the session data decoding error:

-		return nil, fmt.Errorf("failed to decode session data: %w", err)
+		return nil, errors.Join(errors.New("failed to decode session data"), err)
middleware/session/session_test.go (4)

331-504: LGTM: Comprehensive key type testing added

The new Test_Session_KeyTypes function significantly enhances the test coverage for session functionality. It thoroughly tests various key types, including both registered and unregistered types, which is crucial for ensuring type safety and correct behavior of the session store.

The test function includes proper resource management with deferred releases, aligning with the improved practices seen throughout the file.

This addition aligns well with the PR objectives and greatly improves the robustness of the test suite.

Consider adding error checking when setting unregistered key types. For example:

err := sess.Set(unregisteredKey, "test")
require.Error(t, err, "Expected an error when setting an unregistered key type")

This would make the test even more thorough by explicitly checking that setting unregistered types results in an error.


Line range hint 558-700: LGTM: Enhanced timeout testing and consistent resource management

The updates to Test_Session_Save_IdleTimeout (renamed from Test_Session_Save_Expiration) and the addition of Test_Session_Save_AbsoluteTimeout align well with the PR objectives. These changes provide better coverage for the timeout functionality, including the new absolute timeout feature.

The consistent use of NewStore() for initialization and the addition of session releases improve resource management throughout these tests.

For consistency, consider adding error checking for sess.Save() calls in both functions. For example:

err = sess.Save()
require.NoError(t, err, "Failed to save session")

This would make the error handling more robust and consistent across all test functions.


1281-1319: LGTM: Comprehensive error handling test added

The new Test_Session_StoreGetDecodeSessionDataError function significantly enhances the test coverage for error handling when decoding invalid session data. It properly tests both the Get() and GetByID() methods, ensuring that appropriate errors are returned when dealing with corrupted session data.

This addition aligns well with the PR objectives of improving session management and error handling, contributing to the overall robustness of the session middleware.

For consistency with other tests in the file, consider using require.ErrorIs() instead of require.ErrorContains() when checking for specific errors. For example:

require.ErrorIs(t, err, ErrFailedToDecodeSessionData, "Unexpected error")

This assumes that there's a specific error type ErrFailedToDecodeSessionData defined for this case. If not, the current implementation is appropriate.

🧰 Tools
🪛 GitHub Check: lint

[failure] 1281-1281:
empty-lines: extra empty line at the end of a block (revive)


[failure] 1319-1319:
unnecessary trailing newline (whitespace)


1281-1281: Minor: Address linting issues

There are two minor linting issues in the file:

  1. An extra empty line at the end of a block (line 1281).
  2. An unnecessary trailing newline (line 1319).

While these don't affect functionality, addressing them would improve code consistency and adhere to Go style guidelines.

Consider making the following changes:

  1. Remove the extra empty line at line 1281.
  2. Remove the trailing newline at line 1319.

These minor adjustments will resolve the linting warnings and improve the overall code style consistency.

Also applies to: 1319-1319

🧰 Tools
🪛 GitHub Check: lint

[failure] 1281-1281:
empty-lines: extra empty line at the end of a block (revive)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 07092c8 and 84adbe1.

📒 Files selected for processing (2)
  • middleware/session/session_test.go (49 hunks)
  • middleware/session/store.go (4 hunks)
🧰 Additional context used
🪛 GitHub Check: lint
middleware/session/session_test.go

[failure] 1281-1281:
empty-lines: extra empty line at the end of a block (revive)


[failure] 1319-1319:
unnecessary trailing newline (whitespace)

🔇 Additional comments (35)
middleware/session/store.go (8)

16-20: Improved error handling with new error variables

The addition of these new error variables enhances the error handling capabilities of the package. The error messages are consistent in capitalization and terminology, following Go conventions.


53-62: Enhanced NewStore function with custom type registration

The addition of custom type registration for AbsoluteTimeout improves the flexibility of the session store. This change allows for better handling of absolute timeouts in sessions.


77-104: Improved Get method with better documentation and session loading check

The Get method has been enhanced with detailed documentation and a check to prevent duplicate session loading. This improvement helps prevent potential issues and improves the overall robustness of the session handling.


106-121: Added documentation for getSession method

The addition of detailed documentation for the getSession method improves the overall clarity of the codebase and helps developers understand the method's purpose and usage.


187-196: Added documentation for getSessionID method

The addition of detailed documentation for the getSessionID method enhances the overall clarity of the codebase and aids developers in understanding the method's purpose and usage.


221-230: Added documentation for Reset method

The addition of detailed documentation for the Reset method improves the overall clarity of the codebase and helps developers understand the method's purpose and potential error handling.


236-248: Added documentation for Delete method

The addition of detailed documentation for the Delete method enhances the overall clarity of the codebase and aids developers in understanding the method's purpose, parameters, and potential error handling.


Line range hint 1-324: Overall assessment: Significant improvements to the session store implementation

The changes made to middleware/session/store.go represent a substantial improvement to the session management functionality. Key enhancements include:

  1. Introduction of specific error variables for better error handling.
  2. Renaming of the New function to the more descriptive NewStore.
  3. Addition of comprehensive documentation for all methods.
  4. Implementation of absolute timeout handling for sessions.
  5. Introduction of the GetByID method for direct session retrieval.

These changes collectively improve the package's usability, robustness, and maintainability. The code is well-structured, and the new features are implemented with careful consideration for error handling and edge cases.

middleware/session/session_test.go (27)

11-11: LGTM: Added UUID package import

The addition of the github.com/google/uuid import is appropriate for generating UUIDs in the tests. This is a reliable and widely-used package for this purpose.


21-21: LGTM: Updated store initialization

The change from New() to NewStore() is consistent with the PR objectives mentioning a re-write of the session middleware. This new initialization method likely provides enhanced functionality or configuration options.


36-37: LGTM: Improved resource management

The addition of sess.Release() and the reacquisition of the context enhance resource management and ensure a clean state for subsequent test operations. This change aligns with best practices for handling sessions and contexts in tests.


50-50: LGTM: Enhanced type flexibility for session keys

The change from []string{} to []any{} in the assertions for sess.Keys() indicates increased flexibility in the types of keys that can be stored in the session. This modification allows for a more versatile session storage system.

Also applies to: 64-64


85-87: LGTM: Consistent resource cleanup

The addition of explicit sess.Release() and app.ReleaseCtx(ctx) calls ensures proper cleanup of resources after test operations. This change is consistent with earlier modifications and reinforces good resource management practices throughout the test suite.


100-101: LGTM: Consistent session release

The addition of sess.Release() after checking for a fresh session ensures consistent resource cleanup, even in this specific test scenario. This change aligns with the improved resource management practices implemented throughout the test suite.


111-111: LGTM: Robust session cleanup with defer

The addition of a deferred sess.Release() call ensures that the session is properly released even in case of early returns or panics. This is a robust Go practice for resource management and improves the overall reliability of the test cleanup.


122-122: LGTM: Consistent store initialization

The change from New() to NewStore() in the Test_Session_Types function maintains consistency with earlier modifications. This ensures that the new store initialization method is used uniformly across all tests in the suite.


196-198: LGTM: Consistent resource management in Test_Session_Types

The addition of session release and context reacquisition in the Test_Session_Types function maintains consistency with the resource management improvements implemented throughout the test suite. These changes ensure a clean state between different parts of the test, enhancing test isolation and reliability.


288-289: LGTM: Final session cleanup in Test_Session_Types

The addition of sess.Release() at the end of the Test_Session_Types function ensures proper cleanup of the session resource. This change completes the consistent resource management pattern implemented throughout the test suite.


297-297: LGTM: Consistent store initialization in Test_Session_Store_Reset

The change from New() to NewStore() in the Test_Session_Store_Reset function maintains consistency with earlier modifications. This ensures that the new store initialization method is used uniformly across all tests in the suite.


317-325: LGTM: Enhanced resource management in Test_Session_Store_Reset

The additions of session release, context reacquisition, and deferred releases in the Test_Session_Store_Reset function align with the improved resource management practices implemented throughout the test suite. The use of defer ensures proper cleanup even in case of early returns or panics, enhancing overall test reliability.


513-513: LGTM: Consistent store initialization in Test_Session_Save

The change from New() to NewStore() in the Test_Session_Save function maintains consistency with earlier modifications. This ensures that the new store initialization method is used uniformly across all tests in the suite.


528-528: LGTM: Consistent session cleanup in Test_Session_Save

The addition of sess.Release() calls at the end of each subtest in Test_Session_Save ensures proper cleanup of session resources. These changes maintain consistency with the improved resource management practices implemented throughout the test suite.

Also applies to: 554-554


709-709: LGTM: Consistent updates in Test_Session_Destroy

The changes in Test_Session_Destroy, including the use of NewStore() for initialization and the addition of session releases, align with the modifications seen throughout the file. These updates improve resource management and maintain consistency across the test suite.

Also applies to: 730-730, 748-748, 757-757


770-775: LGTM: Improved configuration testing

The updates in Test_Session_Custom_Config enhance the testing of configuration options. The use of NewStore() with custom configuration and the checks for both custom and default values provide better coverage for the store's configuration capabilities.


782-782: LGTM: Enhanced cookie testing and consistent updates

The changes in Test_Session_Cookie, including the use of NewStore(), addition of session release, and updated cookie checking logic, align with the improvements seen throughout the file. The more specific cookie validation enhances the test's effectiveness.

Also applies to: 794-795, 797-799


806-806: LGTM: Consistent updates in middleware chain test

The changes in Test_Session_Cookie_In_Middleware_Chain, including the use of NewStore() and the addition of session releases, align with the improvements seen throughout the file. These updates enhance resource management and maintain consistency across the test suite.

Also applies to: 821-822, 825-825


838-838: LGTM: Consistent resource management in single key deletion test

The updates in Test_Session_Deletes_Single_Key, including the use of NewStore() and the addition of session releases (including a deferred release), align with the improvements seen throughout the file. These changes enhance resource management and maintain consistency across the test suite.

Also applies to: 849-849, 859-859, 865-865


880-880: LGTM: Consistent updates and improved type handling in reset test

The changes in Test_Session_Reset, including the use of NewStore(), addition of session releases, and updated type assertion, align with the improvements seen throughout the file. The change from []string to []any enhances type flexibility. These updates improve resource management and maintain consistency across the test suite.

Also applies to: 902-902, 924-924, 935-936


954-954: LGTM: Consistent updates in regenerate test

The changes in Test_Session_Regenerate, including the use of NewStore() and the addition of session releases, align with the improvements seen throughout the file. These updates enhance resource management and maintain consistency across the test suite.

Also applies to: 970-971, 984-984


Line range hint 1003-1015: LGTM: Improved resource management in benchmarks

The updates in Benchmark_Session, including the use of NewStore() and the addition of session releases within the benchmark loops, align with the improvements seen throughout the file. These changes ensure proper resource management even during performance testing, which is crucial for accurate benchmarking results.

Also applies to: 1021-1035


Line range hint 1043-1056: LGTM: Consistent resource management in parallel benchmarks

The changes in Benchmark_Session_Parallel, including the use of NewStore() and the addition of session releases within the parallel benchmark loops, align with the improvements seen throughout the file. These updates ensure proper resource management even during parallel performance testing, which is essential for accurate and reliable benchmark results.

Also applies to: 1064-1079


Line range hint 1089-1102: LGTM: Improved resource management in asserted benchmarks

The updates in Benchmark_Session_Asserted, including the use of NewStore() and the addition of session releases within the asserted benchmark loops, align with the improvements seen throughout the file. These changes ensure proper resource management even during asserted performance testing, contributing to more accurate and reliable benchmark results.

Also applies to: 1108-1123


Line range hint 1131-1143: LGTM: Consistent resource management in parallel asserted benchmarks

The changes in Benchmark_Session_Asserted_Parallel, including the use of NewStore() and the addition of session releases within the parallel asserted benchmark loops, align with the improvements seen throughout the file. These updates ensure proper resource management even during parallel asserted performance testing, contributing to more accurate and reliable benchmark results.

Also applies to: 1151-1165


1176-1176: LGTM: Enhanced resource management in concurrency test

The updates in Test_Session_Concurrency, including the use of NewStore() and the addition of session releases in concurrent test operations, align with the improvements seen throughout the file. These changes ensure proper resource management even during concurrent testing scenarios, which is crucial for detecting race conditions and ensuring thread-safety of the session handling.

Also applies to: 1190-1190, 1214-1216, 1233-1233


Line range hint 1-1319: Overall: Significant improvements in session testing and resource management

This update to the session middleware test file brings substantial enhancements:

  1. Consistent use of NewStore() for initialization across all tests and benchmarks.
  2. Significantly improved resource management with consistent session releases.
  3. Enhanced test coverage, including new tests for key types, absolute timeout, and error handling.
  4. Updated benchmarks to ensure proper resource management during performance testing.
  5. Improved concurrency testing to ensure thread-safety of session handling.

These changes align well with the PR objectives of re-writing the session middleware with improved management and error handling. The expanded test coverage, especially for new features like absolute timeout and various key types, contributes to the overall robustness of the session middleware.

The consistent updates across all test

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

🧹 Outside diff range and nitpick comments (6)
middleware/session/store.go (3)

35-62: Improved NewStore function with enhanced documentation and features

The renaming of New to NewStore and the addition of detailed documentation significantly improve the function's clarity and usability. The new absolute timeout handling is a valuable addition to session management.

Consider updating the usage example in the documentation to reflect the new function name:

-	store := session.New()
+	store := session.NewStore()

Line range hint 121-182: Improved getSession method with enhanced session management

The additions to handle session freshness, expiration, and absolute timeouts significantly improve the session management capabilities. The error handling for session data decoding has also been enhanced.

However, there's a potential issue with error variable shadowing in the data decoding error handling. Consider the following change:

-		err := sess.decodeSessionData(rawData)
+		decodeErr := sess.decodeSessionData(rawData)
 		sess.data.Unlock()
-		if err != nil {
+		if decodeErr != nil {
 			sess.mu.Unlock()
-			return nil, fmt.Errorf("failed to decode session data: %w", err)
+			return nil, fmt.Errorf("failed to decode session data: %w", decodeErr)
 		}

This change prevents shadowing the outer err variable and ensures that the correct error is being wrapped and returned.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 178-178: middleware/session/store.go#L178
Added line #L178 was not covered by tests


178-178: Improve test coverage for error handling paths

The static analysis tool has identified three lines that are not covered by tests:

  1. Line 178: Error handling for session reset in getSession
  2. Line 290: Error handling for storage retrieval in GetByID
  3. Line 315: Error handling for session destruction in GetByID

Consider adding unit tests to cover these error scenarios. This will ensure that the error handling paths are working as expected and improve the overall robustness of the package.

Also applies to: 290-290, 315-315

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 178-178: middleware/session/store.go#L178
Added line #L178 was not covered by tests

middleware/session/session.go (3)

46-61: Approved: acquireSession function improvements with suggestion

The changes to acquireSession function are appropriate. Setting fresh to true for newly acquired sessions is correct. The removal of the byteBuffer check is safe as it's always initialized in the pool's New function.

However, consider improving error handling in the type assertion:

-	s := sessionPool.Get().(*Session) //nolint:forcetypeassert,errcheck // We store nothing else in the pool
+	s, ok := sessionPool.Get().(*Session)
+	if !ok {
+		panic("invalid type in session pool")
+	}

This change would make the code more robust against potential future modifications to the pool.


63-85: Approved: New Release method with suggestion

The addition of the Release method is an excellent improvement for resource management. The detailed documentation clearly explains its usage and limitations.

Consider adding a check to prevent double release:

 func (s *Session) Release() {
 	if s == nil {
 		return
 	}
+	if s.data == nil {
+		// Session already released
+		return
+	}
 	releaseSession(s)
 }

This change would make the method more robust against potential misuse.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 82-82: middleware/session/session.go#L82
Added line #L82 was not covered by tests


475-513: Approved: New methods for absolute expiration management

The addition of absExpiration, isAbsExpired, and setAbsExpiration methods provides a robust mechanism for managing absolute expiration times for sessions. This aligns well with the PR objectives for improved session management.

Consider adding a method to clear the absolute expiration:

// clearAbsExpiration removes the absolute expiration time from the session.
func (s *Session) clearAbsExpiration() {
	s.Delete(absExpirationKey)
}

This would provide a convenient way to remove the absolute expiration if needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 84adbe1 and eac16b6.

📒 Files selected for processing (4)
  • middleware/session/session.go (8 hunks)
  • middleware/session/session_test.go (50 hunks)
  • middleware/session/store.go (4 hunks)
  • middleware/session/store_test.go (6 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
middleware/session/session.go

[warning] 82-82: middleware/session/session.go#L82
Added line #L82 was not covered by tests


[warning] 287-287: middleware/session/session.go#L287
Added line #L287 was not covered by tests


[warning] 289-289: middleware/session/session.go#L289
Added line #L289 was not covered by tests


[warning] 335-335: middleware/session/session.go#L335
Added line #L335 was not covered by tests

middleware/session/store.go

[warning] 178-178: middleware/session/store.go#L178
Added line #L178 was not covered by tests


[warning] 290-290: middleware/session/store.go#L290
Added line #L290 was not covered by tests


[warning] 315-315: middleware/session/store.go#L315
Added line #L315 was not covered by tests

🔇 Additional comments (28)
middleware/session/store_test.go (7)

23-23: LGTM: Consistent renaming of New() to NewStore()

The changes in the Test_Store_getSessionID function correctly implement the renaming of New() to NewStore(). This maintains consistency with the updated API and doesn't alter the logic of the test cases.

Also applies to: 36-38, 51-53


76-76: LGTM: Consistent renaming in Test_Store_Get

The change in the Test_Store_Get function correctly implements the renaming of New() to NewStore(). This maintains consistency with the updated API and doesn't alter the logic of the test case.


96-96: LGTM: Consistent renaming in Test_Store_DeleteSession

The change in the Test_Store_DeleteSession function correctly implements the renaming of New() to NewStore(). This maintains consistency with the updated API and doesn't alter the logic of the test case.


120-140: Good addition, but consider using NewStore()

The new test case TestStore_Get_SessionAlreadyLoaded is a valuable addition, covering an important error scenario. However, at line 132, consider using NewStore() instead of &Store{} to ensure proper initialization and consistency with other tests:

store := NewStore()

This change will ensure that any initialization logic in NewStore() is not bypassed.


142-156: LGTM: Comprehensive test cases for Delete method

The new TestStore_Delete function adds valuable test coverage for the Delete method. It correctly tests two important scenarios:

  1. Attempting to delete with an empty session ID (expecting an error).
  2. Attempting to delete a non-existing session (expecting no error).

The use of NewStore() is consistent with other tests, and the error checking is appropriate.


158-218: LGTM with a suggestion: Release the acquired context

The new Test_Store_GetByID function is a great addition, providing comprehensive coverage for the GetByID method across various scenarios. However, there's a minor improvement to be made:

At line 182, a new context is acquired:

ctx := fiber.New().AcquireCtx(&fasthttp.RequestCtx{})

To prevent potential resource leaks, especially in tests that may run in parallel, it's recommended to release this context after use. Add the following line at the end of the "valid session ID" subtest:

fiber.New().ReleaseCtx(ctx)

This ensures proper cleanup of resources and aligns with best practices for context management in Fiber.


Line range hint 1-218: Overall assessment: Good improvements with minor suggestions

The changes to middleware/session/store_test.go are generally well-implemented and valuable:

  1. Consistent renaming of New() to NewStore() throughout the file.
  2. Addition of new test cases (TestStore_Get_SessionAlreadyLoaded, TestStore_Delete, and Test_Store_GetByID) that improve coverage and test important scenarios.

Minor suggestions for improvement:

  1. In TestStore_Get_SessionAlreadyLoaded, consider using NewStore() instead of &Store{} for consistency.
  2. In the "valid session ID" subtest of Test_Store_GetByID, remember to release the acquired context to prevent potential resource leaks.

These changes significantly enhance the test suite for the session middleware, providing better coverage and aligning with best practices.

middleware/session/store.go (4)

16-20: Improved error handling with new error variables

The addition of these new error variables enhances the error handling capabilities of the package. The error messages are clear, consistent, and follow Go conventions.


77-104: Enhanced Get method with duplicate loading prevention

The addition of a check for an already loaded session is a valuable safeguard against potential inconsistencies. The detailed documentation provides clear guidance on the method's behavior and possible errors.


236-254: Improved Delete method with input validation

The addition of detailed documentation and the check for an empty session ID enhance the method's usability and robustness. The empty ID check is a good safeguard against potential errors.


Line range hint 1-322: Overall assessment: Significant improvements to session management

The changes made to middleware/session/store.go represent a substantial enhancement to the session management capabilities of the package. Key improvements include:

  1. Better error handling with new, specific error variables
  2. Enhanced documentation across all methods
  3. Improved session retrieval and management logic
  4. New features such as absolute timeout handling

The identified issues are minor and can be easily addressed. Once these are resolved and test coverage is improved for the error handling paths, the changes will greatly benefit the overall quality and functionality of the session management system.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 290-290: middleware/session/store.go#L290
Added line #L290 was not covered by tests


[warning] 315-315: middleware/session/store.go#L315
Added line #L315 was not covered by tests

middleware/session/session.go (8)

15-24: Approved: Session struct improvements

The changes to the Session struct are well-aligned with the PR objectives. Renaming exp to idleTimeout improves clarity, and the addition of the fresh field enhances session management capabilities.


26-31: Approved: New constants for absolute expiration

The addition of absExpirationKeyType and absExpirationKey provides a structured way to manage absolute expiration times for sessions. This enhancement aligns well with the PR objectives for improved session management.


41-42: Approved: Improved sessionPool initialization

The change to return a pointer to a new Session in the sessionPool's New function ensures proper initialization of new sessions. This is a good practice for memory management and consistency.


296-322: Approved: New saveSession method for improved session management

The addition of the saveSession method is a good improvement in code organization. It separates the concerns of saving session data from the main Save method, enhancing maintainability. The automatic setting of idleTimeout ensures consistent session management across the application.


340-351: Approved: Renamed SetIdleTimeout method

The renaming of SetExpiry to SetIdleTimeout is a positive change that improves clarity and consistency in the API. This aligns well with the PR objectives to address inconsistencies in session handling. The updated documentation accurately reflects the method's purpose.


Line range hint 354-387: Approved: Updated setSession method using idleTimeout

The changes in the setSession method correctly implement the use of idleTimeout for setting cookie expiration. This is consistent with the earlier changes in the Session struct and ensures that session cookies are managed correctly based on the idle timeout.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 287-287: middleware/session/session.go#L287
Added line #L287 was not covered by tests


[warning] 289-289: middleware/session/session.go#L289
Added line #L289 was not covered by tests


[warning] 335-335: middleware/session/session.go#L335
Added line #L335 was not covered by tests


Line range hint 1-513: Overall assessment: Significant improvements in session management

This PR introduces substantial enhancements to the session middleware:

  1. Improved clarity with the renaming of exp to idleTimeout.
  2. Enhanced resource management with the new Release method.
  3. More efficient session saving with handler-aware checks.
  4. Better separation of concerns with the new saveSession method.
  5. Introduction of absolute expiration management.

These changes align well with the PR objectives and address the issues raised in #2741. The code is generally well-structured and documented.

Some minor suggestions for improvement have been made:

  • Enhancing error handling in acquireSession.
  • Adding a check to prevent double release in the Release method.
  • Improving test coverage for the new code paths in the Save method.
  • Adding a method to clear absolute expiration.

Overall, this is a solid improvement to the session middleware.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 82-82: middleware/session/session.go#L82
Added line #L82 was not covered by tests


269-294: Approved: Improved Save method with handler-aware logic

The changes to the Save method are well-thought-out and align with the PR objectives. The check for whether the session is being used in the handler prevents unnecessary saves, improving efficiency.

Note: The static analysis tool indicates that lines 287 and 289 are not covered by tests. Consider adding test cases to cover these new code paths to ensure robustness.

To verify the test coverage, you can run the following command:

This will help identify the specific lines that need additional test coverage.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 287-287: middleware/session/session.go#L287
Added line #L287 was not covered by tests


[warning] 289-289: middleware/session/session.go#L289
Added line #L289 was not covered by tests

middleware/session/session_test.go (9)

11-11: LGTM: Added import for uuid package

The addition of the "github.com/google/uuid" import is appropriate for generating unique identifiers in session management.


21-21: Improved session management and flexibility

  1. Changed from New() to NewStore() for store creation, which aligns with the new naming convention.
  2. Added sess.Release() and app.ReleaseCtx(ctx) calls, improving resource management by explicitly releasing sessions and contexts.
  3. Changed key type from []string to []any, allowing for more flexible key types in sessions.

These changes enhance the overall robustness and flexibility of the session management system.

Also applies to: 36-37, 50-50, 64-64, 75-75, 85-87, 100-101


513-513: Enhanced session lifecycle management

  1. Consistently changed from New() to NewStore() for store creation.
  2. Added sess.Release() calls, further improving resource management.
  3. Changed from SetExpiry() to SetIdleTimeout(), indicating a more precise approach to session timeout handling.
  4. Added new verification code to ensure proper session expiration and creation of new sessions.

These changes significantly improve the session lifecycle management, ensuring proper resource cleanup and more accurate timeout handling.

Also applies to: 528-528, 534-534, 554-554, 566-566, 583-583, 589-589, 602-603, 608-615


558-558: Improved test coverage for session timeout mechanisms

  1. Renamed Test_Session_Save_Expiration to Test_Session_Save_IdleTimeout, accurately reflecting the change in timeout mechanism.
  2. Added new test function Test_Session_Save_AbsoluteTimeout, which provides coverage for the newly implemented absolute timeout feature.

These changes enhance the test suite by ensuring both idle timeout and absolute timeout mechanisms are properly tested. The new test thoroughly checks various aspects of the absolute timeout behavior, including:

  • Correct timeout application
  • Session data persistence and retrieval
  • Proper session expiration and recreation

This addition significantly improves the robustness of the session management testing.

Also applies to: 618-698


709-709: Improved session management, flexibility, and verification

  1. Consistently changed from New() to NewStore() for store creation throughout the file.
  2. Added sess.Release() calls in various places, ensuring proper resource management.
  3. Introduced a custom key generator in the store configuration, allowing for more flexibility in session ID creation.
  4. Added cookie verification code to ensure that session cookies are properly set.

These changes enhance the overall robustness of the session management system by improving resource handling, allowing for custom session ID generation, and verifying proper cookie setting. The consistency in using NewStore() and Release() calls throughout the file is commendable.

Also applies to: 718-718, 730-730, 748-748, 757-757, 770-771, 774-775, 782-782, 794-795, 797-799, 806-806, 821-822, 825-825, 838-838, 849-849, 859-859, 865-865, 880-880


902-902: Consistent improvement in resource management

Throughout these changes, there's a clear focus on improving and maintaining consistent resource management:

  1. Added sess.Release() calls consistently across various test functions and benchmarks.
  2. Included app.ReleaseCtx(c) calls where appropriate to release context resources.
  3. Continued the pattern of changing from New() to NewStore() for store creation.

These modifications significantly enhance the overall resource handling in the test suite. By explicitly releasing sessions and contexts, the code reduces the risk of resource leaks and improves overall performance, especially in benchmark scenarios.

The consistency in applying these changes across different parts of the file is commendable and contributes to a more robust and reliable test suite.

Also applies to: 924-924, 935-936, 954-954, 970-971, 984-984, 1003-1003, 1014-1015, 1021-1021, 1034-1035, 1043-1043, 1054-1056, 1064-1064, 1077-1079, 1089-1089, 1102-1102, 1108-1108, 1123-1123, 1131-1131, 1143-1143, 1151-1151, 1165-1165, 1176-1176


1280-1318: Excellent addition of error handling test

The new test function Test_Session_StoreGetDecodeSessionDataError is a valuable addition to the test suite. It covers an important edge case in session management:

  1. It simulates a scenario where invalid session data is stored.
  2. It tests both store.Get() and store.GetByID() methods with this invalid data.
  3. It verifies that appropriate errors are returned and that the error messages are as expected.

This test enhances the robustness of the session management system by ensuring proper handling of corrupted or invalid session data. It's particularly important for maintaining data integrity and security in the session middleware.

The structure of the test is clear and thorough, making it easy to understand the scenario being tested and the expected outcomes.


Line range hint 1-1318: Summary: Significant improvements in session management and testing

The changes in this file represent a substantial enhancement to the session middleware and its testing suite:

  1. Consistent improvement in resource management through the addition of Release() calls for both sessions and contexts.
  2. Introduction of new timeout mechanisms, including the change from expiration to idle timeout and the addition of absolute timeout.
  3. Enhanced flexibility with the use of []any for session keys and the option for custom key generators.
  4. Improved error handling and edge case coverage, particularly with the new test for decoding invalid session data.
  5. Better naming conventions and consistency in function calls (e.g., NewStore() instead of New()).

These modifications significantly contribute to the robustness, efficiency, and maintainability of the session middleware. The expanded test coverage ensures that the new features and edge cases are properly handled, reducing the likelihood of bugs in production.

The changes align well with the stated objectives in the PR description, particularly in re-writing the session middleware with improved management and introducing breaking changes for better consistency and adherence to standards.


1190-1190: Improved session handling and resource management

  1. Changed from store.Get(localCtx) to store.getSession(localCtx), potentially using a new internal method for session retrieval.
  2. Added sess.Release() and defer sess.Release() calls, further improving resource management.

These changes continue to enhance the resource handling in the test suite. The use of getSession instead of Get might indicate a more specific or optimized method for session retrieval in this context.

To ensure the correctness of the getSession method, please run the following verification:

Also applies to: 1214-1216, 1233-1233

✅ Verification successful

Session retrieval method verified

The getSession method exists and is utilized correctly within the middleware/session package. The changes effectively enhance session handling and resource management as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence and usage of the getSession method
rg --type go "func.*getSession" ./middleware/session
rg --type go "store\.getSession" ./middleware/session

Length of output: 1112

middleware/session/store.go Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (8)
middleware/session/store_test.go (2)

120-140: LGTM with suggestion: Use NewStore() for consistency

The new TestStore_Get_SessionAlreadyLoaded function is a valuable addition, enhancing test coverage for session management. It correctly checks for the ErrSessionAlreadyLoadedByMiddleware error when a session is already loaded by middleware.

However, for consistency with other tests and to ensure proper initialization:

-	store := &Store{}
+	store := NewStore()

This change aligns with the initialization pattern used in other tests and ensures any necessary setup in NewStore() is not bypassed.


158-217: LGTM with suggestion: Release the acquired context

The new Test_Store_GetByID function is an excellent addition to the test suite. It comprehensively covers three crucial scenarios:

  1. Attempting to get a session with an empty ID.
  2. Attempting to get a non-existent session.
  3. Creating, retrieving, and manipulating a valid session.

The test thoroughly exercises various session methods, enhancing the overall test coverage.

However, to prevent potential resource leaks, consider releasing the acquired context:

 		ctx := fiber.New().AcquireCtx(&fasthttp.RequestCtx{})
+		defer fiber.New().ReleaseCtx(ctx)
 		session, err := store.Get(ctx)
 		defer session.Release()

This ensures proper cleanup of resources after the test execution.

middleware/session/store.go (2)

Line range hint 121-183: LGTM with a minor suggestion: Improved getSession method with enhanced session management

The additions for handling session freshness, expiration, and absolute timeout significantly improve session management. The enhanced error handling, particularly for session decoding, increases the method's robustness.

However, there's a minor issue in the error handling for session decoding:

 if err != nil {
 	sess.mu.Unlock()
 	sess.Release()
-	return nil, fmt.Errorf("failed to decode session data: %w", err)
+	return nil, fmt.Errorf("failed to decode session data: %w", decodeErr)
 }

This change ensures that the correct error (decodeErr) is being wrapped and returned.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 179-179: middleware/session/store.go#L179
Added line #L179 was not covered by tests


179-179: Suggestion: Improve test coverage for error handling cases

The static analysis tool has identified a few lines that are not covered by tests:

  1. Line 179: Error handling for session reset failure
  2. Line 297: Error handling for storage retrieval failure in GetByID
  3. Lines 323-324: Error handling for session destruction failure in GetByID

Consider adding test cases to cover these specific error scenarios. This will improve code coverage and ensure that the error handling logic works as expected in edge cases.

Would you like assistance in writing these additional test cases?

Also applies to: 297-297, 323-324

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 179-179: middleware/session/store.go#L179
Added line #L179 was not covered by tests

docs/middleware/session.md (4)

5-123: LGTM! Comprehensive introduction and migration guide.

The expanded introduction and detailed migration guide provide excellent context for users, especially those upgrading from v2 to v3. The inclusion of both legacy and recommended approaches is particularly helpful.

Minor formatting improvements needed in the migration guide section.

To enhance readability and adhere to Markdown best practices, consider the following adjustments:

  1. Add blank lines around headings.
  2. Remove trailing colons from headings.

For example:

 ### v3 Example (Recommended Middleware Handler)

+
-##### Key Features:
+##### Key Features
+

-##### Usage Considerations:
+##### Usage Considerations
+

-##### Example Use Cases:
+##### Example Use Cases
+

These changes will improve the document's structure and consistency.


177-229: LGTM! Comprehensive Signatures section.

The Signatures section provides a thorough list of available methods for various components of the session middleware, including new and updated methods.

Consider adding brief descriptions for each method.

To enhance the usefulness of the Signatures section, consider adding brief descriptions for each method. This would help users understand the purpose of each method at a glance. For example:

// Session Methods
func (s *Session) Fresh() bool // Returns true if the session is new
func (s *Session) ID() string // Returns the session ID
func (s *Session) Get(key string) any // Retrieves a value from the session
// ... (add descriptions for other methods)

This addition would make the documentation more informative and user-friendly.


230-439: LGTM! Comprehensive and informative Examples section.

The Examples section provides a wide range of use cases, including the recommended middleware handler approach, custom storage implementation, session usage without middleware handler, and handling of custom types. The inclusion of security notices and middleware order information adds significant value.

Consider improving consistency of code comments across examples.

To enhance readability and maintain consistency, consider adding more inline comments to all example code snippets. This would help users understand the purpose of each code block more easily. For instance, in the "Middleware Handler (Recommended)" example:

// Initialize Fiber app
app := fiber.New()

// Create session middleware and store
sessionMiddleware, sessionStore := session.NewWithStore()

// Use session middleware
app.Use(sessionMiddleware)

// Use CSRF middleware with session store
app.Use(csrf.New(csrf.Config{
    Store: sessionStore,
}))

// Define route handler
app.Get("/", func(c fiber.Ctx) error {
    // Get session from context
    sess := session.FromContext(c)
    if sess == nil {
        return c.SendStatus(fiber.StatusInternalServerError)
    }

    // ... (rest of the handler code)
})

Applying this level of commenting consistently across all examples would improve the overall documentation quality.

🧰 Tools
🪛 LanguageTool

[style] ~238-~238: This phrase is redundant. Consider using “outside”.
Context: ...method when you need to manage sessions outside of the standard HTTP workflow, such as in ...

(OUTSIDE_OF)

🪛 Markdownlint

232-232: Expected: 1; Actual: 0; Above
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


236-236: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


240-240: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


245-245: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


236-236: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


240-240: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


245-245: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


237-237: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


241-241: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


246-246: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


247-247: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)

🪛 GitHub Check: markdownlint

[failure] 232-232: Headings should be surrounded by blank lines
docs/middleware/session.md:232 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Above] [Context: "#### GetByID Method"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 236-236: Headings should be surrounded by blank lines
docs/middleware/session.md:236 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Key Features:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 236-236: Trailing punctuation in heading
docs/middleware/session.md:236:19 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 237-237: Lists should be surrounded by blank lines
docs/middleware/session.md:237 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Context Independence: Se..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md


[failure] 240-240: Headings should be surrounded by blank lines
docs/middleware/session.md:240 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Usage Considerations:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 240-240: Trailing punctuation in heading
docs/middleware/session.md:240:27 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 241-241: Lists should be surrounded by blank lines
docs/middleware/session.md:241 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Manual Persistence: Sinc..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md


[failure] 245-245: Headings should be surrounded by blank lines
docs/middleware/session.md:245 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Example Use Cases:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 245-245: Trailing punctuation in heading
docs/middleware/session.md:245:24 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 246-246: Lists should be surrounded by blank lines
docs/middleware/session.md:246 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Scheduled Jobs: Retrieve..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md


440-477: LGTM! Well-structured Config section.

The Config section provides a comprehensive table of configuration options with descriptions and default values, followed by a code snippet showing the default configuration. This structure makes it easy for users to understand and customize the session middleware.

Consider clarifying some configuration option descriptions.

To enhance user understanding, consider refining the descriptions of some configuration options. For example:

  1. KeyLookup: Clarify that this is a string in the format "source:name" where source can be "header" or "cookie".
  2. CookieSameSite: Provide a brief explanation of what each possible value ("Lax", "Strict", "None") means.
  3. IdleTimeout and AbsoluteTimeout: Clarify the difference between these two timeout mechanisms.

For instance:

| **KeyLookup**         | `string`                       | Key used to store session ID. Format: "source:name" (e.g., "cookie:session_id" or "header:X-Session-ID") | `"cookie:session_id"`     |
| **CookieSameSite**    | `string`                       | SameSite attribute of the session cookie. Options: "Lax" (default, prevents CSRF in most cases), "Strict" (may break some functionalities), "None" (requires HTTPS) | `"Lax"`                   |
| **IdleTimeout**       | `time.Duration`                | Maximum duration of inactivity before session expires. Resets on each request.                           | `30 * time.Minute`        |
| **AbsoluteTimeout**   | `time.Duration`                | Maximum total duration of a session, regardless of activity. Set to 0 for no expiration.                 | `0` (no expiration)       |

These clarifications would help users make more informed decisions when configuring the middleware.

🧰 Tools
🪛 LanguageTool

[style] ~455-~455: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between eac16b6 and e5e5fd8.

📒 Files selected for processing (3)
  • docs/middleware/session.md (1 hunks)
  • middleware/session/store.go (4 hunks)
  • middleware/session/store_test.go (6 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/middleware/session.md

[style] ~238-~238: This phrase is redundant. Consider using “outside”.
Context: ...method when you need to manage sessions outside of the standard HTTP workflow, such as in ...

(OUTSIDE_OF)


[style] ~455-~455: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

🪛 Markdownlint
docs/middleware/session.md

232-232: Expected: 1; Actual: 0; Above
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


236-236: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


240-240: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


245-245: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


236-236: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


240-240: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


245-245: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


237-237: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


241-241: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


246-246: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


247-247: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)

🪛 GitHub Check: markdownlint
docs/middleware/session.md

[failure] 232-232: Headings should be surrounded by blank lines
docs/middleware/session.md:232 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Above] [Context: "#### GetByID Method"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 236-236: Headings should be surrounded by blank lines
docs/middleware/session.md:236 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Key Features:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 236-236: Trailing punctuation in heading
docs/middleware/session.md:236:19 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 237-237: Lists should be surrounded by blank lines
docs/middleware/session.md:237 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Context Independence: Se..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md


[failure] 240-240: Headings should be surrounded by blank lines
docs/middleware/session.md:240 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Usage Considerations:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 240-240: Trailing punctuation in heading
docs/middleware/session.md:240:27 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 241-241: Lists should be surrounded by blank lines
docs/middleware/session.md:241 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Manual Persistence: Sinc..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md


[failure] 245-245: Headings should be surrounded by blank lines
docs/middleware/session.md:245 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Example Use Cases:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 245-245: Trailing punctuation in heading
docs/middleware/session.md:245:24 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 246-246: Lists should be surrounded by blank lines
docs/middleware/session.md:246 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Scheduled Jobs: Retrieve..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md

🪛 GitHub Check: codecov/patch
middleware/session/store.go

[warning] 179-179: middleware/session/store.go#L179
Added line #L179 was not covered by tests


[warning] 297-297: middleware/session/store.go#L297
Added line #L297 was not covered by tests


[warning] 323-324: middleware/session/store.go#L323-L324
Added lines #L323 - L324 were not covered by tests

🔇 Additional comments (11)
middleware/session/store_test.go (5)

23-23: LGTM: Consistent renaming of New() to NewStore()

The changes in the Test_Store_getSessionID function correctly implement the renaming of New() to NewStore(). This modification is consistent across all test cases within the function, maintaining the intended functionality while updating the API.

Also applies to: 36-38, 51-53


76-76: LGTM: Consistent renaming in Test_Store_Get

The change in the Test_Store_Get function correctly implements the renaming of New() to NewStore(). This modification maintains consistency with the updated API.


96-96: LGTM: Consistent renaming in Test_Store_DeleteSession

The change in the Test_Store_DeleteSession function correctly implements the renaming of New() to NewStore(). This modification maintains consistency with the updated API.


142-156: LGTM: Comprehensive test cases for Store.Delete

The new TestStore_Delete function is a valuable addition to the test suite. It covers two important scenarios:

  1. Attempting to delete a session with an empty ID, which correctly returns an ErrEmptySessionID error.
  2. Attempting to delete a non-existing session, which correctly doesn't return an error.

These test cases enhance the robustness of the session deletion functionality and provide good coverage for edge cases.


Line range hint 1-217: Overall assessment: Significant improvement in test coverage

The changes to middleware/session/store_test.go represent a substantial enhancement to the test suite for session management. Key improvements include:

  1. Consistent renaming of New() to NewStore() across all test cases.
  2. Addition of new test functions that cover important scenarios:
    • TestStore_Get_SessionAlreadyLoaded
    • TestStore_Delete
    • Test_Store_GetByID

These additions significantly improve the test coverage for session creation, retrieval, manipulation, and deletion. They also address edge cases and error conditions, enhancing the overall robustness of the session management system.

The suggested minor improvements (using NewStore() consistently and releasing acquired contexts) will further refine the test suite. Overall, these changes contribute to a more comprehensive and reliable testing framework for the session middleware.

middleware/session/store.go (4)

16-20: LGTM: New error variables enhance error handling

The introduction of ErrSessionAlreadyLoadedByMiddleware and ErrSessionIDNotFoundInStore, along with the update to ErrEmptySessionID, improves error handling specificity. The error messages are consistent and follow Go conventions.


35-62: LGTM: Improved NewStore function with enhanced documentation and functionality

The renaming of New to NewStore improves clarity. The added documentation, including parameters, return values, and usage examples, enhances developer understanding. The new absolute timeout handling aligns well with the PR objectives for improved session management.


77-104: LGTM: Enhanced Get method with improved error handling

The addition of a check for sessions already loaded by middleware prevents potential issues with duplicate loading. The updated documentation clearly explains this new behavior, enhancing the method's usability and robustness.


237-255: LGTM: Enhanced Delete method with improved documentation and error handling

The addition of detailed documentation, including parameters, return values, and usage examples, significantly improves the method's usability. The new error handling for empty session IDs enhances the robustness of the method.

docs/middleware/session.md (2)

125-176: LGTM! Well-structured Types section.

The Types section clearly defines the Config, Middleware, Session, and Store structs, providing users with a comprehensive overview of the key components in the session middleware. The inclusion of code snippets for each type enhances understanding.


Line range hint 1-477: Excellent documentation update for the session middleware.

This comprehensive update to the session middleware documentation significantly enhances its usefulness for Fiber users. Key strengths include:

  1. Detailed migration guide from v2 to v3.
  2. Clear explanations of new concepts like IdleTimeout and AbsoluteTimeout.
  3. Comprehensive examples covering various use cases.
  4. Well-structured Config section with detailed explanations.
  5. Inclusion of important security notices and best practices.

The minor formatting and consistency issues identified earlier do not detract from the overall quality of the documentation. Once addressed, this will be an exemplary resource for developers using the Fiber framework.

🧰 Tools
🪛 LanguageTool

[style] ~238-~238: This phrase is redundant. Consider using “outside”.
Context: ...method when you need to manage sessions outside of the standard HTTP workflow, such as in ...

(OUTSIDE_OF)


[style] ~455-~455: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

🪛 Markdownlint

232-232: Expected: 1; Actual: 0; Above
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


236-236: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


240-240: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


245-245: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


236-236: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


240-240: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


245-245: Punctuation: ':'
Trailing punctuation in heading

(MD026, no-trailing-punctuation)


237-237: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


241-241: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


246-246: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


247-247: null
Lists should be surrounded by blank lines

(MD032, blanks-around-lists)

🪛 GitHub Check: markdownlint

[failure] 232-232: Headings should be surrounded by blank lines
docs/middleware/session.md:232 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Above] [Context: "#### GetByID Method"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 236-236: Headings should be surrounded by blank lines
docs/middleware/session.md:236 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Key Features:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 236-236: Trailing punctuation in heading
docs/middleware/session.md:236:19 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 237-237: Lists should be surrounded by blank lines
docs/middleware/session.md:237 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Context Independence: Se..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md


[failure] 240-240: Headings should be surrounded by blank lines
docs/middleware/session.md:240 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Usage Considerations:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 240-240: Trailing punctuation in heading
docs/middleware/session.md:240:27 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 241-241: Lists should be surrounded by blank lines
docs/middleware/session.md:241 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Manual Persistence: Sinc..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md


[failure] 245-245: Headings should be surrounded by blank lines
docs/middleware/session.md:245 MD022/blanks-around-headings Headings should be surrounded by blank lines [Expected: 1; Actual: 0; Below] [Context: "##### Example Use Cases:"] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md022.md


[failure] 245-245: Trailing punctuation in heading
docs/middleware/session.md:245:24 MD026/no-trailing-punctuation Trailing punctuation in heading [Punctuation: ':'] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md026.md


[failure] 246-246: Lists should be surrounded by blank lines
docs/middleware/session.md:246 MD032/blanks-around-lists Lists should be surrounded by blank lines [Context: "- Scheduled Jobs: Retrieve..."] https://github.com/DavidAnson/markdownlint/blob/v0.35.0/doc/md032.md

middleware/session/store.go Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (7)
docs/middleware/session.md (7)

58-60: Consider clarifying IdleTimeout behavior in the legacy approach

The note about IdleTimeout behavior in the legacy approach is helpful. To further improve clarity, consider expanding this note to explain how the IdleTimeout behaves when using the recommended middleware handler approach. This will help users understand the differences between the two approaches more clearly.

 :::note
 When using the legacy approach, the IdleTimeout will be updated when the session is saved.
+When using the recommended middleware handler approach, the IdleTimeout is automatically updated on each request.
 :::

132-147: Consider adding brief descriptions for Config struct fields

To enhance the documentation, consider adding brief descriptions for each field in the Config struct. This will help users understand the purpose and impact of each configuration option more easily.

For example:

type Config struct {
    // Storage defines where session data is stored
    Storage           fiber.Storage

    // Next defines a function to skip this middleware when returned true
    Next              func(fiber.Ctx) bool

    // Add descriptions for other fields...
}

180-228: Enhance consistency in method descriptions

To improve the documentation, consider adding brief descriptions for each method in the Signatures section, similar to the detailed explanation provided for the GetByID method. This will help users understand the purpose and usage of each method more easily.

For example:

// New creates a new session middleware
func New(config ...Config) *Middleware

// NewWithStore creates a new session middleware and returns both the middleware and the store
func NewWithStore(config ...Config) (fiber.Handler, *Store)

// Add descriptions for other methods...

418-444: Enhance custom types example

The example for registering custom types is helpful, but it could be improved by showing how to actually use the custom type in a session. Consider adding a route that demonstrates setting and getting a custom type in the session.

Here's an example of how you could enhance the custom types example:

app.Get("/set-user", func(c fiber.Ctx) error {
    sess := session.FromContext(c)
    if sess == nil {
        return c.SendStatus(fiber.StatusInternalServerError)
    }

    user := User{Name: "John Doe", Age: 30}
    sess.Set("user", user)

    return c.SendString("User set in session")
})

app.Get("/get-user", func(c fiber.Ctx) error {
    sess := session.FromContext(c)
    if sess == nil {
        return c.SendStatus(fiber.StatusInternalServerError)
    }

    user, ok := sess.Get("user").(User)
    if !ok {
        return c.SendString("User not found in session")
    }

    return c.JSON(user)
})

445-482: Align Config table with Default Config code

To improve consistency and clarity, consider aligning the order of fields in the Config table with the order in the Default Config code. This will make it easier for users to compare the default values with the available options.

Additionally, ensure that all fields in the Default Config are also present in the Config table. For example, the Store field is present in the Default Config but not in the Config table.

🧰 Tools
🪛 LanguageTool

[style] ~460-~460: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)


240-240: Consider rephrasing for conciseness

The phrase "outside of" is redundant. Consider using just "outside" for improved conciseness.

-method when you need to manage sessions outside of the standard HTTP workflow, such as in
+method when you need to manage sessions outside the standard HTTP workflow, such as in
🧰 Tools
🪛 LanguageTool

[style] ~240-~240: This phrase is redundant. Consider using “outside”.
Context: ...method when you need to manage sessions outside of the standard HTTP workflow, such as in ...

(OUTSIDE_OF)


460-460: Consider using "inaccessible" for clarity

To improve readability and avoid wordiness, consider using "inaccessible" instead of "not accessible".

-| Ensures session cookie is not accessible to JavaScript (HTTP only).
+| Ensures session cookie is inaccessible to JavaScript (HTTP only).
🧰 Tools
🪛 LanguageTool

[style] ~460-~460: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e5e5fd8 and 00b9e07.

📒 Files selected for processing (1)
  • docs/middleware/session.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/middleware/session.md

[style] ~240-~240: This phrase is redundant. Consider using “outside”.
Context: ...method when you need to manage sessions outside of the standard HTTP workflow, such as in ...

(OUTSIDE_OF)


[style] ~460-~460: Consider using “inaccessible” to avoid wordiness.
Context: ... | Ensures session cookie is not accessible to JavaScript (HTTP only). ...

(NOT_ABLE_PREMIUM)

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

🧹 Outside diff range and nitpick comments (3)
middleware/session/config.go (3)

12-95: Approve changes to Config struct with a minor suggestion

The changes to the Config struct are well-documented and provide improved flexibility for session management. The addition of Next, ErrorHandler, IdleTimeout, and AbsoluteTimeout fields enhances the middleware's capabilities.

Consider adding a brief example in the documentation for the Next field to illustrate its usage, similar to how you've documented the DefaultErrorHandler. This would help developers understand how to implement conditional middleware skipping.


Line range hint 133-187: Approve changes to configDefault with a suggestion

The updates to configDefault improve configuration validation and error handling. The addition of checks for IdleTimeout and AbsoluteTimeout ensures more robust session management.

Consider wrapping the panic calls with a custom function to allow for easier testing and potential future enhancements in error handling. For example:

func configError(message string) {
    panic("[session] " + message)
}

// Usage
if len(selectors) != numSelectors {
    configError("KeyLookup must be in the format '<source>:<name>'")
}

This approach maintains the current behavior while providing flexibility for future modifications.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 129-129: middleware/session/config.go#L129
Added line #L129 was not covered by tests


[warning] 160-160: middleware/session/config.go#L160
Added line #L160 was not covered by tests


129-129: Improve test coverage for error handling paths

The static analysis tool indicates that lines 129 and 160 are not covered by tests. These lines are part of error handling paths in the DefaultErrorHandler and configDefault functions respectively.

Consider adding test cases to cover these error scenarios:

  1. Test the DefaultErrorHandler when SendStatus fails.
  2. Test configDefault with an AbsoluteTimeout less than IdleTimeout.

Improving test coverage for these edge cases will enhance the overall robustness of the session middleware.

Also applies to: 160-160

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 129-129: middleware/session/config.go#L129
Added line #L129 was not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 00b9e07 and 23e823b.

📒 Files selected for processing (1)
  • middleware/session/config.go (4 hunks)
🧰 Additional context used
📓 Learnings (1)
middleware/session/config.go (1)
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/config.go:16-26
Timestamp: 2024-09-25T16:17:00.969Z
Learning: In the session middleware `Config` struct, `Store` is backed by `fiber.Storage`; they are different entities serving distinct purposes in session management.
🪛 GitHub Check: codecov/patch
middleware/session/config.go

[warning] 129-129: middleware/session/config.go#L129
Added line #L129 was not covered by tests


[warning] 160-160: middleware/session/config.go#L160
Added line #L160 was not covered by tests

🔇 Additional comments (1)
middleware/session/config.go (1)

108-115: Approve changes to ConfigDefault

The updates to ConfigDefault correctly reflect the changes made to the Config struct. The replacement of Expiration with IdleTimeout and its default value of 30 minutes is appropriate for general use cases.

middleware/session/config.go Outdated Show resolved Hide resolved
@sixcolors sixcolors requested a review from gaby October 2, 2024 23:47
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

🧹 Outside diff range and nitpick comments (2)
middleware/session/config.go (2)

117-131: LGTM with suggestion: DefaultErrorHandler implementation

The DefaultErrorHandler function provides a good basic error handling mechanism. However, consider enhancing the error logging to include more context, such as the request ID or path.

Example improvement:

func DefaultErrorHandler(c fiber.Ctx, err error) {
    log.Errorf("session error on %s: %v", c.Path(), err)
    if sendErr := c.SendStatus(fiber.StatusInternalServerError); sendErr != nil {
        log.Errorf("session: failed to send error status: %v", sendErr)
    }
}

This change would provide more detailed logging, making it easier to trace and debug issues.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 129-129: middleware/session/config.go#L129
Added line #L129 was not covered by tests


129-129: Consider improving test coverage

Static analysis indicates that lines 129 and 160 are not covered by tests. These lines are part of error handling paths:

  1. Line 129: Error logging in DefaultErrorHandler
  2. Line 160: Panic in configDefault for invalid AbsoluteTimeout

While these scenarios might be challenging to test, consider adding unit tests to cover these edge cases. This would improve the overall robustness of the package.

Also applies to: 160-160

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 129-129: middleware/session/config.go#L129
Added line #L129 was not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 23e823b and ba38786.

📒 Files selected for processing (1)
  • middleware/session/config.go (4 hunks)
🧰 Additional context used
📓 Learnings (1)
middleware/session/config.go (1)
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/config.go:16-26
Timestamp: 2024-09-25T16:17:00.969Z
Learning: In the session middleware `Config` struct, `Store` is backed by `fiber.Storage`; they are different entities serving distinct purposes in session management.
🪛 GitHub Check: codecov/patch
middleware/session/config.go

[warning] 129-129: middleware/session/config.go#L129
Added line #L129 was not covered by tests


[warning] 160-160: middleware/session/config.go#L160
Added line #L160 was not covered by tests

🔇 Additional comments (8)
middleware/session/config.go (8)

8-8: LGTM: Import statement addition

The addition of the log package from github.com/gofiber/fiber/v3/log is appropriate for the new error handling functionality introduced in this file.


19-21: LGTM: Addition of Next function

The Next function allows for conditional skipping of the middleware, providing more flexibility in request handling.


28-31: LGTM: Addition of ErrorHandler

The ErrorHandler function allows for custom error handling, improving the middleware's flexibility and error management capabilities.


66-71: LGTM: Replacement of Expiration with IdleTimeout

The IdleTimeout field replaces the previous Expiration field, providing a clearer semantic meaning for session inactivity expiration. The default value and documentation are appropriate.


73-78: LGTM: Addition of AbsoluteTimeout

The AbsoluteTimeout field adds the ability to set a maximum duration for a session, independent of activity. This enhances session management capabilities.


155-157: LGTM: IdleTimeout handling

The check for IdleTimeout ensures that a valid duration is always set, defaulting to the ConfigDefault value if necessary.


158-161: LGTM: AbsoluteTimeout validation

The check ensuring that AbsoluteTimeout is greater than or equal to IdleTimeout is crucial for maintaining logical session timeout behavior.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 160-160: middleware/session/config.go#L160
Added line #L160 was not covered by tests


Line range hint 169-184: LGTM: Improved KeyLookup parsing

The parsing of KeyLookup has been enhanced with better error messages and handling of different sources. This improves the robustness of the configuration process.

@gaby gaby added this to the v3 milestone Oct 8, 2024
Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall looks fine, few concerns with the "any" key for maps and the timeout/idle of CSRF.

docs/middleware/csrf.md Show resolved Hide resolved
docs/whats_new.md Show resolved Hide resolved
middleware/session/data.go Show resolved Hide resolved
middleware/session/data.go Show resolved Hide resolved
middleware/session/store_test.go Show resolved Hide resolved
middleware/session/store_test.go Outdated Show resolved Hide resolved
middleware/session/store_test.go Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
middleware/session/store_test.go (1)

164-225: Consider optimizing test setup.

The test cases are comprehensive and well-structured. However, consider moving the fiber.New() initialization outside the subtest to improve test efficiency:

func Test_Store_GetByID(t *testing.T) {
	t.Parallel()
	// Create a new store
	store := NewStore()
+	app := fiber.New()

	t.Run("valid session ID", func(t *testing.T) {
		t.Parallel()
-		app := fiber.New()
		// Create a new session
		ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
		// ... rest of the test
	})
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ba38786 and b54c954.

📒 Files selected for processing (1)
  • middleware/session/store_test.go (6 hunks)
🧰 Additional context used
🔇 Additional comments (3)
middleware/session/store_test.go (3)

Line range hint 23-104: LGTM! Consistent initialization and proper resource cleanup.

The changes correctly:

  • Use the new NewStore() initialization consistently
  • Add proper context cleanup with defer app.ReleaseCtx(ctx) addressing previous resource leak concerns

125-146: LGTM! Well-structured test for middleware conflict.

The test properly verifies the behavior when a session is already loaded by middleware.


148-162: LGTM! Comprehensive test coverage for delete operations.

The test cases properly verify:

  • Error handling for empty session IDs
  • Graceful handling of non-existing sessions

@ReneWerner87 ReneWerner87 merged commit e3232c1 into gofiber:main Oct 25, 2024
17 of 18 checks passed
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.

🐛 [Bug]: Inconsistency in Session and CSRF Middleware Handling of Timeout and Expiration
5 participants