Resolve real client IP behind trusted proxies (closes #94)
check / check (push) Successful in 2m31s
check / check (push) Successful in 2m31s
RFC1918 ranges are the default trusted proxy set on an omitted key; an explicit list replaces the default; an explicit empty list trusts no one; unparseable values abort startup; forwarded headers honored only from trusted peers. Independent review passed: #127 (comment) model: claude-opus-4-8 (implementation and review); merged by claude-fable-5
This commit was merged in pull request #127.
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"sneak.berlin/go/pixa/internal/clientip"
|
||||
"sneak.berlin/go/pixa/internal/config"
|
||||
)
|
||||
|
||||
// testForwardedClient is the client address the proxy forwards.
|
||||
const testForwardedClient = "203.0.113.7"
|
||||
|
||||
// newTestMiddleware builds a Middleware whose resolver trusts the given
|
||||
// CIDRs and whose logger writes JSON to buf.
|
||||
func newTestMiddleware(t *testing.T, buf *bytes.Buffer, trusted ...string) *Middleware {
|
||||
t.Helper()
|
||||
|
||||
prefixes := make([]netip.Prefix, 0, len(trusted))
|
||||
|
||||
for _, c := range trusted {
|
||||
p, err := netip.ParsePrefix(c)
|
||||
if err != nil {
|
||||
t.Fatalf("netip.ParsePrefix(%q) error = %v", c, err)
|
||||
}
|
||||
|
||||
prefixes = append(prefixes, p)
|
||||
}
|
||||
|
||||
return &Middleware{
|
||||
log: slog.New(slog.NewJSONHandler(buf, nil)),
|
||||
config: &config.Config{TrustedProxies: prefixes},
|
||||
clientIP: clientip.NewResolver(prefixes),
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientIPMiddlewareStoresResolvedIP verifies the ClientIP middleware
|
||||
// puts the resolved address into the request context for a trusted and an
|
||||
// untrusted peer.
|
||||
func TestClientIPMiddlewareStoresResolvedIP(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
remoteAddr string
|
||||
forwarded string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "trusted peer honors forwarded client",
|
||||
remoteAddr: "10.0.0.1:5000",
|
||||
forwarded: testForwardedClient,
|
||||
want: testForwardedClient,
|
||||
},
|
||||
{
|
||||
name: "untrusted peer ignores forwarded header",
|
||||
remoteAddr: "198.51.100.9:5000",
|
||||
forwarded: testForwardedClient,
|
||||
want: "198.51.100.9",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mw := newTestMiddleware(t, &bytes.Buffer{}, "10.0.0.0/8")
|
||||
|
||||
var got string
|
||||
|
||||
handler := mw.ClientIP()(http.HandlerFunc(
|
||||
func(_ http.ResponseWriter, r *http.Request) {
|
||||
got = clientip.FromContext(r.Context())
|
||||
}))
|
||||
|
||||
req := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, "/", nil)
|
||||
req.RemoteAddr = tt.remoteAddr
|
||||
req.Header.Set("X-Forwarded-For", tt.forwarded)
|
||||
|
||||
handler.ServeHTTP(httptest.NewRecorder(), req)
|
||||
|
||||
if got != tt.want {
|
||||
t.Errorf("client IP in context = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoggingUsesResolvedClientIP verifies the logging middleware records
|
||||
// the resolved forwarded client IP rather than the proxy peer address.
|
||||
func TestLoggingUsesResolvedClientIP(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var buf bytes.Buffer
|
||||
|
||||
mw := newTestMiddleware(t, &buf, "10.0.0.0/8")
|
||||
|
||||
handler := mw.ClientIP()(mw.Logging()(http.HandlerFunc(
|
||||
func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})))
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
|
||||
req.RemoteAddr = "10.0.0.1:5000"
|
||||
req.Header.Set("X-Forwarded-For", testForwardedClient)
|
||||
|
||||
handler.ServeHTTP(httptest.NewRecorder(), req)
|
||||
|
||||
if !strings.Contains(buf.String(), `"remoteIP":"`+testForwardedClient+`"`) {
|
||||
t.Errorf("log output missing resolved client IP; got %q", buf.String())
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -14,6 +13,7 @@ import (
|
||||
ghmm "github.com/slok/go-http-metrics/middleware"
|
||||
"github.com/slok/go-http-metrics/middleware/std"
|
||||
"go.uber.org/fx"
|
||||
"sneak.berlin/go/pixa/internal/clientip"
|
||||
"sneak.berlin/go/pixa/internal/config"
|
||||
"sneak.berlin/go/pixa/internal/logger"
|
||||
)
|
||||
@@ -58,31 +58,34 @@ type Params struct {
|
||||
|
||||
// Middleware provides HTTP middleware functions.
|
||||
type Middleware struct {
|
||||
log *slog.Logger
|
||||
config *config.Config
|
||||
log *slog.Logger
|
||||
config *config.Config
|
||||
clientIP *clientip.Resolver
|
||||
}
|
||||
|
||||
// New creates a new Middleware instance.
|
||||
func New(_ fx.Lifecycle, params Params) (*Middleware, error) {
|
||||
s := &Middleware{
|
||||
log: params.Logger.Get(),
|
||||
config: params.Config,
|
||||
log: params.Logger.Get(),
|
||||
config: params.Config,
|
||||
clientIP: clientip.NewResolver(params.Config.TrustedProxies),
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func ipFromHostPort(hp string) string {
|
||||
h, _, err := net.SplitHostPort(hp)
|
||||
if err != nil {
|
||||
return ""
|
||||
// ClientIP returns a middleware that resolves the real client IP,
|
||||
// honoring X-Forwarded-For only from trusted proxies, and stores it in
|
||||
// the request context for the logging middleware and handlers to read.
|
||||
func (s *Middleware) ClientIP() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := s.clientIP.Resolve(
|
||||
r.RemoteAddr, r.Header.Values(clientip.ForwardedForHeader))
|
||||
ctx := clientip.WithClientIP(r.Context(), ip)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
if len(h) > 0 && h[0] == '[' {
|
||||
return h[1 : len(h)-1]
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
type loggingResponseWriter struct {
|
||||
@@ -127,7 +130,7 @@ func (s *Middleware) Logging() func(http.Handler) http.Handler {
|
||||
"request_id", reqID,
|
||||
"referer", r.Referer(),
|
||||
"proto", r.Proto,
|
||||
"remoteIP", ipFromHostPort(r.RemoteAddr),
|
||||
"remoteIP", clientip.FromContext(ctx),
|
||||
"status", lrw.statusCode,
|
||||
"response_bytes", lrw.bytesWritten,
|
||||
"latency_ms", latency.Milliseconds(),
|
||||
|
||||
Reference in New Issue
Block a user