diff --git a/config.go b/config.go index 0e81da2..b366c46 100644 --- a/config.go +++ b/config.go @@ -1,12 +1,5 @@ package proxy -import ( - "net" -) - -// Cidrs is a slice of IPNet addresses -type Cidrs []*net.IPNet - type Config struct { // TrustedSubnets declare IP subnets which are allowed to set ip using X-Real-Ip and X-Forwarded-For TrustedSubnets []string `mapstructure:"trusted_subnets"` diff --git a/plugin.go b/plugin.go index 9afa5a6..b1a652e 100644 --- a/plugin.go +++ b/plugin.go @@ -27,9 +27,7 @@ const ( forwarded string = "Forwarded" ) -var ( - forwardedRegex = regexp.MustCompile(`(?i)(?:for=)([^(;|,| )]+)`) -) +var forwardedRegex = regexp.MustCompile(`(?i)(?:for=)([^(;|,| )]+)`) type Logger interface { NamedLogger(name string) *slog.Logger @@ -107,8 +105,8 @@ func (p *Plugin) Middleware(next http.Handler) http.Handler { } ip := net.ParseIP(host) - for i := range p.trusted { - if p.trusted[i].Contains(ip) { + for _, subnet := range p.trusted { + if subnet.Contains(ip) { resolvedIP := p.resolveIP(r.Header) if resolvedIP != "" { r.RemoteAddr = resolvedIP @@ -144,16 +142,9 @@ func (p *Plugin) resolveIP(headers http.Header) string { } // XFF parse } else if fwd := headers.Get(xff); fwd != "" { - s := strings.Index(fwd, ",") - if s == -1 { - return fwd - } - - if len(fwd) < s { - return "" - } - - return fwd[:s] + // take the first address; Cut returns the whole string when no comma is present + before, _, _ := strings.Cut(fwd, ",") + return before // next -> X-Real-Ip } else if fwd := headers.Get(xrip); fwd != "" { return fwd @@ -174,12 +165,3 @@ func (p *Plugin) resolveIP(headers http.Header) string { return "" } - -func inc(ip net.IP) { - for j := len(ip) - 1; j >= 0; j-- { - ip[j]++ - if ip[j] > 0 { - break - } - } -} diff --git a/trusted_test.go b/trusted_test.go index fc1bdde..6ee735e 100644 --- a/trusted_test.go +++ b/trusted_test.go @@ -62,3 +62,12 @@ func TestCidrsInRange(t *testing.T) { require.Len(t, addrs, 1024) } + +func inc(ip net.IP) { + for j := len(ip) - 1; j >= 0; j-- { + ip[j]++ + if ip[j] > 0 { + break + } + } +}