mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 00:15:56 +08:00
fix(site): trim site UA/header fields and surface invalid header errors (#7535)
This commit is contained in:
@@ -11,9 +11,11 @@ import threading
|
||||
import time
|
||||
import types
|
||||
import weakref
|
||||
from collections.abc import Mapping
|
||||
from contextlib import AsyncExitStack, asynccontextmanager, contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, AsyncIterator, Dict, Iterator, Literal, Optional, Tuple, Union, cast, overload
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import chardet
|
||||
import httpx
|
||||
@@ -79,6 +81,74 @@ def _proxy_configured(proxies: Any) -> bool:
|
||||
return bool(proxies)
|
||||
|
||||
|
||||
def _url_origin(url: str) -> str:
|
||||
"""
|
||||
提取仅含协议与主机端口的目标来源,避免在请求异常日志中泄露路径或查询凭据。
|
||||
"""
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
port = f":{parts.port}" if parts.port is not None else ""
|
||||
except ValueError:
|
||||
return "<invalid-url>"
|
||||
if not parts.scheme or not parts.hostname:
|
||||
return "<invalid-url>"
|
||||
host = f"[{parts.hostname}]" if ":" in parts.hostname else parts.hostname
|
||||
return f"{parts.scheme}://{host}{port}"
|
||||
|
||||
|
||||
def _is_valid_header_part(part: Any, *, is_name: bool) -> bool:
|
||||
"""
|
||||
按 HTTP 请求头规范校验单个字段名或值,避免调用传输库内部工具改变 egress 指纹。
|
||||
"""
|
||||
if isinstance(part, bytes):
|
||||
text = part.decode("latin-1")
|
||||
elif isinstance(part, str):
|
||||
try:
|
||||
part.encode("latin-1")
|
||||
except UnicodeEncodeError:
|
||||
return False
|
||||
text = part
|
||||
else:
|
||||
return False
|
||||
if is_name:
|
||||
return bool(text) and not text[0].isspace() and ":" not in text and "\r" not in text and "\n" not in text
|
||||
if not text:
|
||||
return True
|
||||
if text != text.strip():
|
||||
return False
|
||||
return not any((ord(ch) < 0x20 and ch != "\t") or ord(ch) == 0x7F for ch in text)
|
||||
|
||||
|
||||
def _find_invalid_header_names(headers: Any) -> list[str]:
|
||||
"""
|
||||
识别触发请求头校验失败的字段名称,不输出可能包含凭据的字段值。
|
||||
"""
|
||||
if not isinstance(headers, Mapping):
|
||||
return []
|
||||
invalid_names: list[str] = []
|
||||
for key, value in headers.items():
|
||||
if value is None:
|
||||
continue
|
||||
if not _is_valid_header_part(key, is_name=True) or not _is_valid_header_part(value, is_name=False):
|
||||
invalid_names.append(str(key))
|
||||
return invalid_names
|
||||
|
||||
|
||||
def _log_invalid_header_error(error: Exception, headers: Any, url: str) -> None:
|
||||
"""
|
||||
记录请求头构造失败的异常类型与出错字段,避免静默返回 None 误导为网络故障。
|
||||
"""
|
||||
invalid_names = _find_invalid_header_names(headers)
|
||||
origin = _url_origin(url)
|
||||
if invalid_names:
|
||||
logger.warning(
|
||||
f"HTTP 请求头无效({type(error).__name__}),"
|
||||
f"异常字段:{', '.join(invalid_names)},目标:{origin}"
|
||||
)
|
||||
return
|
||||
logger.warning(f"HTTP 请求头无效({type(error).__name__}),目标:{origin}")
|
||||
|
||||
|
||||
def _can_retry_proxy_tls12(url: str, proxies: Any, method: str) -> bool:
|
||||
"""
|
||||
仅为代理下的 HTTPS 幂等请求启用 TLS 1.2 回退。
|
||||
@@ -656,6 +726,8 @@ class RequestUtils:
|
||||
if headers:
|
||||
self._headers = headers
|
||||
else:
|
||||
if isinstance(ua, str):
|
||||
ua = ua.strip()
|
||||
if ua and ua == _default_user_agent:
|
||||
caller_name = get_caller()
|
||||
if caller_name:
|
||||
@@ -836,6 +908,11 @@ class RequestUtils:
|
||||
if raise_exception:
|
||||
raise
|
||||
return None
|
||||
except requests.exceptions.InvalidHeader as error:
|
||||
if raise_exception:
|
||||
raise
|
||||
_log_invalid_header_error(error, kwargs.get("headers"), url)
|
||||
return None
|
||||
except requests.exceptions.RequestException:
|
||||
if raise_exception:
|
||||
raise
|
||||
@@ -1435,6 +1512,8 @@ class AsyncRequestUtils:
|
||||
# 过滤掉None值的headers
|
||||
self._headers = {k: v for k, v in headers.items() if v is not None}
|
||||
else:
|
||||
if isinstance(ua, str):
|
||||
ua = ua.strip()
|
||||
if ua and ua == _default_user_agent:
|
||||
caller_name = get_caller()
|
||||
if caller_name:
|
||||
@@ -1615,30 +1694,16 @@ class AsyncRequestUtils:
|
||||
return await self._dispatch_request(
|
||||
True, cookies_dict, method, url, True, **kwargs
|
||||
)
|
||||
except _H2_TUNNEL_BREAK_ERRORS:
|
||||
_trip_h2_proxy_breaker(self._proxies, url)
|
||||
try:
|
||||
return await self._dispatch_request(
|
||||
False,
|
||||
cookies_dict,
|
||||
method,
|
||||
url,
|
||||
True if proxy_tls_fallback else raise_exception,
|
||||
**kwargs,
|
||||
)
|
||||
except httpx2.RequestError as error:
|
||||
if proxy_tls_fallback and isinstance(error, _ASYNC_PROXY_TLS_FALLBACK_ERRORS):
|
||||
return await self._dispatch_with_tls12(
|
||||
False,
|
||||
cookies_dict,
|
||||
method,
|
||||
url,
|
||||
raise_exception,
|
||||
**kwargs,
|
||||
)
|
||||
if raise_exception:
|
||||
raise
|
||||
return None
|
||||
except _H2_TUNNEL_BREAK_ERRORS as error:
|
||||
return await self._handle_h2_proxy_tunnel_error(
|
||||
error,
|
||||
cookies_dict,
|
||||
method,
|
||||
url,
|
||||
proxy_tls_fallback,
|
||||
raise_exception,
|
||||
**kwargs,
|
||||
)
|
||||
except _ASYNC_PROXY_TLS_FALLBACK_ERRORS:
|
||||
if proxy_tls_fallback:
|
||||
return await self._dispatch_with_tls12(
|
||||
@@ -1659,6 +1724,53 @@ class AsyncRequestUtils:
|
||||
raise
|
||||
return None
|
||||
|
||||
async def _handle_h2_proxy_tunnel_error(
|
||||
self,
|
||||
error: Exception,
|
||||
cookies_dict: Optional[dict[str, Any]],
|
||||
method: str,
|
||||
url: str,
|
||||
proxy_tls_fallback: bool,
|
||||
raise_exception: bool,
|
||||
**kwargs: Any,
|
||||
) -> Optional[httpx2.Response]:
|
||||
"""
|
||||
处理代理 HTTP/2 协议异常:本地非法请求头直接告警返回,真实隧道中断再熔断并回落 HTTP/1.1。
|
||||
"""
|
||||
if isinstance(error, httpx2.LocalProtocolError):
|
||||
request_headers = kwargs.get("headers", self._headers)
|
||||
if _find_invalid_header_names(request_headers):
|
||||
if raise_exception:
|
||||
raise error
|
||||
_log_invalid_header_error(error, request_headers, url)
|
||||
return None
|
||||
if self._proxies:
|
||||
_trip_h2_proxy_breaker(self._proxies, url)
|
||||
try:
|
||||
return await self._dispatch_request(
|
||||
False,
|
||||
cookies_dict,
|
||||
method,
|
||||
url,
|
||||
True if proxy_tls_fallback else raise_exception,
|
||||
**kwargs,
|
||||
)
|
||||
except httpx2.RequestError as fallback_error:
|
||||
if proxy_tls_fallback and isinstance(
|
||||
fallback_error, _ASYNC_PROXY_TLS_FALLBACK_ERRORS
|
||||
):
|
||||
return await self._dispatch_with_tls12(
|
||||
False,
|
||||
cookies_dict,
|
||||
method,
|
||||
url,
|
||||
raise_exception,
|
||||
**kwargs,
|
||||
)
|
||||
if raise_exception:
|
||||
raise
|
||||
return None
|
||||
|
||||
async def _dispatch_request(
|
||||
self, http2: bool, cookies_dict: Optional[dict[str, Any]], method: str, url: str,
|
||||
raise_exception: bool, verify: Optional[_VerifySetting] = None, **kwargs: Any
|
||||
@@ -1773,6 +1885,12 @@ class AsyncRequestUtils:
|
||||
if raise_exception:
|
||||
raise
|
||||
return None
|
||||
except httpx2.LocalProtocolError as error:
|
||||
if raise_exception:
|
||||
raise
|
||||
if _find_invalid_header_names(kwargs.get("headers")):
|
||||
_log_invalid_header_error(error, kwargs.get("headers"), url)
|
||||
return None
|
||||
except httpx2.RequestError:
|
||||
if raise_exception:
|
||||
raise
|
||||
|
||||
@@ -36,6 +36,9 @@ _SITE_MUTATION_FIELDS = frozenset(
|
||||
}
|
||||
)
|
||||
|
||||
# 复制粘贴站点配置时容易带入首尾空白,直接参与请求头或地址构造的字段在入库前统一裁剪。
|
||||
_SITE_TRIMMED_STRING_FIELDS = frozenset({"ua", "cookie", "rss", "apikey", "token"})
|
||||
|
||||
_SITE_USERDATA_MUTATION_FIELDS = frozenset(
|
||||
{
|
||||
"domain",
|
||||
@@ -350,12 +353,18 @@ class SiteMutation:
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""
|
||||
拒绝模型外字段并冻结嵌套 JSON。
|
||||
拒绝模型外字段、裁剪易受复制空白影响的请求字段并冻结嵌套 JSON。
|
||||
"""
|
||||
normalized = {
|
||||
key: value.strip()
|
||||
if key in _SITE_TRIMMED_STRING_FIELDS and isinstance(value, str)
|
||||
else value
|
||||
for key, value in self.values.items()
|
||||
}
|
||||
object.__setattr__(
|
||||
self,
|
||||
"values",
|
||||
_freeze_mapping(self.values, allowed_fields=_SITE_MUTATION_FIELDS),
|
||||
_freeze_mapping(normalized, allowed_fields=_SITE_MUTATION_FIELDS),
|
||||
)
|
||||
|
||||
def to_payload(self) -> dict[str, JsonData]:
|
||||
|
||||
@@ -161,6 +161,8 @@ class SiteMutationCommand:
|
||||
"""
|
||||
values = dict(payload)
|
||||
raw_url = values.get("url")
|
||||
if isinstance(raw_url, str):
|
||||
raw_url = raw_url.strip()
|
||||
if not isinstance(raw_url, str) or not raw_url:
|
||||
return SiteMutationResult(False, "站点地址不能为空")
|
||||
if self._auth_level_provider() < 2:
|
||||
@@ -204,7 +206,9 @@ class SiteMutationCommand:
|
||||
return SiteMutationResult(False, "站点不存在")
|
||||
|
||||
raw_url = values.get("url")
|
||||
normalized_url = self._url_normalizer(raw_url if isinstance(raw_url, str) else "")
|
||||
normalized_url = self._url_normalizer(
|
||||
raw_url.strip() if isinstance(raw_url, str) else ""
|
||||
)
|
||||
normalized_domain = self._domain_extractor(normalized_url)
|
||||
values["url"] = normalized_url
|
||||
values["domain"] = normalized_domain
|
||||
|
||||
@@ -790,7 +790,12 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
"""
|
||||
site_url = site_info.url
|
||||
site_cookie = site_info.cookie or ""
|
||||
ua = site_info.ua or self.runtime_config.user_agent
|
||||
ua = (site_info.ua or "").strip() or self.runtime_config.user_agent
|
||||
if ua and not site_rules.is_valid_http_header_value(ua):
|
||||
logger.warning(
|
||||
f"站点【{site_info.name}】请求头 User-Agent 包含非法字符,无法发起连通性测试"
|
||||
)
|
||||
return False, "站点浏览器标识(UA)包含非法字符,请检查配置!"
|
||||
render = site_info.render
|
||||
public = site_info.public
|
||||
proxies = (self.runtime_config.proxy or {}) if site_info.proxy else {}
|
||||
|
||||
@@ -495,7 +495,7 @@ class SiteOper(DbOper):
|
||||
if not site:
|
||||
return False, "站点不存在"
|
||||
self._stage_update(site, {
|
||||
"cookie": cookies
|
||||
"cookie": cookies.strip() if isinstance(cookies, str) else cookies
|
||||
})
|
||||
return True, "更新站点Cookie成功"
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"""
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Optional
|
||||
from typing import Mapping, Optional
|
||||
from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplit
|
||||
|
||||
from lxml import etree
|
||||
@@ -141,6 +141,47 @@ def resolve_page_url(site_url: str, page_path: Optional[str]) -> str:
|
||||
return urljoin(f"{str(site_url).rstrip('/')}/", page_path.lstrip("/"))
|
||||
|
||||
|
||||
def is_valid_http_header_value(value: str) -> bool:
|
||||
"""
|
||||
校验字符串能否作为合法的 HTTP 请求头值发送。
|
||||
|
||||
拒绝首尾空白、控制字符(保留水平制表符)以及无法按 Latin-1 编码的字符,
|
||||
避免底层 HTTP 客户端在组装请求头阶段直接抛出异常。
|
||||
|
||||
:param value: 待校验的请求头文本;空字符串视为合法
|
||||
:return: 可安全写入 HTTP 请求头时返回 True,否则返回 False
|
||||
"""
|
||||
if not value:
|
||||
return True
|
||||
if value != value.strip():
|
||||
return False
|
||||
if any((ord(ch) < 0x20 and ch != "\t") or ord(ch) == 0x7F for ch in value):
|
||||
return False
|
||||
try:
|
||||
value.encode("latin-1")
|
||||
except UnicodeEncodeError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def find_invalid_http_header_names(headers: Optional[Mapping[str, object]]) -> list[str]:
|
||||
"""
|
||||
返回请求头映射中取值非法的字段名称,不暴露可能包含凭据的字段值。
|
||||
|
||||
:param headers: 待检查的请求头映射;None 或空映射返回空列表
|
||||
:return: 取值不符合 HTTP 请求头规范的字段名称列表
|
||||
"""
|
||||
if not headers:
|
||||
return []
|
||||
invalid_names: list[str] = []
|
||||
for key, value in headers.items():
|
||||
if value is None:
|
||||
continue
|
||||
if not isinstance(value, str) or not is_valid_http_header_value(value):
|
||||
invalid_names.append(str(key))
|
||||
return invalid_names
|
||||
|
||||
|
||||
class SiteUtils:
|
||||
"""
|
||||
提供站点域名、Cookie 和访问参数处理能力。
|
||||
|
||||
@@ -488,11 +488,13 @@ class IndexerModule(_ModuleBase):
|
||||
:param site: 包含搜索协议和当前用户配置的站点上下文
|
||||
:return: 专站规则处理后的 User-Agent,普通站点保留当前配置值
|
||||
"""
|
||||
raw_ua = site.get("ua")
|
||||
normalized_ua = raw_ua.strip() if isinstance(raw_ua, str) else raw_ua
|
||||
parser_class = SPIDER_PARSER_CLASSES.get(str(site.get("parser") or ""))
|
||||
get_user_agent = getattr(parser_class, "get_user_agent", None)
|
||||
if callable(get_user_agent):
|
||||
return cast(str, get_user_agent(site.get("ua")))
|
||||
return cast(Optional[str], site.get("ua"))
|
||||
return cast(str, get_user_agent(normalized_ua))
|
||||
return cast(Optional[str], normalized_ua)
|
||||
|
||||
@staticmethod
|
||||
def __parse_result(site: dict[str, Any], result_array: list[dict[str, Any]], seconds: int) -> List[TorrentInfo]:
|
||||
@@ -1316,13 +1318,15 @@ class IndexerModule(_ModuleBase):
|
||||
f"{str(site_url).rstrip('/')}/",
|
||||
userdata_path.lstrip("/"),
|
||||
)
|
||||
raw_ua = site.get("ua")
|
||||
site_ua = raw_ua.strip() if isinstance(raw_ua, str) else ""
|
||||
return site_schema(
|
||||
site_name=site.get("name"),
|
||||
url=site_url,
|
||||
site_cookie=site.get("cookie"),
|
||||
apikey=site.get("apikey"),
|
||||
token=site.get("token"),
|
||||
ua=site.get("ua") or get_runtime_setting("USER_AGENT"),
|
||||
ua=site_ua or get_runtime_setting("USER_AGENT"),
|
||||
proxy=site.get("proxy"),
|
||||
api_url=site.get("api_url"))
|
||||
return None
|
||||
|
||||
@@ -12,7 +12,7 @@ from urllib.parse import urljoin, urlsplit
|
||||
|
||||
from app.adapters.network.cloudflare import under_challenge
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.domain.site import SiteUtils
|
||||
from app.domain.site import SiteUtils, find_invalid_http_header_names
|
||||
from app.foundation import size as size_tools
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
@@ -128,7 +128,7 @@ class SiteParserBase(metaclass=ABCMeta):
|
||||
self._site_cookie = site_cookie
|
||||
self._api_url = api_url
|
||||
self._request_utils = request_utils or RequestUtils(use_session=True)
|
||||
self._ua = ua
|
||||
self._ua = ua.strip() if isinstance(ua, str) else ua
|
||||
self._emulate = emulate
|
||||
self._proxy = proxy
|
||||
self._index_html: SitePage = ""
|
||||
@@ -431,6 +431,17 @@ class SiteParserBase(metaclass=ABCMeta):
|
||||
if self._addition_headers:
|
||||
req_headers.update(self._addition_headers)
|
||||
|
||||
invalid_headers = find_invalid_http_header_names(req_headers)
|
||||
if invalid_headers:
|
||||
fields = ", ".join(invalid_headers)
|
||||
self.err_msg = f"请求头包含非法字符({fields}),请检查站点 UA 或认证配置"
|
||||
# 请求头构造阶段即非法,更换其他解析模型无法恢复,跳过无意义的回退探测。
|
||||
self.allow_schema_fallback = False
|
||||
logger.warning(
|
||||
f"{self._site_name} 用户数据请求头无效(InvalidHeader),异常字段:{fields}"
|
||||
)
|
||||
return ""
|
||||
|
||||
if self.request_mode == "apikey":
|
||||
# 使用apikey请求,通过请求头传递
|
||||
cookie = None
|
||||
@@ -519,7 +530,8 @@ class SiteParserBase(metaclass=ABCMeta):
|
||||
"""
|
||||
logged_in = SiteUtils.is_logged_in(html_text)
|
||||
if not logged_in:
|
||||
self.err_msg = "未检测到已登陆,请检查cookies是否过期"
|
||||
if not self.err_msg:
|
||||
self.err_msg = "未检测到已登陆,请检查cookies是否过期"
|
||||
logger.warn(f"{self._site_name} 未登录,跳过后续操作")
|
||||
|
||||
return logged_in
|
||||
|
||||
@@ -304,3 +304,34 @@ def test_legacy_http_module_uses_httpx2_by_default(monkeypatch):
|
||||
|
||||
assert legacy_http.AsyncRequestUtils is AsyncRequestUtils
|
||||
assert isinstance(response, httpx2.Response)
|
||||
|
||||
|
||||
def test_async_invalid_header_logs_field_without_tripping_h2_breaker(monkeypatch):
|
||||
"""
|
||||
异步请求因非法请求头触发 LocalProtocolError 时应记录出错字段,且不得触发代理 h2 熔断。
|
||||
"""
|
||||
warnings: list[str] = []
|
||||
monkeypatch.setattr(http_module.logger, "warning", warnings.append)
|
||||
|
||||
async def fail_invalid_header(_self, _http2, _cookies_dict, _method, _url, _raise_exception, **_kwargs):
|
||||
"""
|
||||
模拟底层协议栈拒绝非法请求头。
|
||||
"""
|
||||
raise httpx2.LocalProtocolError("Illegal header value")
|
||||
|
||||
monkeypatch.setattr(AsyncRequestUtils, "_dispatch_request", fail_invalid_header)
|
||||
|
||||
utils = AsyncRequestUtils(
|
||||
proxies={"https": PROXY},
|
||||
headers={"User-Agent": " Mozilla/5.0", "x-api-key": " secret-api-key\n"},
|
||||
)
|
||||
result = asyncio.run(utils.request("get", "https://site.example/api?token=secret-token"))
|
||||
|
||||
assert result is None
|
||||
assert http_module._h2_proxy_allowed(PROXY, "https://site.example/api?token=secret-token") is True
|
||||
assert len(warnings) == 1
|
||||
assert "LocalProtocolError" in warnings[0]
|
||||
assert "User-Agent" in warnings[0]
|
||||
assert "x-api-key" in warnings[0]
|
||||
assert "secret-api-key" not in warnings[0]
|
||||
assert "secret-token" not in warnings[0]
|
||||
|
||||
@@ -687,3 +687,58 @@ def test_pterclub_headers_reach_http_transport_and_failures_are_visible(monkeypa
|
||||
lambda *_args: "Forbidden")
|
||||
parser._get_page_content(url="https://pterclub.net/", headers=parser._torrent_seeding_headers)
|
||||
assert any("HTTP 403" in warning for warning in warnings)
|
||||
|
||||
|
||||
def test_site_parser_trims_ua_and_reports_invalid_header_without_fallback(monkeypatch):
|
||||
"""
|
||||
站点解析器应裁剪历史 UA 首尾空格;若仍含非法字符,应明确告警、保留错误说明并停止模型回退。
|
||||
"""
|
||||
from app.modules.indexer import IndexerModule
|
||||
from app.modules.indexer.parser import SiteSchema
|
||||
from app.modules.indexer.parser.nexus_php import NexusPhpSiteUserInfo
|
||||
|
||||
trimmed_parser = NexusPhpSiteUserInfo(
|
||||
site_name="憨憨",
|
||||
url="https://hhan.test/",
|
||||
site_cookie="sid=1",
|
||||
apikey=None,
|
||||
token=None,
|
||||
ua=" Mozilla/5.0 Edg/158.0.0.0 ",
|
||||
)
|
||||
assert trimmed_parser._ua == "Mozilla/5.0 Edg/158.0.0.0"
|
||||
|
||||
warnings: list[str] = []
|
||||
monkeypatch.setattr("app.modules.indexer.parser.logger.warning", warnings.append)
|
||||
fallback_called: list[str] = []
|
||||
|
||||
class _FallbackParser(NexusPhpSiteUserInfo):
|
||||
"""
|
||||
记录异常请求头场景下是否被错误触发的回退解析器。
|
||||
"""
|
||||
|
||||
schema = SiteSchema.Gazelle
|
||||
|
||||
def parse(self) -> None:
|
||||
"""
|
||||
记录回退解析器的调用次数。
|
||||
"""
|
||||
fallback_called.append("Gazelle")
|
||||
|
||||
monkeypatch.setattr(IndexerModule, "_site_schemas", [NexusPhpSiteUserInfo, _FallbackParser])
|
||||
module = object.__new__(IndexerModule)
|
||||
result = module.refresh_userdata(
|
||||
{
|
||||
"name": "憨憨",
|
||||
"url": "https://hhan.test/",
|
||||
"cookie": "sid=1",
|
||||
"ua": "Mozilla/5.0\nBadUA",
|
||||
"schema": SiteSchema.NexusPhp.value,
|
||||
"public": False,
|
||||
}
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result.userid is None
|
||||
assert result.err_msg == "请求头包含非法字符(User-Agent),请检查站点 UA 或认证配置"
|
||||
assert fallback_called == []
|
||||
assert any("InvalidHeader" in warning and "User-Agent" in warning for warning in warnings)
|
||||
|
||||
@@ -309,3 +309,61 @@ def test_cookie_parse_preserves_percent_encoded_signature_values(monkeypatch) ->
|
||||
{"name": "userid", "value": "123"},
|
||||
]
|
||||
assert prepared_requests[0].headers["Cookie"] == raw_cookie
|
||||
|
||||
|
||||
def test_request_utils_trims_user_agent_for_sync_and_async_clients() -> None:
|
||||
"""
|
||||
同步与异步客户端构造时应裁剪 UA 首尾空白,兼容历史脏数据。
|
||||
"""
|
||||
sync_client = RequestUtils(ua=" Mozilla/5.0 Edg/158.0.0.0 ")
|
||||
async_client = AsyncRequestUtils(ua=" Mozilla/5.0 Edg/158.0.0.0 ")
|
||||
|
||||
assert sync_client._headers["User-Agent"] == "Mozilla/5.0 Edg/158.0.0.0"
|
||||
assert async_client._headers["User-Agent"] == "Mozilla/5.0 Edg/158.0.0.0"
|
||||
|
||||
|
||||
def test_request_utils_logs_invalid_header_field_without_leaking_values(monkeypatch) -> None:
|
||||
"""
|
||||
请求头触发 InvalidHeader 时必须记录异常类型和出错字段,且不泄露凭据值或查询参数。
|
||||
"""
|
||||
warnings: list[str] = []
|
||||
monkeypatch.setattr(http_module.logger, "warning", warnings.append)
|
||||
|
||||
session = requests.Session()
|
||||
result = RequestUtils(
|
||||
session=session,
|
||||
headers={
|
||||
"User-Agent": " Mozilla/5.0 Edg/158.0.0.0",
|
||||
"Authorization": "Bearer super-secret\nvalue",
|
||||
},
|
||||
).get_res("https://site.example/index.php?passkey=secret-passkey")
|
||||
|
||||
assert result is None
|
||||
assert len(warnings) == 1
|
||||
assert "InvalidHeader" in warnings[0]
|
||||
assert "User-Agent" in warnings[0]
|
||||
assert "Authorization" in warnings[0]
|
||||
assert "https://site.example" in warnings[0]
|
||||
assert "super-secret" not in warnings[0]
|
||||
assert "secret-passkey" not in warnings[0]
|
||||
|
||||
|
||||
def test_request_utils_invalid_header_raises_without_duplicate_warning(monkeypatch) -> None:
|
||||
"""
|
||||
调用方显式要求抛出异常时应传播 InvalidHeader,不额外重复告警。
|
||||
"""
|
||||
warnings: list[str] = []
|
||||
monkeypatch.setattr(http_module.logger, "warning", warnings.append)
|
||||
|
||||
session = requests.Session()
|
||||
try:
|
||||
RequestUtils(
|
||||
session=session,
|
||||
headers={"User-Agent": " Mozilla/5.0"},
|
||||
).get_res("https://site.example/", raise_exception=True)
|
||||
except requests.exceptions.InvalidHeader:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("开启 raise_exception 时应抛出 InvalidHeader")
|
||||
|
||||
assert warnings == []
|
||||
|
||||
@@ -701,3 +701,60 @@ def test_favicon_failure_logs_only_site_origin(monkeypatch) -> None:
|
||||
assert favicon_url == "https://site.test/icon.png?token=secret"
|
||||
assert content is None
|
||||
assert errors == ["获取站点图标失败:https://site.test"]
|
||||
|
||||
|
||||
def test_site_connectivity_trims_legacy_whitespace_ua_and_falls_back_when_blank() -> None:
|
||||
"""
|
||||
历史配置中带首尾空格或全空白的站点 UA 在连通性测试时应自动裁剪或回退默认 UA。
|
||||
"""
|
||||
http = _FakeHttpPort(_FakeResponse(200, text="ok"), _FakeResponse(200, text="ok"))
|
||||
_configure(http)
|
||||
padded_site = SiteSnapshot(
|
||||
id=1,
|
||||
name="空格UA站",
|
||||
domain="padded.test",
|
||||
url="https://padded.test/",
|
||||
ua=" Mozilla/5.0 Edg/158.0.0.0 ",
|
||||
public=True,
|
||||
)
|
||||
blank_site = SiteSnapshot(
|
||||
id=2,
|
||||
name="空白UA站",
|
||||
domain="blank.test",
|
||||
url="https://blank.test/",
|
||||
ua=" ",
|
||||
public=True,
|
||||
)
|
||||
|
||||
assert _chain()._SiteChain__test(padded_site)[0] is True
|
||||
assert _chain()._SiteChain__test(blank_site)[0] is True
|
||||
assert http.calls[0]["ua"] == "Mozilla/5.0 Edg/158.0.0.0"
|
||||
assert http.calls[1]["ua"] == "MoviePilot-Test"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_ua", ["Mozilla/5.0\nInjected", "Mozilla/5.0 中文"])
|
||||
def test_site_connectivity_reports_invalid_ua_instead_of_unreachable(
|
||||
monkeypatch: pytest.MonkeyPatch, bad_ua: str,
|
||||
) -> None:
|
||||
"""
|
||||
UA 含非法字符时应明确提示配置错误并告警,而不是误报无法打开网站。
|
||||
"""
|
||||
http = _FakeHttpPort()
|
||||
_configure(http)
|
||||
warnings: list[str] = []
|
||||
monkeypatch.setattr(site_module.logger, "warning", warnings.append)
|
||||
site = SiteSnapshot(
|
||||
id=3,
|
||||
name="非法UA站",
|
||||
domain="bad-ua.test",
|
||||
url="https://bad-ua.test/",
|
||||
ua=bad_ua,
|
||||
public=True,
|
||||
)
|
||||
|
||||
result = _chain()._SiteChain__test(site)
|
||||
|
||||
assert result == (False, "站点浏览器标识(UA)包含非法字符,请检查配置!")
|
||||
assert http.calls == []
|
||||
assert len(warnings) == 1
|
||||
assert "User-Agent" in warnings[0]
|
||||
|
||||
@@ -4,7 +4,11 @@
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.domain.site import SiteUtils
|
||||
from app.domain.site import (
|
||||
SiteUtils,
|
||||
find_invalid_http_header_names,
|
||||
is_valid_http_header_value,
|
||||
)
|
||||
from app.foundation.dom import DomUtils
|
||||
from app.sdk.string import StringUtils
|
||||
|
||||
@@ -52,3 +56,27 @@ def test_site_checkin_state_is_derived_from_html_markers():
|
||||
assert SiteUtils.is_checkin(pending_html) is False
|
||||
assert SiteUtils.is_checkin(completed_html) is True
|
||||
assert SiteUtils.is_checkin("") is False
|
||||
|
||||
|
||||
def test_http_header_value_validation_rejects_whitespace_controls_and_non_latin1():
|
||||
"""
|
||||
HTTP 请求头纯规则校验应拒绝首尾空白、控制字符及非 Latin-1 文本,并仅返回出错字段名。
|
||||
"""
|
||||
assert is_valid_http_header_value("") is True
|
||||
assert is_valid_http_header_value("Mozilla/5.0 (Windows NT 10.0; Win64; x64)") is True
|
||||
assert is_valid_http_header_value(" Mozilla/5.0") is False
|
||||
assert is_valid_http_header_value("Mozilla/5.0 ") is False
|
||||
assert is_valid_http_header_value("Mozilla/5.0\nBad") is False
|
||||
assert is_valid_http_header_value("Mozilla/5.0\x00Bad") is False
|
||||
assert is_valid_http_header_value("Mozilla/5.0 中文") is False
|
||||
|
||||
assert find_invalid_http_header_names(None) == []
|
||||
assert find_invalid_http_header_names({}) == []
|
||||
assert find_invalid_http_header_names(
|
||||
{
|
||||
"User-Agent": " Mozilla/5.0",
|
||||
"Accept": "text/html",
|
||||
"X-Empty": None,
|
||||
"X-Bad-Type": 123,
|
||||
}
|
||||
) == ["User-Agent", "X-Bad-Type"]
|
||||
|
||||
@@ -205,3 +205,67 @@ async def test_update_priorities_uses_one_transaction():
|
||||
)
|
||||
)
|
||||
dependencies["unit_of_work"].commit.assert_awaited_once_with()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_site_mutations_trim_header_and_credential_whitespace():
|
||||
"""
|
||||
新增、更新与浏览器 Cookie 保存应裁剪 UA、Cookie、RSS、API Key 和 Token 首尾空白,并保留过滤规则原样。
|
||||
"""
|
||||
site = SimpleNamespace(
|
||||
domain="demo.example",
|
||||
name="Demo",
|
||||
url="https://demo.example/",
|
||||
)
|
||||
repository = Mock()
|
||||
repository.get_by_id = AsyncMock(return_value=site)
|
||||
repository.async_get_by_domain = AsyncMock(return_value=None)
|
||||
repository.stage_create = AsyncMock()
|
||||
repository.stage_update = AsyncMock(return_value=True)
|
||||
command, _ = _command(
|
||||
repository=repository,
|
||||
domain_extractor=lambda value: value.split("://", 1)[1].split("/", 1)[0],
|
||||
url_normalizer=lambda value: f"{value.rstrip('/')}/",
|
||||
)
|
||||
|
||||
create_result = await command.create(
|
||||
{
|
||||
"url": " https://demo.example/path ",
|
||||
"ua": " Mozilla/5.0 Edg/158.0.0.0 ",
|
||||
"cookie": " sid=1; uid=2 ",
|
||||
"rss": " https://demo.example/rss ",
|
||||
"apikey": " secret-key ",
|
||||
"token": " secret-token ",
|
||||
"filter": " 1080p ",
|
||||
}
|
||||
)
|
||||
assert create_result.success is True
|
||||
created = repository.stage_create.await_args.args[0]
|
||||
assert created.values["url"] == "https://demo.example/path/"
|
||||
assert created.values["ua"] == "Mozilla/5.0 Edg/158.0.0.0"
|
||||
assert created.values["cookie"] == "sid=1; uid=2"
|
||||
assert created.values["rss"] == "https://demo.example/rss"
|
||||
assert created.values["apikey"] == "secret-key"
|
||||
assert created.values["token"] == "secret-token"
|
||||
assert created.values["filter"] == " 1080p "
|
||||
|
||||
update_result = await command.update(
|
||||
{
|
||||
"id": 7,
|
||||
"url": " https://demo.example ",
|
||||
"ua": "\tMozilla/5.0 Chrome/130.0\n",
|
||||
"cookie": " sid=updated ",
|
||||
"filter": " REMUX ",
|
||||
}
|
||||
)
|
||||
assert update_result.success is True
|
||||
updated = repository.stage_update.await_args_list[0].args[1]
|
||||
assert updated.values["url"] == "https://demo.example/"
|
||||
assert updated.values["ua"] == "Mozilla/5.0 Chrome/130.0"
|
||||
assert updated.values["cookie"] == "sid=updated"
|
||||
assert updated.values["filter"] == " REMUX "
|
||||
|
||||
cookie_result = await command.set_cookie(7, " sid=browser ", " Browser UA ")
|
||||
assert cookie_result.success is True
|
||||
cookie_mutation = repository.stage_update.await_args_list[1].args[1]
|
||||
assert cookie_mutation.values == {"cookie": "sid=browser", "ua": "Browser UA"}
|
||||
|
||||
@@ -308,3 +308,17 @@ def test_rss_oper_leaves_transaction_to_caller(db) -> None:
|
||||
|
||||
saved = _transactional_repository().get(record.id)
|
||||
assert saved is not None and saved.rss is None
|
||||
|
||||
|
||||
def test_update_cookie_trims_surrounding_whitespace(db) -> None:
|
||||
"""
|
||||
通过站点仓储更新 Cookie 时应裁剪首尾空白,避免带入非法请求头空格。
|
||||
"""
|
||||
db.add(Site(name="Cookie裁剪", domain="cookie-trim.example", url="https://cookie-trim.example/"))
|
||||
repository = _transactional_repository()
|
||||
|
||||
result = repository.update_cookie("cookie-trim.example", " sid=abc; uid=1 \n")
|
||||
|
||||
assert result.success is True
|
||||
saved = repository.get_by_domain("cookie-trim.example")
|
||||
assert saved is not None and saved.cookie == "sid=abc; uid=1"
|
||||
|
||||
Reference in New Issue
Block a user