fix(audit): strip IPv6 brackets before INET insert #9
+13
-11
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -87,22 +88,23 @@ func (s *statusRecorder) WriteHeader(c int) {
|
|||||||
func clientIP(r *http.Request) string {
|
func clientIP(r *http.Request) string {
|
||||||
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
|
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
|
||||||
if i := strings.IndexByte(fwd, ','); i > 0 {
|
if i := strings.IndexByte(fwd, ','); i > 0 {
|
||||||
return strings.TrimSpace(fwd[:i])
|
return stripBrackets(strings.TrimSpace(fwd[:i]))
|
||||||
}
|
}
|
||||||
return strings.TrimSpace(fwd)
|
return stripBrackets(strings.TrimSpace(fwd))
|
||||||
}
|
}
|
||||||
if host, _, ok := splitHostPort(r.RemoteAddr); ok {
|
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||||
|
// net.SplitHostPort returns IPv6 without brackets already.
|
||||||
return host
|
return host
|
||||||
}
|
}
|
||||||
return r.RemoteAddr
|
return stripBrackets(r.RemoteAddr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// splitHostPort is a port-tolerant version of net.SplitHostPort that doesn't
|
// stripBrackets removes the `[...]` wrapping IPv6 hosts pick up from
|
||||||
// error on missing port.
|
// net/http's RemoteAddr in some Go versions, since Postgres `inet` rejects
|
||||||
func splitHostPort(s string) (string, string, bool) {
|
// `[::1]` but accepts `::1`.
|
||||||
i := strings.LastIndexByte(s, ':')
|
func stripBrackets(s string) string {
|
||||||
if i < 0 {
|
if len(s) >= 2 && s[0] == '[' && s[len(s)-1] == ']' {
|
||||||
return s, "", false
|
return s[1 : len(s)-1]
|
||||||
}
|
}
|
||||||
return s[:i], s[i+1:], true
|
return s
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user