Skip to content

🐛 bug: harden session middleware lifecycle and error handling#4107

Merged
gaby merged 2 commits intoupdate-session-middleware-to-fail-gracefullyfrom
copilot/sub-pr-4059
Feb 24, 2026
Merged

🐛 bug: harden session middleware lifecycle and error handling#4107
gaby merged 2 commits intoupdate-session-middleware-to-fail-gracefullyfrom
copilot/sub-pr-4059

Conversation

Copy link
Contributor

Copilot AI commented Feb 24, 2026

Description

Hardens the session middleware against three classes of defects: leaked pool objects via incomplete context cleanup, unsanitized session IDs used directly as storage keys, and panics in the request handler path from pool type assertions.

Changes introduced

fiber.StoreInContext for cleanup — Middleware cleanup now uses fiber.StoreInContext(c, key, nil) instead of c.Locals(key, nil), so released *Middleware pointers are cleared from both Locals and context.Context when PassLocalsToContext is enabled. Previously, stale pointers remained accessible via c.Context() after the object was returned to the pool.

Session ID validation — Extracted session IDs are now validated before reaching Storage.GetWithContext(). isValidSessionID() rejects empty, oversized (>4096 bytes), and non-visible-ASCII (outside 0x21–0x7E) values. Invalid IDs are silently discarded and a fresh session is generated.

// store.go — IDs from extractors are validated before use as storage keys
func (s *Store) getSessionID(c fiber.Ctx) string {
    sessionID, err := s.Extractor.Extract(c)
    if err != nil {
        return ""
    }
    if !isValidSessionID(sessionID) {
        return ""
    }
    return sessionID
}

Panic removalacquireMiddleware(), acquireSession(), and acquireData() now use safe type assertions with fallback allocation instead of panic(). Pool corruption no longer crashes the server.

Init-error handlinginitialize() returns error; NewWithStore routes init failures through the configured ErrorHandler/DefaultErrorHandler, releases the middleware, and only returns the raw error when no response was written.

finalizeSession() — Conditionally calls saveSession() (skips when destroyed) and always calls releaseSession() exactly once.

Store error pathsgetSession releases the session before returning on Reset() failure; GetByID releases before returning ErrSessionIDNotFoundInStore after expired-session destroy. Fixed the nolint contextcheck comment to reflect that sess.gctx is now correctly set.

  • Benchmarks: No regressions; hot paths unchanged.
  • Documentation Update: N/A — internal behavioral hardening only.
  • Changelog/What's New: Session middleware no longer panics on pool type-assertion failures; extracted session IDs are validated for length and character set before storage lookup.
  • Migration Guide: N/A — no public API changes.
  • API Alignment with Express: N/A
  • API Longevity: Exported ErrTypeAssertionFailed retained for backward compatibility despite panic removal.
  • Examples: N/A

Type of change

  • Enhancement (improvement to existing features and functionality)
  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.

Commit formatting

🐛 Used throughout.


🔒 GitHub Advanced Security automatically protects Copilot coding agent pull requests. You can protect all pull requests by enabling Advanced Security for your repositories. Learn more about Advanced Security.

…anics

Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Feb 24, 2026

