fix: support non-standard X-Forwarded-For header formats#4605
Open
xingzihai wants to merge 2 commits intogin-gonic:masterfrom
Open
fix: support non-standard X-Forwarded-For header formats#4605xingzihai wants to merge 2 commits intogin-gonic:masterfrom
xingzihai wants to merge 2 commits intogin-gonic:masterfrom
Conversation
) This fix addresses issue gin-gonic#4572 where ClientIP method fails to parse X-Forwarded-For headers with non-standard formats: - IPv6 addresses with square brackets: [240e:318:2f4a:de56::240] - IPv4 addresses with port: 192.168.8.39:38792 - IPv6 addresses with square brackets and port: [240e:318:2f4a:de56::240]:38792 Changes: - Modified validateHeader() to normalize IP strings before parsing - Added normalizeIPFromHeader() helper function to handle various formats - Added tryRemoveBracketsAndParse() helper function for bracket removal - Added comprehensive test cases for all non-standard formats The fix uses net.SplitHostPort to handle IP:port and [IPv6]:port formats, and manual bracket removal for [IPv6] format (which SplitHostPort doesn't handle).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The
ClientIPmethod did not properly handle non-standard X-Forwarded-For header formats:[240e:318:2f4a:de56::240]192.168.8.39:38792[240e:318:2f4a:de56::240]:38792Problem
net.ParseIPcannot parse these formats directly, causingClientIPto fail or return incorrect results.Solution
net.SplitHostPortto handle formats with ports[IPv6]formatnormalizeIPFromHeaderandtryRemoveBracketsAndParseChanges
validateHeadermethod ingin.go(+42 lines)gin_test.go(+255 lines)Testing
Added comprehensive tests for:
Fixes #4572