Skip to content

🐛 bug: guard nil request in adaptor LocalContextFromHTTPRequest#4097

Merged
ReneWerner87 merged 2 commits intomainfrom
update-localcontextfromhttprequest-guard-for-nil-r
Feb 22, 2026
Merged

🐛 bug: guard nil request in adaptor LocalContextFromHTTPRequest#4097
ReneWerner87 merged 2 commits intomainfrom
update-localcontextfromhttprequest-guard-for-nil-r

Conversation

@gaby
Copy link
Member

@gaby gaby commented Feb 21, 2026

Motivation

  • Prevent a panic when LocalContextFromHTTPRequest is called with a nil *http.Request by returning (nil, false) early.
  • Preserve the existing type-assertion behavior for non-nil requests so adapted handlers continue to receive the stored Fiber context when present.

Description

  • Add an early nil-check in LocalContextFromHTTPRequest that returns nil, false if r == nil.
  • Add unit tests in middleware/adaptor (Test_LocalContextFromHTTPRequest) that verify nil request handling, requests without the stored context key, and requests with the stored context value under localContextKey.
  • Updated middleware/adaptor/adaptor.go and middleware/adaptor/adaptor_test.go to include the change and tests.

Copilot AI review requested due to automatic review settings February 21, 2026 18:09
@gaby gaby requested a review from a team as a code owner February 21, 2026 18:09
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a potential panic in the LocalContextFromHTTPRequest function by introducing a robust nil check for the incoming *http.Request. The change ensures that the function gracefully handles nil requests, returning (nil, false) instead of panicking, thereby improving the stability and reliability of the adaptor middleware. New unit tests have been added to validate this new behavior and existing context extraction logic.

Highlights

  • Panic Prevention: Implemented a nil check in LocalContextFromHTTPRequest to prevent panics when a nil *http.Request is passed, ensuring graceful handling.
  • Context Extraction Robustness: Enhanced the LocalContextFromHTTPRequest function to return (nil, false) early for nil requests, while preserving existing type-assertion behavior for valid requests.
  • Unit Testing: Added comprehensive unit tests for LocalContextFromHTTPRequest to verify correct behavior with nil requests, requests without the stored context key, and requests with the context key.
Changelog
  • middleware/adaptor/adaptor.go
    • Added an early nil-check for the *http.Request parameter in LocalContextFromHTTPRequest.
  • middleware/adaptor/adaptor_test.go
    • Introduced Test_LocalContextFromHTTPRequest with sub-tests to verify nil request handling, requests without the stored context key, and requests with the stored context value.
Activity
  • Ran go test ./middleware/adaptor which completed successfully and the adaptor package tests passed.
  • Ran full test suite via make test which completed successfully (all tests passed; 1 skipped).
  • Ran make generate, make betteralign, make modernize, make format, and make lint all succeeded.
  • Noted that make audit failed due to govulncheck findings in the Go standard library toolchain (go1.25.1), unrelated to these changes.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@ReneWerner87 ReneWerner87 added this to v3 Feb 21, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Feb 21, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 21, 2026

Walkthrough

Added defensive nil checks to two helper functions in the adaptor to avoid panics on nil inputs; expanded unit tests to cover nil request, missing context keys, and various context-copying scenarios.

Changes

Cohort / File(s) Summary
Adaptor runtime changes
middleware/adaptor/adaptor.go
Added nil checks in public helpers (LocalContextFromHTTPRequest, CopyContextToFiberContext) to return early on nil inputs and avoid dereferencing nil pointers.
Tests expanded / new cases
middleware/adaptor/adaptor_test.go
Added unit tests covering nil http.Request, missing stored context key, stored local context retrieval, nil request-context handling, nested/wrapped contexts, and key-value copying into Fiber context.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 I hopped through code both calm and quick,
Found a nil that made my whiskers prick.
I placed a guard, then wrote a test or two,
Now contexts hop safe — through me and you. 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main bug fix—adding a nil guard for LocalContextFromHTTPRequest—matching the primary change in the changeset.
Description check ✅ Passed The description provides clear motivation and outlines the changes made, but is missing several template sections like Changes introduced checklist items, Type of change, and Checklist verification items.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch update-localcontextfromhttprequest-guard-for-nil-r

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Prevents a panic in the adaptor layer by making LocalContextFromHTTPRequest safe to call with a nil *http.Request, while preserving existing behavior for non-nil requests so adapted handlers can still retrieve the stored Fiber context when present.

