fix(web): read the client address from the proxy end of forwarded headers

getRemoteIp took a trusted proxy's X-Real-IP first, otherwise the leftmost
X-Forwarded-For entry. A proxy that forwards a client-sent X-Real-IP
unchanged (Caddy, HAProxy) or appends to X-Forwarded-For leaves both values
to the client. X-Forwarded-For is now read from the right, skipping trusted
proxies. X-Real-IP is believed only when it agrees with that hop or stands
alone, and a disagreement falls back to the proxy's own address.

The documented Caddyfile and the docs reverse-proxy generator now overwrite
X-Real-IP with the address Caddy saw.
This commit is contained in:
MHSanaei
2026-10-24 01:39:23 +02:00
parent 1df8ab29f8
commit d50c419e28
8 changed files with 87 additions and 24 deletions
+29
View File
@@ -33,6 +33,35 @@ func TestGetRemoteIpHonorsForwardedHeadersFromTrustedLoopbackProxy(t *testing.T)
}
}
// Caddy and HAProxy set X-Forwarded-For but pass the client's own X-Real-IP
// through, so a client could pick its login-limiter bucket per request.
func TestGetRemoteIpDistrustsRealIPThatContradictsForwardedFor(t *testing.T) {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Request.RemoteAddr = "127.0.0.1:12345"
c.Request.Header.Set("X-Forwarded-For", "203.0.113.5")
c.Request.Header.Set("X-Real-IP", "198.51.100.1")
if got := getRemoteIp(c); got != "127.0.0.1" {
t.Fatalf("remote IP = %q, want the proxy address when the forwarded headers disagree", got)
}
}
// An appending proxy keeps whatever X-Forwarded-For the client sent in front of
// the address it saw, so only the hop next to the trusted proxies is real.
func TestGetRemoteIpReadsForwardedForFromTheProxyEnd(t *testing.T) {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Request.RemoteAddr = "127.0.0.1:12345"
c.Request.Header.Set("X-Forwarded-For", "198.51.100.1, 203.0.113.5")
if got := getRemoteIp(c); got != "203.0.113.5" {
t.Fatalf("remote IP = %q, want the hop the trusted proxy appended", got)
}
}
func TestResolveHostPrefersForwardedHostOverRealIP(t *testing.T) {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())