Skip to content

Comments

🐛 bug: fix Unix-socket support in IsProxyTrusted#4088

Merged
ReneWerner87 merged 11 commits intomainfrom
update-proxy-trust-logic-in-req.go
Feb 17, 2026
Merged

🐛 bug: fix Unix-socket support in IsProxyTrusted#4088
ReneWerner87 merged 11 commits intomainfrom
update-proxy-trust-logic-in-req.go

Conversation

@gaby
Copy link
Member

@gaby gaby commented Feb 16, 2026

This pull request addresses a potential runtime panic in the IsProxyTrusted function by adding a nil check for remote IPs and refines proxy trust logic to correctly handle Unix socket connections. It ensures that Unix socket remotes are explicitly controlled by loopback trust settings, preventing unexpected behavior and enhancing the robustness of proxy trust evaluations without impacting existing TCP/UDP remote handling

Fixes #4086

Copilot AI review requested due to automatic review settings February 16, 2026 14:05
@gaby gaby requested a review from a team as a code owner February 16, 2026 14:05
@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 runtime panic in the IsProxyTrusted function by adding a nil check for remote IPs and refines proxy trust logic to correctly handle Unix socket connections. It ensures that Unix socket remotes are explicitly controlled by loopback trust settings, preventing unexpected behavior and enhancing the robustness of proxy trust evaluations without impacting existing TCP/UDP remote handling.

Highlights

  • Prevented panics in IsProxyTrusted: Added a defensive nil check for RemoteIP() to prevent panics when it yields nil, ensuring IsProxyTrusted() returns false instead.
  • Enhanced Unix socket proxy trust handling: Implemented specific logic within IsProxyTrusted() to handle *net.UnixAddr by returning TrustProxyConfig.Loopback, while preserving existing TCP/UDP trust semantics.
  • Added Unix socket proxy trust tests: Introduced Test_Ctx_ProxyTrust_UnixRemoteAddr and a helper function to validate IsProxyTrusted() and IP() behavior with real Unix sockets, skipping the test on Windows.
Changelog
  • ctx_test.go
    • Added Test_Ctx_ProxyTrust_UnixRemoteAddr to verify proxy trust behavior with Unix sockets.
    • Included runCtxProxyTrustUnixRemoteAddrCase helper function to set up and execute Unix socket test scenarios.
  • req.go
    • Modified IsProxyTrusted to cache RemoteAddr() and use a type switch to specifically handle *net.UnixAddr based on TrustProxyConfig.Loopback.
    • Introduced a nil check for r.c.fasthttp.RemoteIP() to prevent panics, returning false if the IP is nil.
Activity
  • Successfully ran targeted tests Test_Ctx_IsProxyTrusted and Test_Ctx_ProxyTrust_UnixRemoteAddr.
  • Executed make generate, make betteralign, make modernize, make format, and make lint without any reported issues.
  • Encountered a transient timeout during make test on the first attempt, but it passed on a subsequent run.
  • make audit failed due to govulncheck reporting vulnerabilities in the Go standard library for the go1.25.1 toolchain, which is unrelated to the changes in this PR.
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 16, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Feb 16, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 16, 2026

No actionable comments were generated in the recent review. 🎉


Walkthrough

Adds Unix-domain socket trust support: new TrustProxyConfig.UnixSocket field, IsProxyTrusted/IsFromLocal nil-safety and *net.UnixAddr handling, and unit tests exercising X-Forwarded-For over Unix sockets. Minor test resource-release tweaks added.

Changes

