优化更新

This commit is contained in:
2026-09-14 11:54:46 +08:00
parent 06c623be87
commit bf08cf1248
12 changed files with 186 additions and 357 deletions
@@ -39,7 +39,7 @@ tests/
│ │ ├── test_base_service_page.py
│ │ └── ...
│ ├── utils/ # 工具函数测试
│ │ ├── test_ip_trusted_proxy.py
│ │ ├── test_ip.py
│ │ ├── test_ip2region.py
│ │ └── ...
│ └── scripts/ # 脚本测试
@@ -256,12 +256,11 @@ def test_is_private_ip_private_ranges():
assert _is_private_ip('8.8.8.8') is False
```
### 代理白名单测试
### IP 获取测试
```python
# tests/unit/utils/test_ip_trusted_proxy.py
# tests/unit/utils/test_ip.py
import types
from utils import ip as ip_mod
from utils.ip import get_client_ip
@@ -273,32 +272,25 @@ def _make_request(client_host, xff=None):
return req
def test_proxy_count_zero_ignores_xff(monkeypatch):
"""TRUSTED_PROXY_COUNT=0:不信任代理头"""
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_COUNT', 0)
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_IPS', frozenset({'127.0.0.1'}))
assert get_client_ip(_make_request('203.0.113.9', xff='1.2.3.4')) == '203.0.113.9'
def test_peer_not_in_whitelist_rejects_xff(monkeypatch):
"""直连对端不在白名单 → XFF 被忽略"""
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_COUNT', 1)
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_IPS', frozenset({'10.0.0.1'}))
assert get_client_ip(_make_request('203.0.113.9', xff='1.2.3.4')) == '203.0.113.9'
def test_peer_in_whitelist_trusts_xff(monkeypatch):
"""单层代理:对端在白名单 → 信任 XFF"""
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_COUNT', 1)
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_IPS', frozenset({'10.0.0.1'}))
def test_xff_single_ip():
"""XFF 只有一个 IP → 直接返回"""
assert get_client_ip(_make_request('10.0.0.1', xff='1.2.3.4')) == '1.2.3.4'
def test_peer_in_whitelist_spoofed_left_entry_ignored(monkeypatch):
"""客户端伪造条目只会在 XFF 左侧"""
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_COUNT', 1)
monkeypatch.setattr(ip_mod, 'TRUSTED_PROXY_IPS', frozenset({'10.0.0.1'}))
assert get_client_ip(_make_request('10.0.0.1', xff='6.6.6.6, 1.2.3.4')) == '1.2.3.4'
def test_xff_multiple_ips_returns_leftmost():
"""XFF 多个 IP → 取最左侧(真实客户端 IP)"""
assert get_client_ip(_make_request('10.0.0.1', xff='1.2.3.4, 10.0.0.1')) == '1.2.3.4'
def test_no_xff_falls_back_to_client_host():
"""无 XFF 头 → 回退到 request.client.host"""
assert get_client_ip(_make_request('203.0.113.9')) == '203.0.113.9'
def test_no_client_falls_back_to_localhost():
"""client 为 None → 回退到 127.0.0.1"""
req = types.SimpleNamespace(client=None, headers={})
assert get_client_ip(req) == '127.0.0.1'
```
### service 层公共 fixture