安全修复: 收敛认证与日志风险并补充基础测试

This commit is contained in:
2026-02-16 00:34:52 +08:00
parent 7627885b1b
commit 7d42f96e42
12 changed files with 163 additions and 50 deletions

View File

@@ -197,6 +197,9 @@ class IPRateLimiter:
# 全局IP限流器实例
ip_rate_limiter = IPRateLimiter()
_TRUTHY_VALUES = {"1", "true", "yes", "on"}
_TRUST_PROXY_HEADERS = str(os.environ.get("TRUST_PROXY_HEADERS", "false") or "").strip().lower() in _TRUTHY_VALUES
def require_ip_not_locked(f):
"""装饰器检查IP是否被锁定"""
@@ -443,7 +446,7 @@ def get_client_ip(trust_proxy=False):
"""
# 安全说明X-Forwarded-For 可被伪造
# 仅在确认请求来自可信代理时才使用代理头
if trust_proxy:
if trust_proxy and _TRUST_PROXY_HEADERS:
if request.headers.get('X-Forwarded-For'):
return request.headers.get('X-Forwarded-For').split(',')[0].strip()
elif request.headers.get('X-Real-IP'):
@@ -455,7 +458,7 @@ def get_client_ip(trust_proxy=False):
def _load_trusted_proxy_networks():
"""加载可信代理 CIDR 列表。"""
default_cidrs = "127.0.0.1/32,::1/128,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7"
default_cidrs = "127.0.0.1/32,::1/128"
raw = str(os.environ.get("TRUSTED_PROXY_CIDRS", default_cidrs) or "").strip()
if not raw:
return []
@@ -525,6 +528,9 @@ def _extract_real_ip_from_forwarded_chain() -> str | None:
def get_rate_limit_ip() -> str:
"""在可信代理场景下取真实IP用于限流/风控。"""
remote_addr = request.remote_addr or ""
if not _TRUST_PROXY_HEADERS:
return remote_addr
remote_ip = _parse_ip_address(remote_addr)
if remote_ip is None:
return remote_addr