Cohort / File(s) Summary
Proxy trust logic
req.go
Add nil guards around RemoteIP(); IsProxyTrusted() type-switches on RemoteAddr() to handle *net.UnixAddr via TrustProxyConfig.UnixSocket; preserve TCP/UDP IP-based checks; tighten IsFromLocal() nil-safety.
Config surface
app.go
Add public field UnixSocket bool json:"unix_socket"toTrustProxyConfig`.
Tests
ctx_test.go
Add Test_Ctx_ProxyTrust_UnixRemoteAddr with subtests and helper runCtxProxyTrustUnixRemoteAddrCase to validate proxy trust and IP extraction when requests arrive via a Unix domain socket; add defer app.ReleaseCtx(c) in several tests.
Documentation
docs/api/ctx.md, docs/whats_new.md
Document TrustProxyConfig.UnixSocket and example settings (Loopback: true, UnixSocket: true).

Sequence Diagram

sequenceDiagram
    participant TestRunner as Test Runner
    participant Client as Unix Socket Client
    participant App as Fiber App
    participant Handler as /ip Handler

    TestRunner->>App: create app (TrustProxy=true, TrustProxyConfig{UnixSocket/Loopback})
    TestRunner->>Client: connect to unix socket and send HTTP request with X-Forwarded-For
    Client->>App: deliver request (RemoteAddr = net.UnixAddr)
    App->>Handler: invoke /ip handler
    Handler->>Handler: call IsProxyTrusted() (type-switch on RemoteAddr)
    alt UnixAddr path
        Handler->>Handler: consult TrustProxyConfig.UnixSocket and extract IP from header
    else non-Unix path
        Handler->>Handler: run TCP/UDP IP checks (loopback/private/CIDR)
    end
    Handler-->>TestRunner: return "IsProxyTrusted|IP" response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • #3170: Prior TrustProxy enhancements that this PR extends with Unix-socket-specific handling and tests.
  • #3974: Modifies IsProxyTrusted trust evaluation logic — overlaps with proxy-trust behavior changes.
  • #4051: Adjusts handling for net.Addr variants (including *net.UnixAddr) — directly related.

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 I nudged a socket in the ground, so deep and round,
A header hopped along—X-Forwarded-Found.
Loopback blinked, the handler sighed,
Unix trusted the proxied tide,
The rabbit's packets leap and bound 🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a concise summary and references issue #4086, but the PR description template checklist items are largely unchecked and missing detailed coverage of changes. Complete the description template checklist to document benchmarks, documentation updates, changelog entries, and confirm unit tests were added and passed.
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies this as a bug fix for Unix-socket support in IsProxyTrusted, which matches the main changes in the PR.
Linked Issues check ✅ Passed The PR successfully addresses all core objectives from issue #4086: Unix socket trust handling via config flag, nil safety in IP extraction, and preservation of TCP/UDP behavior.
Out of Scope Changes check ✅ Passed All changes are within scope: request handler fixes (req.go), config struct addition (app.go), test coverage (ctx_test.go), and documentation updates align with Unix socket proxy trust objectives.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into main

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch update-proxy-trust-logic-in-req.go

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.

@gaby gaby changed the title 🐛 bug: avoid panic in IsProxyTrusted and add Unix-socket trust test 🐛 bug: fix Unix-socket support in IsProxyTrusted Feb 16, 2026
@codecov
Copy link

codecov bot commented Feb 16, 2026

Codecov Report

❌ Patch coverage is 66.66667% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.01%. Comparing base (6b75c82) to head (8e5d985).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
req.go 66.66% 6 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4088   +/-   ##
=======================================
  Coverage   91.01%   91.01%           
=======================================
  Files         119      119           
  Lines       11302    11320   +18     
=======================================
+ Hits        10286    10303   +17     
- Misses        643      644    +1     
  Partials      373      373           
Flag Coverage Δ
unittests 91.01% <66.66%> (+<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

This pull request effectively addresses a potential panic in IsProxyTrusted by adding a nil check for the remote IP. The introduction of explicit handling for Unix sockets, tying their trust status to the Loopback configuration, is a logical improvement. The accompanying test using a real Unix socket is a great addition that validates the new behavior and improves test coverage. I have one suggestion to make the new test more robust by replacing the fixed sleep with a retry mechanism.

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 PR prevents runtime panics in the proxy trust determination logic by adding defensive nil checks and explicit Unix socket handling. It introduces Unix socket-aware proxy trust semantics controlled by the TrustProxyConfig.Loopback setting and adds test coverage for Unix socket scenarios.

Changes:

  • Added nil guard for RemoteIP() in IsProxyTrusted() to prevent panics
  • Implemented Unix socket detection using type switch on RemoteAddr() with trust controlled by Loopback config
  • Added comprehensive Unix socket test with both enabled and disabled loopback scenarios

Reviewed changes

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

File Description
req.go Added type switch to detect Unix sockets and return trust based on Loopback config; added nil check for RemoteIP() to prevent panic
ctx_test.go Added Test_Ctx_ProxyTrust_UnixRemoteAddr test and helper function to verify Unix socket proxy trust behavior in real runtime scenarios

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

🤖 Fix all issues with AI agents
In `@ctx_test.go`:
- Around line 3012-3036: The fixed 300ms sleep in the goroutine makes the
unix-socket test flaky; replace the sleep with a readiness probe that retries
dialing the unix socket (sock) before creating the fasthttp.HostClient and
calling client.Do. Implement a short loop with a total timeout (e.g., 1s) that
repeatedly attempts net.Dial or net.DialTimeout (using NetworkUnix) and breaks
when a connection succeeds (closing the probe conn immediately), returning a
failure via errCh if the probe times out; then proceed to construct the
HostClient, perform client.Do(req, resp) and send results/errors as before
(preserve result, errCh, and app.Shutdown usage).

@gaby
Copy link
Member Author

gaby commented Feb 16, 2026

@copilot open a new pull request to apply changes based on the comments in this thread

Copy link
Contributor

Copilot AI commented Feb 16, 2026

@gaby I've opened a new pull request, #4089, to work on those changes. Once the pull request is ready, I'll request review from you.

Copilot AI and others added 3 commits February 16, 2026 14:19
…est race condition

Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
🐛 bug: address PR review comments for Unix-socket proxy trust
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

🤖 Fix all issues with AI agents
In `@req.go`:
- Around line 1120-1125: The IsFromLocal method currently returns false for Unix
socket connections because it only checks ip.IsLoopback() on
r.c.fasthttp.RemoteIP(); keep the nil guard, but add an explicit type assertion
for *net.UnixAddr (as done in IsProxyTrusted()) and return true for Unix domain
sockets; in DefaultReq.IsFromLocal, check if remote := r.c.fasthttp.RemoteIP();
if remote == nil return false, else if _, ok := remote.(*net.UnixAddr); ok
return true, otherwise return remote.IsLoopback().
🧹 Nitpick comments (1)
req.go (1)

1084-1098: Core Unix-socket trust logic looks correct.

The type switch cleanly separates address families: Unix sockets are controlled by the new UnixSocket flag, TCP/UDP falls through to existing IP checks, and unknown types default to untrusted. The nil guard on RemoteIP() (line 1096) is good defensive coding even though TCP/UDP addresses should always yield a non-nil IP.

One minor note: RemoteAddr() is called on line 1084 and RemoteIP() is called again on line 1095. You could avoid the second virtual method call by extracting the IP directly from the type assertion:

♻️ Optional: extract IP from the type switch to avoid a second call
 	remoteAddr := r.c.fasthttp.RemoteAddr()
-	switch remoteAddr.(type) {
+	var ip net.IP
+	switch addr := remoteAddr.(type) {
 	case *net.UnixAddr:
 		return config.TrustProxyConfig.UnixSocket
-	case *net.TCPAddr, *net.UDPAddr:
-		// Keep existing RemoteIP/IP-map/CIDR checks for TCP/UDP paths as-is.
+	case *net.TCPAddr:
+		ip = addr.IP
+	case *net.UDPAddr:
+		ip = addr.IP
 	default:
 		// Unknown address type: do not trust by default.
 		return false
 	}
 
-	ip := r.c.fasthttp.RemoteIP()
 	if ip == nil {
 		return false
 	}

Copy link
Contributor

Copilot AI commented Feb 16, 2026

@gaby I've opened a new pull request, #4090, to work on those changes. Once the pull request is ready, I'll request review from you.

Copilot AI and others added 4 commits February 16, 2026 19:00
Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
🐛 bug: Handle Unix sockets explicitly in IsFromLocal()
@ReneWerner87 ReneWerner87 merged commit 1ce2669 into main Feb 17, 2026
26 of 28 checks passed
@ReneWerner87 ReneWerner87 deleted the update-proxy-trust-logic-in-req.go branch February 17, 2026 07:15
@github-project-automation github-project-automation bot moved this to Done in v3 Feb 17, 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.

🐛 [Bug]: Unix Domain Socket isn't trusted as Localhost

3 participants