Just as a heads up, I was blocked by some firewall rules while working on your feedback. Expand below for details.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • exampleretry.com
    • Triggering command: /tmp/go-build2412590885/b307/client.test /tmp/go-build2412590885/b307/client.test -test.paniconexit0 -test.v=test2json -test.timeout=10m0s -test.count=1 -test.shuffle=on mpile ux-amd64/pkg/tool/linux_amd64/compile -d github.com/gofib-unsafeptr=false m ux-amd64/pkg/too/tmp/go-build2412590885/b093/vet.cfg -V=f�� g_.a m rg/toolchain@v0./tmp/go-build2412590885/b256/symabis -c=4 -nolocalimports -importcfg rg/toolchain@v0./tmp/go-build2412590885/b250/vet.cfg (dns block)
  • vuln.go.dev
    • Triggering command: /tmp/go-build2725541116/b001/exe/govulncheck /tmp/go-build2725541116/b001/exe/govulncheck ./... ead l/linux_amd64/vet env s WF 0.1-go1.25.0.lin-lang=go1.25 GOINSECURE fips140/hmac l/linux_amd64/cg--exclude-standard 0.1-go1.25.0.lin--others 2590�� pkg/mod/golang.o-dwarf=false pkg/mod/golang.o-goversion 0.1-go1.25.0.lingo1.25.0 2590885/b161/ GOWORK (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Copilot AI changed the title [WIP] Fix session middleware lifecycle and error handling 🐛 bug: harden session middleware lifecycle and error handling Feb 24, 2026
Copilot AI requested a review from gaby February 24, 2026 05:42
@codecov
Copy link

codecov bot commented Feb 24, 2026

Codecov Report

❌ Patch coverage is 66.66667% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.13%. Comparing base (a5953ea) to head (a7fdf2c).
⚠️ Report is 3 commits behind head on update-session-middleware-to-fail-gracefully.

Files with missing lines Patch % Lines
middleware/session/data.go 40.00% 2 Missing and 1 partial ⚠️
middleware/session/session.go 33.33% 1 Missing and 1 partial ⚠️
middleware/session/middleware.go 50.00% 1 Missing ⚠️
middleware/session/store.go 90.90% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@                               Coverage Diff                                @@
##           update-session-middleware-to-fail-gracefully    #4107      +/-   ##
================================================================================
- Coverage                                         91.15%   91.13%   -0.03%     
================================================================================
  Files                                               119      119              
  Lines                                             11354    11367      +13     
================================================================================
+ Hits                                              10350    10359       +9     
- Misses                                              636      638       +2     
- Partials                                            368      370       +2     
Flag Coverage Δ
unittests 91.13% <66.66%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: a7fdf2c Previous: 92ada8a Ratio
BenchmarkDecoderedirectionMsgs - MB/s 114.95 MB/s 47.86 MB/s 2.40

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

@gaby gaby marked this pull request as ready for review February 24, 2026 10:20
Copilot AI review requested due to automatic review settings February 24, 2026 10:20
@gaby gaby requested a review from a team as a code owner February 24, 2026 10:20
@gaby gaby requested review from ReneWerner87, efectn and sixcolors and removed request for a team February 24, 2026 10:20
@gaby gaby merged commit 93fdf46 into update-session-middleware-to-fail-gracefully Feb 24, 2026
16 of 23 checks passed
@gaby gaby deleted the copilot/sub-pr-4059 branch February 24, 2026 10:20
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This pull request hardens the session middleware against three classes of potential defects: leaked pool objects, unsanitized session IDs, and panics from pool type assertion failures. The changes improve the robustness and reliability of the session middleware without introducing breaking changes to the public API.

Changes:

  • Replaced c.Locals(key, nil) with fiber.StoreInContext(c, key, nil) to properly clear middleware pointers from both Locals and context.Context when PassLocalsToContext is enabled
  • Added session ID validation (isValidSessionID) that rejects empty, oversized (>4096 bytes), or non-visible-ASCII session IDs before they're used as storage keys
  • Converted panic-based error handling to safe type assertions with fallback allocation in acquireMiddleware(), acquireSession(), and acquireData()

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
middleware/session/store.go Added session ID validation function and integrated it into getSessionID; improved nolint comment clarity
middleware/session/session.go Replaced panic with safe type assertion and fallback allocation in acquireSession
middleware/session/middleware.go Changed cleanup to use fiber.StoreInContext for proper context clearing; removed panic from acquireMiddleware
middleware/session/data.go Replaced panic with safe type assertion and fallback allocation in acquireData
middleware/session/store_test.go Added comprehensive tests for session ID validation including boundary cases
middleware/session/middleware_test.go Added test to verify proper cleanup when PassLocalsToContext is enabled

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants