fix: 兼容反代和 Docker 客户端 IP 解析

This commit is contained in:
Jlypx
2026-07-19 19:41:01 +08:00
parent d4b9797ff7
commit 732aeef880
9 changed files with 165 additions and 20 deletions
+1 -1
View File
@@ -571,7 +571,7 @@ Additional security-related options are available in `config.yaml`:
- `security.response_headers.enabled` to enable configurable response header filtering (disabled uses default allowlist)
- `security.csp` to control Content-Security-Policy headers
- `billing.circuit_breaker` to fail closed on billing errors
- `server.trusted_proxies` to enable X-Forwarded-For parsing
- `server.trusted_proxies` to configure forwarded-IP trust for security-sensitive paths (local/container proxy ranges are trusted by default; replace them with exact remote proxy CIDRs when needed)
- `turnstile.required` to require Turnstile in release mode
**⚠️ Security Warning: HTTP URL Configuration**
+1 -1
View File
@@ -607,7 +607,7 @@ gateway:
- `security.response_headers.enabled` 可启用可配置响应头过滤(关闭时使用默认白名单)
- `security.csp` 配置 Content-Security-Policy
- `billing.circuit_breaker` 计费异常时 fail-closed
- `server.trusted_proxies` 启用可信代理解析 X-Forwarded-For
- `server.trusted_proxies` 配置安全敏感路径的反代 IP 信任(本机/常见 Docker 私网网段默认已信任;远程反代请替换为精确 CIDR)
- `turnstile.required` 在 release 模式强制启用 Turnstile
**网关防御纵深建议(重点)**
+1 -1
View File
@@ -569,7 +569,7 @@ default:
- `security.response_headers.enabled` - 設定可能なレスポンスヘッダーフィルタリングを有効化(無効時はデフォルトの許可リストを使用)
- `security.csp` - Content-Security-Policy ヘッダーの制御
- `billing.circuit_breaker` - 課金エラー時にフェイルクローズ
- `server.trusted_proxies` - X-Forwarded-For パースの有効化
- `server.trusted_proxies` - セキュリティ用途の転送 IP 信頼を設定(ローカル/一般的な Docker プライベート範囲はデフォルトで信頼。リモートプロキシは正確な CIDR に置換)
- `turnstile.required` - リリースモードでの Turnstile 必須化
**⚠️ セキュリティ警告: HTTP URL 設定**
+19 -1
View File
@@ -652,6 +652,21 @@ type ServerConfig struct {
H2C H2CConfig `mapstructure:"h2c"` // HTTP/2 Cleartext 配置
}
// defaultTrustedProxies covers local and container-network reverse proxies.
// It keeps a fresh installation usable without weakening trust to every
// network address; deployments with a public/private load balancer should
// replace it with the exact proxy CIDRs.
func defaultTrustedProxies() []string {
return []string{
"127.0.0.0/8",
"::1/128",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
}
}
// H2CConfig HTTP/2 Cleartext 配置
type H2CConfig struct {
Enabled bool `mapstructure:"enabled"` // 是否启用 H2C
@@ -1714,7 +1729,10 @@ func setDefaults() {
viper.SetDefault("server.read_header_timeout", 10) // 10秒读取请求头
viper.SetDefault("server.max_header_bytes", 64*1024)
viper.SetDefault("server.idle_timeout", 120) // 120秒空闲超时
viper.SetDefault("server.trusted_proxies", []string{})
// Trust local/container reverse proxies by default so existing deployments
// keep working without a config migration. An explicit list still replaces
// this default, and an explicit empty list disables the trust chain.
viper.SetDefault("server.trusted_proxies", defaultTrustedProxies())
viper.SetDefault("server.max_request_body_size", int64(256*1024*1024))
// H2C 默认配置
viper.SetDefault("server.h2c.enabled", false)
+17
View File
@@ -41,12 +41,29 @@ func TestLoadHTTPIngressSafetyDefaults(t *testing.T) {
require.NoError(t, err)
require.Equal(t, 10, cfg.Server.ReadHeaderTimeout)
require.Equal(t, 64*1024, cfg.Server.MaxHeaderBytes)
require.Equal(t, []string{
"127.0.0.0/8",
"::1/128",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
}, cfg.Server.TrustedProxies)
require.Equal(t, int64(32*1024*1024), cfg.Gateway.TextMaxBodySize)
require.True(t, cfg.APIKeyAuth.InvalidAbuse.Enabled)
require.Equal(t, 120, cfg.APIKeyAuth.InvalidAbuse.Threshold)
require.Equal(t, 16384, cfg.APIKeyAuth.InvalidAbuse.Capacity)
}
func TestLoadExplicitEmptyTrustedProxiesKeepsLegacyDefault(t *testing.T) {
resetViperWithJWTSecret(t)
viper.Set("server.trusted_proxies", []string{})
cfg, err := Load()
require.NoError(t, err)
require.Empty(t, cfg.Server.TrustedProxies)
}
func TestLoadForBootstrapAllowsMissingJWTSecret(t *testing.T) {
viper.Reset()
t.Setenv("JWT_SECRET", "")
+81 -6
View File
@@ -8,10 +8,51 @@ import (
"github.com/gin-gonic/gin"
)
// GetClientIP resolves a client address only through Gin's configured trusted
// proxy chain. Forwarding headers from a direct or untrusted peer are ignored.
// GetClientIP resolves the client address using the legacy forwarding-header
// precedence used before the trusted-proxy hardening. It remains the
// compatibility path for request metadata and usage/error logs; security-
// sensitive callers must use GetTrustedClientIP or GetSecurityClientIP.
func GetClientIP(c *gin.Context) string {
return GetTrustedClientIP(c)
if c == nil {
return ""
}
// Preserve the historical precedence used by existing reverse-proxy
// deployments, while skipping an internal proxy address when a public XFF
// value is available. This covers Docker/Nginx setups that accidentally
// write the bridge address into X-Real-IP.
var fallback string
if forwarded := normalizeIP(c.GetHeader("CF-Connecting-IP")); forwarded != "" {
fallback = forwarded
if !isPrivateIP(forwarded) {
return forwarded
}
}
if realIP := normalizeIP(c.GetHeader("X-Real-IP")); realIP != "" {
if fallback == "" {
fallback = realIP
}
if !isPrivateIP(realIP) {
return realIP
}
}
if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
ips := strings.Split(xff, ",")
for _, candidate := range ips {
candidate = strings.TrimSpace(candidate)
if candidate != "" && !isPrivateIP(candidate) {
return normalizeIP(candidate)
}
}
if fallback == "" && len(ips) > 0 {
fallback = normalizeIP(strings.TrimSpace(ips[0]))
}
}
if fallback != "" {
return fallback
}
return normalizeIP(c.ClientIP())
}
// GetTrustedClientIP 从 Gin 的可信代理解析链提取客户端 IP。
@@ -24,9 +65,9 @@ func GetTrustedClientIP(c *gin.Context) string {
return normalizeIP(c.ClientIP())
}
// GetSecurityClientIP returns the address resolved through Gin's configured
// trusted-proxy chain. The legacy toggle is retained for configuration/API
// compatibility, but never makes raw forwarding headers trustworthy by itself.
// GetSecurityClientIP returns the address used by security-sensitive paths.
// The legacy toggle remains in the signature for configuration/API
// compatibility, but cannot make raw forwarding headers trustworthy by itself.
func GetSecurityClientIP(c *gin.Context, _ bool) string {
return GetTrustedClientIP(c)
}
@@ -41,6 +82,27 @@ func normalizeIP(ip string) string {
return ip
}
// privateNets contains the private/loopback ranges skipped while selecting a
// public address from a legacy X-Forwarded-For chain.
var privateNets []*net.IPNet
func init() {
for _, cidr := range []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"127.0.0.0/8",
"::1/128",
"fc00::/7",
} {
_, block, err := net.ParseCIDR(cidr)
if err != nil {
panic("invalid CIDR: " + cidr)
}
privateNets = append(privateNets, block)
}
}
// CompiledIPRules 表示预编译的 IP 匹配规则。
// PatternCount 记录原始规则数量,用于保留“规则存在但全无效”时的行为语义。
type CompiledIPRules struct {
@@ -96,6 +158,19 @@ func matchesCompiledRules(parsedIP net.IP, rules *CompiledIPRules) bool {
return false
}
func isPrivateIP(ipStr string) bool {
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
for _, block := range privateNets {
if block.Contains(ip) {
return true
}
}
return false
}
// MatchesPattern 检查 IP 是否匹配指定的模式(支持单个 IP 或 CIDR)。
// pattern 可以是:
// - 单个 IP: "192.168.1.100"
+20
View File
@@ -32,6 +32,26 @@ func TestGetTrustedClientIPUsesGinClientIP(t *testing.T) {
require.Equal(t, "9.9.9.9", w.Body.String())
}
func TestGetClientIPPreservesLegacyDockerForwardedHeaders(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
require.NoError(t, r.SetTrustedProxies(nil))
r.GET("/t", func(c *gin.Context) {
c.String(200, GetClientIP(c))
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/t", nil)
req.RemoteAddr = "192.168.32.1:12345"
req.Header.Set("X-Forwarded-For", "10.0.0.2, 203.0.113.42")
req.Header.Set("X-Real-IP", "192.168.32.1")
r.ServeHTTP(w, req)
require.Equal(t, 200, w.Code)
require.Equal(t, "203.0.113.42", w.Body.String())
}
func TestCheckIPRestrictionWithCompiledRules(t *testing.T) {
whitelist := CompileIPRules([]string{"10.0.0.0/8", "192.168.1.2"})
blacklist := CompileIPRules([]string{"10.1.1.1"})
+13 -7
View File
@@ -29,15 +29,21 @@ the application's responsibility.
## Trusted client IPs
`server.trusted_proxies` must contain only the CIDR/IP addresses that connect
directly to Sub2API, normally the local Nginx/Caddy address or the private load
balancer subnet. An empty list disables forwarded-IP trust.
`server.trusted_proxies` controls forwarded-IP trust for security-sensitive
paths such as API-key ACLs, session binding, and rejection aggregation. Fresh
installations default to local/container ranges (`127.0.0.0/8`, `::1/128`,
`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, and `fc00::/7`) so a local
Nginx/Caddy or Docker bridge works without a migration. For a remote load
balancer, replace the defaults with only the CIDRs that connect directly to
Sub2API. An explicit empty list disables forwarded-IP trust for these paths;
ordinary request/usage metadata keeps its legacy compatibility behavior.
Never trust `CF-Connecting-IP`, `X-Real-IP`, or `X-Forwarded-For` merely because
the header exists. A CDN deployment must firewall the origin so only the CDN or
load balancer can reach it, and the proxy must overwrite forwarded headers.
Never use `CF-Connecting-IP`, `X-Real-IP`, or `X-Forwarded-For` for an ACL or
session decision merely because the header exists. A CDN deployment must
firewall the origin so only the CDN or load balancer can reach it, and the proxy
must overwrite forwarded headers.
Example for a proxy on the same host:
Example for a proxy on the same host (the default already covers this case):
```yaml
server:
+12 -3
View File
@@ -36,9 +36,18 @@ server:
# Keep-alive idle timeout in seconds.
# Keep-Alive 空闲连接超时(秒)。
idle_timeout: 120
# Trusted proxies for X-Forwarded-For parsing (CIDR/IP). Empty disables trusted proxies.
# 信任的代理地址(CIDR/IP 格式),用于解析 X-Forwarded-For 头。留空则禁用代理信任。
trusted_proxies: []
# Trusted proxies for security-sensitive X-Forwarded-For parsing (CIDR/IP).
# These local/container ranges are the default; replace them with the exact
# proxy CIDRs for a remote load balancer. Set [] explicitly to disable trust.
# 安全敏感场景解析 X-Forwarded-For 的可信代理(CIDR/IP)。以下为本机/容器
# 网段默认值;远程负载均衡请替换为实际 CIDR。显式设置 [] 可禁用代理信任。
trusted_proxies:
- 127.0.0.0/8
- ::1/128
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
- fc00::/7
# Global max request body size in bytes (default: 256MB)
# 全局最大请求体大小(字节,默认 256MB)
# Applies to all requests, especially important for h2c first request memory protection