fix: extract client IP via net.SplitHostPort consistently

Ultraworked with Sisyphus (https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
2026-05-31 10:55:23 +01:00
co-authored by Sisyphus
parent a38fda612e
commit 700b7c1152
2 changed files with 14 additions and 22 deletions
+9 -15
View File
@@ -13,6 +13,7 @@ import (
"crussell/db" "crussell/db"
"crussell/handlers/scheduling" "crussell/handlers/scheduling"
"crussell/mw" "crussell/mw"
"net"
) )
// ReserveSlotRequest represents the request body for reserving a slot // 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 // b. Extract client IP: check CF-Connecting-IP → X-Real-IP → X-Forwarded-For → RemoteAddr
ip := r.Header.Get("CF-Connecting-IP") ip := r.Header.Get("CF-Connecting-IP")
if ip == "" { if ip == "" {
ip = r.Header.Get("X-Real-IP") ip, _, _ = net.SplitHostPort(r.RemoteAddr)
} if ip == "" {
if ip == "" { ip = r.RemoteAddr
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]
}
// 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) userID, hasUser := r.Context().Value(mw.UserIDKey).(string)
hasAuth := hasUser && userID != "" hasAuth := hasUser && userID != ""
+5 -7
View File
@@ -3,6 +3,7 @@ package mw
import ( import (
"net/http" "net/http"
"sync" "sync"
"net"
"time" "time"
) )
@@ -79,13 +80,10 @@ func RateLimit(limit int, window time.Duration) func(http.Handler) http.Handler
// Get client IP // Get client IP
ip := r.Header.Get("CF-Connecting-IP") ip := r.Header.Get("CF-Connecting-IP")
if ip == "" { if ip == "" {
ip = r.Header.Get("X-Real-IP") ip, _, _ = net.SplitHostPort(r.RemoteAddr)
} if ip == "" {
if ip == "" { ip = r.RemoteAddr
ip = r.Header.Get("X-Forwarded-For") }
}
if ip == "" {
ip = r.RemoteAddr
} }
if !limiter.Allow(ip) { if !limiter.Allow(ip) {