Remove IP whitelist mechanism, keep only token authentication

Co-authored-by: krau <71133316+krau@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-01-19 05:42:14 +00:00
parent 20a5e317ae
commit 173a5e3733
6 changed files with 11 additions and 204 deletions

View File

@@ -1,7 +1,6 @@
package api
import (
"net"
"net/http"
"strings"
"time"
@@ -10,7 +9,7 @@ import (
"github.com/krau/SaveAny-Bot/config"
)
// authMiddleware validates API token and IP restrictions
// authMiddleware validates API token
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip auth for health check
@@ -21,15 +20,6 @@ func authMiddleware(next http.Handler) http.Handler {
cfg := config.C()
// Check IP whitelist if configured
if len(cfg.API.TrustedIPs) > 0 {
clientIP := getClientIP(r)
if !isIPAllowed(clientIP, cfg.API.TrustedIPs) {
http.Error(w, `{"error":"forbidden: IP not allowed"}`, http.StatusForbidden)
return
}
}
// Check token if configured
if cfg.API.Token != "" {
authHeader := r.Header.Get("Authorization")
@@ -74,52 +64,3 @@ func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// getClientIP extracts the real client IP from the request
func getClientIP(r *http.Request) string {
// Check X-Forwarded-For header
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
ips := strings.Split(xff, ",")
if len(ips) > 0 {
return strings.TrimSpace(ips[0])
}
}
// Check X-Real-IP header
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return xri
}
// Fall back to RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
// If SplitHostPort fails, try to parse RemoteAddr as IP directly
if parsedIP := net.ParseIP(r.RemoteAddr); parsedIP != nil {
return r.RemoteAddr
}
// If all else fails, return empty string (will fail IP check)
return ""
}
return ip
}
// isIPAllowed checks if the client IP is in the allowed list
func isIPAllowed(clientIP string, allowedIPs []string) bool {
for _, allowedIP := range allowedIPs {
if clientIP == allowedIP || allowedIP == "*" {
return true
}
// Support CIDR notation
if strings.Contains(allowedIP, "/") {
_, ipNet, err := net.ParseCIDR(allowedIP)
if err != nil {
continue
}
ip := net.ParseIP(clientIP)
if ip != nil && ipNet.Contains(ip) {
return true
}
}
}
return false
}