Merge pull request #7465 from jxxghp/fix/issue-7460-site-diagnostics

fix(site): separate connectivity and user authentication
This commit is contained in:
jxxghp
2026-11-19 01:22:17 +08:00
committed by GitHub
13 changed files with 252 additions and 17 deletions

View File

@@ -75,7 +75,10 @@ OPERATION_DESCRIPTIONS = {
"site.cookie.update": "登录一个站点并刷新保存的认证 Cookie。",
"site.cookie.set": "为一个站点保存浏览器取得的认证 Cookie 和可选 User-Agent,保留其他设置。",
"site.list": "按状态和名称筛选已配置站点;认证字段仅向超级管理员返回。",
"site.test": "测试一个已配置站点的连通性和认证状态。",
"site.test": (
"测试站点连通性和适配器支持的登录状态;通用网页检测仅检查页面和 Cookie,"
"不校验独立的用户认证接口,不能据此判断 UID、Passkey 等用户认证参数有效。"
),
"site.update": "更新一个已配置站点的完整设置。",
"site.userdata": "读取最近采集的指定站点账号统计。",
"slash.list": "列出智能体可分发的斜杠命令。",

View File

@@ -12853,7 +12853,7 @@
},
{
"additionalProperties": false,
"description": "测试一个已配置站点的连通性和认证状态。请求方法:GET;路径:/api/v1/site/test/{site_id}。操作效果:safe_read;身份范围:bound_user。所需角色:user。",
"description": "测试站点连通性和适配器支持的登录状态;通用网页检测仅检查页面和 Cookie,不校验独立的用户认证接口,不能据此判断 UID、Passkey 等用户认证参数有效。请求方法:GET;路径:/api/v1/site/test/{site_id}。操作效果:safe_read;身份范围:bound_user。所需角色:user。",
"properties": {
"operation_id": {
"const": "site.test",
@@ -12862,7 +12862,7 @@
},
"path_params": {
"additionalProperties": false,
"description": "site.test 的资源标识参数。测试一个已配置站点的连通性和认证状态。仅使用下列已声明字段。",
"description": "site.test 的资源标识参数。测试站点连通性和适配器支持的登录状态;通用网页检测仅检查页面和 Cookie,不校验独立的用户认证接口,不能据此判断 UID、Passkey 等用户认证参数有效。仅使用下列已声明字段。",
"properties": {
"site_id": {
"description": "site.list 返回的持久化站点标识。",

View File

@@ -620,7 +620,9 @@ def test_site(
_: _SchemaTokenPayload = Depends(verify_token),
) -> Any:
"""
测试站点是否可用
检查站点连通性及适配器支持的登录状态。
通用检测只检查网页和 Cookie;此接口不验证用户认证页保存的 UID、Passkey 等参数。
"""
site = query.get_sync(site_id)
if not site:
@@ -861,6 +863,8 @@ def auth_site(
auth_info.params,
sites_helper.get_authsites(),
)
if not auth_params:
return _SchemaResponse(success=False, message="请输入认证站点和认证参数")
status, msg = sites_helper.check_user(auth_info.site, auth_params)
if status:
get_configured_system_config().set(

View File

@@ -31,8 +31,8 @@ def normalize_site_auth_params(
把站点字段名规范化为认证资源使用的站点前缀键名。
认证资源的公共认证入口按 ``SITE_PARAMETER`` 读取参数,但旧版 API、
CLI 配置和外部调用方可能提交资源清单中的原始字段名。保留未知字段,
只将已知站点字段转换为资源契约键名。
CLI 配置和外部调用方可能提交资源清单中的原始字段名。移除其他认证站点的
前缀字段,避免切换表单后继续保存旧凭据;未知扩展字段仍保持兼容。
"""
normalized = dict(params or {})
if not site or not params or not isinstance(auth_sites, Mapping):
@@ -45,6 +45,13 @@ def normalize_site_auth_params(
if not isinstance(param_definitions, Mapping):
return normalized
other_prefixes = tuple(
f"{auth_site.upper()}_" for auth_site in auth_sites if auth_site != site
)
normalized = {
key: value for key, value in normalized.items()
if not key.startswith(other_prefixes)
}
for raw_key in param_definitions:
if not isinstance(raw_key, str):
continue

View File

@@ -743,10 +743,13 @@ class SiteChain(InteractionChainMixin, ChainBase):
def test(self, url: str) -> Tuple[bool, str]:
"""
测试站点是否可用
测试站点连通性,并在适配器支持时检查对应的认证接口。
通用网页检测会检查页面可达性和已保存 Cookie 的登录状态,但不会验证独立的
UID、Passkey 或 API Key 认证参数。
:param url: 站点域名
:return: (是否可用, 错误信息)
:return: 检测是否通过及对应的范围或失败原因
"""
domain = site_domain(url)
repository = self.site_repository
@@ -803,6 +806,8 @@ class SiteChain(InteractionChainMixin, ChainBase):
proxies=proxy_server,
timeout=timeout,
) or ""
if not page_source:
return False, "无法打开网站!"
if not public and not SiteUtils.is_logged_in(page_source):
if ports.challenge.detected(page_source):
return False, "无法通过Cloudflare!"
@@ -814,8 +819,9 @@ class SiteChain(InteractionChainMixin, ChainBase):
cookie=site_cookie,
ua=ua,
proxies=proxies,
timeout=timeout,
) as res:
if res and res.status_code in [200, 500, 403]:
if res is not None and res.status_code in [200, 500, 403]:
content = res.text
if not public and not SiteUtils.is_logged_in(content):
if _site_ports_snapshot().challenge.detected(content):
@@ -825,13 +831,13 @@ class SiteChain(InteractionChainMixin, ChainBase):
else:
msg = f"错误:{res.status_code} {res.reason}"
return False, f"{msg}!"
if public and res.status_code != 200:
if res.status_code != 200:
return False, f"错误:{res.status_code} {res.reason}!"
elif res is not None:
return False, f"错误:{res.status_code} {res.reason}!"
else:
return False, "无法打开网站!"
return True, "连接成功"
return True, "网页可访问(按站点设置检查登录状态,未验证用户认证接口)"
def _interaction_handler(self) -> "SiteInteractionHandler":
"""

View File

@@ -400,6 +400,19 @@
"无法打开网站!": "Unable to open the site!",
"无法获取Token": "Unable to get token",
"连接成功": "Connection successful",
"网页可访问(按站点设置检查登录状态,未验证用户认证接口)": "Page reachable (login checked according to site settings; user-authentication endpoint not verified)",
"请求超时": "Request timed out",
"DNS 解析失败": "DNS resolution failed",
"代理连接失败": "Proxy connection failed",
"TLS 连接失败": "TLS connection failed",
"网络连接失败": "Network connection failed",
"认证请求失败": "Authentication request failed",
"认证接口未收到响应": "No response from the authentication endpoint",
"认证接口返回内容为空": "Authentication endpoint returned an empty response",
"认证接口返回内容与预期不符(不是 JSON 对象)": "Unexpected authentication response (expected a JSON object)",
"认证接口返回内容与预期不符(不是有效 JSON)": "Unexpected authentication response (invalid JSON)",
"认证接口返回内容与预期不符(缺少认证状态)": "Unexpected authentication response (missing authentication status)",
"认证未通过,请检查凭据和站点用户状态!": "Authentication was not approved. Check your credentials and site account status.",
"Cookie已失效": "Cookie has expired",
"鉴权已过期或无效": "Authentication has expired or is invalid",
"Cookie已过期": "Cookie has expired",
@@ -658,6 +671,14 @@
"渠道授权服务不可用": "The channel authorization service is unavailable"
},
"message_patterns": [
{
"source": "认证接口返回 HTTP {status}",
"target": "Authentication endpoint returned HTTP {status}"
},
{
"source": "用户认证出错({error_type})",
"target": "User authentication error ({error_type})"
},
{
"source": "{name} 未能加入整理队列,请稍后重试",
"target": "Could not add {name} to the organization queue. Try again later"

View File

@@ -362,6 +362,19 @@
"无法打开网站!": "無法開啟網站!",
"无法获取Token": "無法取得 Token",
"连接成功": "連線成功",
"网页可访问(按站点设置检查登录状态,未验证用户认证接口)": "網頁可存取(依站點設定檢查登入狀態,未驗證使用者認證介面)",
"请求超时": "請求逾時",
"DNS 解析失败": "DNS 解析失敗",
"代理连接失败": "代理連線失敗",
"TLS 连接失败": "TLS 連線失敗",
"网络连接失败": "網路連線失敗",
"认证请求失败": "認證請求失敗",
"认证接口未收到响应": "認證介面未收到回應",
"认证接口返回内容为空": "認證介面回傳內容為空",
"认证接口返回内容与预期不符(不是 JSON 对象)": "認證介面回傳內容不符預期(不是 JSON 物件)",
"认证接口返回内容与预期不符(不是有效 JSON)": "認證介面回傳內容不符預期(不是有效 JSON)",
"认证接口返回内容与预期不符(缺少认证状态)": "認證介面回傳內容不符預期(缺少認證狀態)",
"认证未通过,请检查凭据和站点用户状态!": "認證未通過,請檢查憑據和站點使用者狀態!",
"Cookie已失效": "Cookie 已失效",
"鉴权已过期或无效": "鑑權已過期或無效",
"Cookie已过期": "Cookie 已過期",
@@ -606,6 +619,14 @@
"渠道授权服务不可用": "渠道授權服務無法使用"
},
"message_patterns": [
{
"source": "认证接口返回 HTTP {status}",
"target": "認證介面回傳 HTTP {status}"
},
{
"source": "用户认证出错({error_type})",
"target": "使用者認證出錯({error_type})"
},
{
"source": "{name} 未能加入整理队列,请稍后重试",
"target": "無法將 {name} 加入整理佇列,請稍後再試"

View File

@@ -251,6 +251,14 @@ Web 影视精确与标题 SSE 的 `manual_paging=true` 模式在最终 `done`
各表单持有独立副本。相关站点、系统设置和订阅写操作成功后,以及登录身份变化后,
快照立即失效,在途旧结果不能写回新会话;失败查询允许重试。
`GET /api/v1/site/test/{site_id}` 检查站点连通性和适配器支持的登录状态。普通站点只检测
网页和 Cookie,成功说明不代表「用户认证」中的 UID、Passkey 等凭据有效;API 站点使用
各自已适配的登录接口。独立的用户认证仍通过 `POST /api/v1/site/auth` 执行,成功保存时清除
切换站点遗留的其他已知站点前缀字段;启动认证也会过滤这些字段,未知扩展参数继续兼容。
过滤后参数为空时直接拒绝请求,避免资源改为读取环境变量并认证其他站点。
认证资源 `3.0.7` 起区分超时、DNS、代理、TLS、HTTP 状态及接口内容异常;请求日志记录
脱敏主机、耗时、HTTP 状态和安全调用位置,不输出请求参数、完整 URL 或原始异常字符串。
`GET /api/v1/site/userdata/{site_id}` 支持 `page` / `count`;趋势界面使用最近 90 条记录,
并传入 `latest_seeding_only=true`,仅窗口内最新记录携带 `seeding_info`,历史统计字段不变。
省略该选项时保留每条记录的完整明细;这不会删除或修改采集历史。

View File

@@ -111,6 +111,11 @@ AppPush 的所有用户范围由 `tests/test_notification_routing_parity.py` 验
- 用例**不得**连接或写入真实数据库、不得读写真实 `config/`。需要的库状态在用例内构造。
- 用例**不得**依赖某个本地才有的动态模块副本;缺失的外部模块由 conftest 兜底或用例自行 mock。
`tests/test_site_auth.py` 验证用户认证参数规范化、切换站点后过滤其他站点前缀、仅持久化成功
配置,以及启动认证的环境变量优先级。`tests/test_site_chain_ports.py` 覆盖错误 HTTP 响应、
Cloudflare、空浏览器页面和通用检测的范围提示;这些检测不会验证用户认证页的 UID 或 Passkey。
认证扩展的传输诊断与各平台 ABI 由 MoviePilot-Build 的离线回放和编译资源验证负责。
## 外部依赖:一律 mock,零真实网络
季集选集由 `tests/test_episode_file_selection.py`、`tests/test_download_batch_phases.py` 和

View File

@@ -157,7 +157,7 @@ Identity scope: `admin`; required role: `system_admin`.
### `site.test`
`GET /api/v1/site/test/{site_id}`; policy effect: `safe_read`.
Purpose: 测试一个已配置站点的连通性和认证状态。
Purpose: 测试站点连通性和适配器支持的登录状态;通用网页检测仅检查页面和 Cookie,不校验独立的用户认证接口,不能据此判断 UID、Passkey 等用户认证参数有效。
Identity scope: `bound_user`; required role: `user`.
- `path_params`: `site_id*` (integer): site.list 返回的持久化站点标识。
- `query`: none

View File

@@ -5,11 +5,14 @@
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from app.api.endpoints import site as site_endpoint
from app.application.site.auth import (
normalize_site_auth_config,
normalize_site_auth_params,
)
from app.runtime.localization import LocaleHelper
from app.scheduler import reconcile as scheduler_reconcile
from app.schemas.site import SiteAuth
from app.schemas.types import SystemConfigKey
@@ -24,6 +27,32 @@ HAIDAN_AUTH_SITES = {
}
}
AUTH_SITES = {
**HAIDAN_AUTH_SITES,
"hdkyl": {"params": {"uid": {"name": "用户ID"}, "passkey": {"name": "密钥"}}},
}
def test_normalization_removes_other_site_credentials_without_mutating_input() -> None:
"""
切换站点遗留的前缀凭据被过滤,当前站点和未知扩展字段继续兼容。
"""
params = {"id": 123, "passkey": "current", "HDKYL_UID": 456, "HDKYL_PASSKEY": "old", "extra": "value"}
original = dict(params)
assert normalize_site_auth_params("haidan", params, AUTH_SITES) == {
"HAIDAN_ID": 123, "HAIDAN_PASSKEY": "current", "extra": "value",
}
assert params == original
@pytest.mark.parametrize("site,params", [(None, None), ("unknown", {"field": "value"})])
def test_unrecognized_auth_configuration_keeps_legacy_parameters(site, params) -> None:
"""
缺失或尚未识别的资源配置不能删除调用方提供的扩展参数。
"""
assert normalize_site_auth_params(site, params, AUTH_SITES) == (params or {})
def test_normalize_site_auth_params_accepts_resource_field_names() -> None:
"""
@@ -73,13 +102,13 @@ def test_auth_site_normalizes_parameters_before_check_and_persist(monkeypatch) -
认证端点应以规范化键名调用资源并只持久化成功配置。
"""
helper = Mock()
helper.get_authsites.return_value = HAIDAN_AUTH_SITES
helper.get_authsites.return_value = AUTH_SITES
helper.check_user.return_value = (True, "haidan")
config = Mock()
_patch_auth_endpoint(monkeypatch, helper, config)
response = site_endpoint.auth_site(
SiteAuth(site="haidan", params={"id": 63632, "passkey": "secret"}),
SiteAuth(site="haidan", params={"id": 63632, "passkey": "secret", "HDKYL_PASSKEY": "old"}),
SimpleNamespace(),
)
@@ -116,6 +145,74 @@ def test_auth_site_does_not_persist_failed_parameters(monkeypatch) -> None:
config.set.assert_not_called()
def test_auth_site_rejects_parameters_belonging_only_to_another_site(monkeypatch) -> None:
"""
过滤后为空时直接拒绝,避免资源把空参数误当成改用环境变量认证。
"""
helper = Mock()
helper.get_authsites.return_value = AUTH_SITES
config = Mock()
_patch_auth_endpoint(monkeypatch, helper, config)
response = site_endpoint.auth_site(
SiteAuth(site="haidan", params={"HDKYL_UID": 456, "HDKYL_PASSKEY": "old"}),
SimpleNamespace(),
)
assert response.success is False
assert response.message == "请输入认证站点和认证参数"
helper.check_user.assert_not_called()
config.set.assert_not_called()
@pytest.mark.parametrize("locale,message,expected", [
("en-US", "请求超时", "Request timed out"),
("en-US", "认证接口返回 HTTP 403", "Authentication endpoint returned HTTP 403"),
("en-US", "用户认证出错(RuntimeError)", "User authentication error (RuntimeError)"),
("zh-TW", "请求超时", "請求逾時"),
("zh-TW", "认证接口返回 HTTP 403", "認證介面回傳 HTTP 403"),
("zh-TW", "用户认证出错(RuntimeError)", "使用者認證出錯(RuntimeError)"),
])
def test_auth_failure_response_keeps_the_requested_language(monkeypatch, locale, message, expected) -> None:
"""
认证资源的新诊断通过真实 API 响应本地化,不让前端原样显示中文 fallback。
"""
helper = Mock()
helper.get_authsites.return_value = HAIDAN_AUTH_SITES
helper.check_user.return_value = (False, message)
_patch_auth_endpoint(monkeypatch, helper, Mock())
token = LocaleHelper.set_current_locale(locale)
try:
response = site_endpoint.auth_site(SiteAuth(site="haidan", params={"id": 123}), SimpleNamespace())
finally:
LocaleHelper.reset_current_locale(token)
assert response.message == expected
assert response.success is False
@pytest.mark.parametrize("locale,expected", [
("en-US", "Page reachable (login checked according to site settings; user-authentication endpoint not verified)"),
("zh-TW", "網頁可存取(依站點設定檢查登入狀態,未驗證使用者認證介面)"),
])
def test_connectivity_scope_response_keeps_the_requested_language(monkeypatch, locale, expected) -> None:
"""
站点测试成功的范围说明经过 API 翻译后再由前端展示。
"""
chain = Mock()
chain.test.return_value = (True, "网页可访问(按站点设置检查登录状态,未验证用户认证接口)")
monkeypatch.setattr(site_endpoint, "SiteChain", Mock(return_value=chain))
query = Mock(get_sync=Mock(return_value=SimpleNamespace(domain="site.test")))
token = LocaleHelper.set_current_locale(locale)
try:
response = site_endpoint.test_site(1, query=query)
finally:
LocaleHelper.reset_current_locale(token)
assert response.message == expected
assert response.success is True
def test_startup_auth_prefers_environment_configuration(monkeypatch) -> None:
"""
设置环境变量时启动认证应从环境读取,而不是使用旧持久化配置。
@@ -143,6 +240,30 @@ def test_startup_auth_prefers_environment_configuration(monkeypatch) -> None:
helper.check_user.assert_called_once_with()
def test_startup_auth_filters_other_site_credentials_in_saved_configuration(monkeypatch) -> None:
"""
启动时只按保存的站点认证,混存的其他站点前缀不能进入资源调用。
"""
helper = Mock(auth_level=1)
helper.get_authsites.return_value = AUTH_SITES
helper.check_user.return_value = (False, "请求超时")
config = Mock()
config.get.return_value = {
"site": "haidan",
"params": {"id": 123, "passkey": "current", "HDKYL_UID": 456, "HDKYL_PASSKEY": "old"},
}
monkeypatch.setattr(module_initializer, "SitesHelper", Mock(return_value=helper))
monkeypatch.setattr(module_initializer, "get_configured_system_config", Mock(return_value=config))
monkeypatch.setattr(module_initializer, "get_runtime_setting", lambda _key: "")
module_initializer.user_auth()
helper.check_user.assert_called_once_with(
site="haidan", params={"HAIDAN_ID": 123, "HAIDAN_PASSKEY": "current"},
)
config.set.assert_not_called()
def test_scheduler_auth_prefers_environment_configuration(monkeypatch) -> None:
"""
定时认证应与启动认证使用相同的环境变量优先级。

View File

@@ -213,7 +213,7 @@ def test_unconfigured_site_port_fails_without_implicit_adapter() -> None:
[
(None, (False, "无法打开网站!")),
(_FakeResponse(429, reason="rate"), (False, "错误:429 rate!")),
(_FakeResponse(200, text="ok"), (True, "连接成功")),
(_FakeResponse(200, text="ok"), (True, "网页可访问(按站点设置检查登录状态,未验证用户认证接口)")),
],
)
def test_http_port_preserves_failure_tristate_and_closes_response(
@@ -230,6 +230,7 @@ def test_http_port_preserves_failure_tristate_and_closes_response(
assert result == expected
assert http.closed == 1
assert http.calls[0]["url"] == "https://port.test/"
assert http.calls[0]["timeout"] == 60
def test_browser_and_challenge_ports_keep_render_failure_semantics() -> None:
@@ -255,6 +256,44 @@ def test_browser_and_challenge_ports_keep_render_failure_semantics() -> None:
assert browser.calls[0]["url"] == "https://protected.test/"
@pytest.mark.parametrize("status_code", [403, 500])
def test_private_site_error_response_cannot_pass_with_login_markers(status_code: int) -> None:
"""
HTTP 失败页即使带有退出链接,也不能记录为站点连接成功。
"""
http = _FakeHttpPort(_FakeResponse(status_code, text='<a href="logout.php">退出</a>'))
_configure(http)
site = SiteSnapshot(id=2, name="测试站点", domain="port.test", url="https://port.test/")
assert _chain()._SiteChain__test(site) == (False, f"错误:{status_code} OK!")
assert http.closed == 1
def test_falsey_http_403_response_keeps_cloudflare_diagnosis() -> None:
"""
requests 的错误响应为假值时,仍能从 403 正文识别 Cloudflare。
"""
challenge = _FakeChallengePort(True)
http = _FakeHttpPort(_FakeResponse(403, text="challenge"))
_configure(http, challenge=challenge)
site = SiteSnapshot(id=2, name="测试站点", domain="port.test", url="https://port.test/")
assert _chain()._SiteChain__test(site) == (False, "站点被Cloudflare防护,请打开站点浏览器仿真!")
assert challenge.calls == ["challenge"]
assert http.closed == 1
@pytest.mark.parametrize("source", [None, ""])
def test_empty_browser_result_cannot_pass_for_a_public_site(source: Optional[str]) -> None:
"""
公开站点未取得浏览器页面时应失败,不能跳过登录判断后直接报成功。
"""
browser = _FakeBrowserPort(source)
_configure(_FakeHttpPort(), browser=browser)
assert _chain()._SiteChain__test(_public_site(render=True)) == (False, "无法打开网站!")
def test_cookiecloud_failure_uses_fake_port_without_network() -> None:
"""
CookieCloud 下载失败应保持二元返回且只调用注入端口。
@@ -574,7 +613,7 @@ def test_site_connection_keeps_cookie_when_hdwing_redirects_to_https(monkeypatch
id=1, name="瓷器", domain="hdwing.org", url="http://hdwing.org/", cookie="uid=1",
)
assert _chain()._SiteChain__test(site) == (True, "连接成功")
assert _chain()._SiteChain__test(site) == (True, "网页可访问(按站点设置检查登录状态,未验证用户认证接口)")
assert [hop["cookies"] for hop in hops] == ["uid=1", "uid=1"]

View File

@@ -3,7 +3,7 @@
"""
APP_VERSION = 'v3.2.8'
FRONTEND_VERSION = 'v3.2.8'
FRONTEND_VERSION = 'v3.2.9'
# 本版本要求的最低 Docker 镜像系统基线(ISO 日期),与镜像内 /etc/moviepilot/system-baseline 比较。
# 低于该值的镜像拒绝应用内更新,提示用户先更新 Docker 镜像。只在修复严重系统级漏洞时提高,
# 且在同一发布中把 docker/system-baseline 改成相同日期,保证新镜像自身满足要求。