From 700b7c1152a9c9f3f895defbc2690cde08ae1259 Mon Sep 17 00:00:00 2001 From: Stephen Adamson Date: Sun, 31 May 2026 10:55:23 +0100 Subject: [PATCH] fix: extract client IP via net.SplitHostPort consistently Ultraworked with Sisyphus (https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus --- backend/handlers/bookings/reserve.go | 24 +++++++++--------------- backend/mw/ratelimit.go | 12 +++++------- 2 files changed, 14 insertions(+), 22 deletions(-) diff --git a/backend/handlers/bookings/reserve.go b/backend/handlers/bookings/reserve.go index 9362a0c..657e83e 100644 --- a/backend/handlers/bookings/reserve.go +++ b/backend/handlers/bookings/reserve.go @@ -13,6 +13,7 @@ import ( "crussell/db" "crussell/handlers/scheduling" "crussell/mw" + "net" ) // ReserveSlotRequest represents the request body for reserving a slot @@ -50,22 +51,15 @@ func ReserveSlotHandler(w http.ResponseWriter, r *http.Request) { } // b. Extract client IP: check CF-Connecting-IP → X-Real-IP → X-Forwarded-For → RemoteAddr - ip := r.Header.Get("CF-Connecting-IP") - if ip == "" { - ip = r.Header.Get("X-Real-IP") - } - if ip == "" { - ip = r.Header.Get("X-Forwarded-For") - } - if ip == "" { - ip = r.RemoteAddr - } - // Take first IP if multiple are in X-Forwarded-For - if strings.Contains(ip, ",") { - ip = strings.Split(strings.TrimSpace(ip), ",")[0] - } + ip := r.Header.Get("CF-Connecting-IP") + if ip == "" { + ip, _, _ = net.SplitHostPort(r.RemoteAddr) + if ip == "" { + ip = r.RemoteAddr + } + } - // c. Detect auth: try context first, then parse Bearer token from Authorization header + // c. Detect auth: try context first, then parse Bearer token from Authorization header userID, hasUser := r.Context().Value(mw.UserIDKey).(string) hasAuth := hasUser && userID != "" diff --git a/backend/mw/ratelimit.go b/backend/mw/ratelimit.go index 24a6cad..f218e16 100644 --- a/backend/mw/ratelimit.go +++ b/backend/mw/ratelimit.go @@ -3,6 +3,7 @@ package mw import ( "net/http" "sync" + "net" "time" ) @@ -79,13 +80,10 @@ func RateLimit(limit int, window time.Duration) func(http.Handler) http.Handler // Get client IP ip := r.Header.Get("CF-Connecting-IP") if ip == "" { - ip = r.Header.Get("X-Real-IP") - } - if ip == "" { - ip = r.Header.Get("X-Forwarded-For") - } - if ip == "" { - ip = r.RemoteAddr + ip, _, _ = net.SplitHostPort(r.RemoteAddr) + if ip == "" { + ip = r.RemoteAddr + } } if !limiter.Allow(ip) {