Changes:

  • Add an early nil guard in LocalContextFromHTTPRequest returning (nil, false) when r == nil.
  • Add unit tests covering nil requests, missing context key, and present context key cases.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
middleware/adaptor/adaptor.go Adds a nil check to avoid panics when extracting local context from a nil request.
middleware/adaptor/adaptor_test.go Adds focused tests validating LocalContextFromHTTPRequest behavior across key scenarios.

@codecov
Copy link

codecov bot commented Feb 21, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.03%. Comparing base (8b4b146) to head (2caae2a).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4097   +/-   ##
=======================================
  Coverage   91.03%   91.03%           
=======================================
  Files         119      119           
  Lines       11320    11324    +4     
=======================================
+ Hits        10305    10309    +4     
  Misses        643      643           
  Partials      372      372           
Flag Coverage Δ
unittests 91.03% <100.00%> (+<0.01%) ⬆️

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

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request correctly implements a nil check in LocalContextFromHTTPRequest to prevent panics when a nil request is passed. The added unit tests are well-structured and cover the relevant edge cases, including nil requests and missing context keys. The changes improve the stability of the adaptor middleware without introducing any regressions.

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.

🧹 Nitpick comments (1)
middleware/adaptor/adaptor_test.go (1)

879-902: Optional: replace vacuous assert.NotNil(t, &fctx) with a meaningful assertion.

assert.NotNil(t, &fctx) takes the address of a local variable — this is always non-nil and provides zero test coverage value. Now that both subtests are parallel, consider either removing the assertion entirely (the panic-safety is proven by the test not panicking) or replacing it with an assertion on observable side-effects (e.g., that no user values were written).

🧹 Suggested clean-up (both affected subtests)
 t.Run("invalid src", func(t *testing.T) {
     t.Parallel()
     var fctx fasthttp.RequestCtx
     CopyContextToFiberContext(nil, &fctx)
-    // Add assertion to ensure no panic and coverage is detected
-    assert.NotNil(t, &fctx)
 })
 t.Run("nil pointer", func(t *testing.T) {
     t.Parallel()
     var nilPtr *context.Context
     var fctx fasthttp.RequestCtx
     CopyContextToFiberContext(nilPtr, &fctx)
-    // Add assertion to ensure no panic and coverage is detected
-    assert.NotNil(t, &fctx)
 })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@middleware/adaptor/adaptor_test.go` around lines 879 - 902, Replace the
vacuous assert.NotNil(t, &fctx) checks in the "invalid src" and "nil pointer"
subtests with assertions that verify observable side-effects of
CopyContextToFiberContext: call fctx.UserValue("nil-request-context") (or the
expected key used in the ctx) and assert it is nil (or not set), and keep the
require.NotPanics where present; this uses the function
CopyContextToFiberContext as the target and ensures the test actually verifies
that no user values were written instead of asserting the address of a local
variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@middleware/adaptor/adaptor_test.go`:
- Around line 879-902: Replace the vacuous assert.NotNil(t, &fctx) checks in the
"invalid src" and "nil pointer" subtests with assertions that verify observable
side-effects of CopyContextToFiberContext: call
fctx.UserValue("nil-request-context") (or the expected key used in the ctx) and
assert it is nil (or not set), and keep the require.NotPanics where present;
this uses the function CopyContextToFiberContext as the target and ensures the
test actually verifies that no user values were written instead of asserting the
address of a local variable.

@ReneWerner87 ReneWerner87 merged commit af52730 into main Feb 22, 2026
19 of 20 checks passed
@ReneWerner87 ReneWerner87 deleted the update-localcontextfromhttprequest-guard-for-nil-r branch February 22, 2026 08:03
@github-project-automation github-project-automation bot moved this to Done in v3 Feb 22, 2026
@ReneWerner87 ReneWerner87 modified the milestones: v3, v3.1.0 Feb 27, 2026
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.

3 participants