refactor(url): centralize HTTP URL validation in UrlUtils

This commit is contained in:
InfinityPacer
2026-09-09 17:30:03 +08:00
parent a13d13aeba
commit b6fe6998eb
8 changed files with 78 additions and 34 deletions

View File

@@ -6,6 +6,7 @@ import dateutil.parser
from lxml import etree
from app.application.configuration import get_chain_runtime_config_snapshot
from app.foundation.url import UrlUtils
from app.runtime.log import logger
@@ -304,30 +305,6 @@ class RssHelper:
parts = hostname.split(".")
return ".".join(parts[-2:]) if len(parts) >= 2 else hostname
@staticmethod
def normalize_url(url: Any) -> Optional[str]:
"""校验并规范化 RSS HTTP 地址,保留合法地址中的 fragment。"""
if not isinstance(url, str):
return None
normalized_url = url.strip()
if not normalized_url:
return None
if any(character.isspace() for character in normalized_url):
return None
try:
parsed_url = urlparse(normalized_url)
hostname = parsed_url.hostname
port = parsed_url.port
except ValueError:
return None
if (
parsed_url.scheme.lower() not in ("http", "https")
or not hostname
or (port is not None and not 0 <= port <= 65535)
):
return None
return normalized_url
@staticmethod
def _parse_publish_time(value: str):
"""将 RSS 常见日期表达解析为 datetime,无法解析时返回 None。"""
@@ -356,6 +333,9 @@ class RssHelper:
def parse(self, url, proxy: bool = False,
timeout: Optional[int] = 15, headers: dict = None, ua: str = None) -> Union[List[dict], None, bool]:
"""解析 RSS 地址并保留插件兼容的返回约定。"""
url = UrlUtils.normalize_http_url(url)
if url is None:
return False
return self._parse_impl(url, proxy=proxy, timeout=timeout, headers=headers, ua=ua)
def _parse_impl(self, url, proxy: bool = False,
@@ -372,11 +352,6 @@ class RssHelper:
"""
# 开始处理
ret_array: list = []
normalized_url = self.normalize_url(url)
if normalized_url is None:
return False
url = normalized_url
http_port, _, _ = _require_rss_ports()
try:

View File

@@ -14,6 +14,7 @@ from app.domain.context import Context, MediaInfo, MusicInfo, TorrentInfo
from app.domain.meta.metabase import MetaBase
from app.domain.meta.metamusic import MetaMusic
from app.domain.metainfo import MetaInfo
from app.foundation.url import UrlUtils
from app.runtime.log import logger
from app.runtime.stop import runtime_stop_state
from app.schemas.media import resolve_media_identity
@@ -318,7 +319,7 @@ class TorrentsChain(ChainBase):
if not site:
logger.error(f'站点 {domain} 不存在!')
return []
rss_url = RssHelper.normalize_url(site.get("rss"))
rss_url = UrlUtils.normalize_http_url(site.get("rss"))
if rss_url is None:
logger.warning(f'站点 {domain} RSS地址无效,跳过获取')
return []

View File

@@ -8,6 +8,34 @@ from urllib.parse import parse_qs, urlencode, urljoin, urlparse, urlunparse
class UrlUtils:
"""提供不发起网络请求的 URL 解析与组合能力。"""
@staticmethod
def normalize_http_url(url: object) -> Optional[str]:
"""校验绝对 HTTP(S) 地址,无效输入返回 None。
仅去除首尾空白,不补协议或重写路径、查询串和 fragment,避免改变地址语义。
此处只检查地址格式,不保证远端可访问或响应内容有效。
"""
if not isinstance(url, str):
return None
normalized_url = url.strip()
if not normalized_url:
return None
if any(character.isspace() for character in normalized_url):
return None
try:
parsed_url = urlparse(normalized_url)
hostname = parsed_url.hostname
port = parsed_url.port
except ValueError:
return None
if (
parsed_url.scheme.lower() not in ("http", "https")
or not hostname
or (port is not None and not 0 <= port <= 65535)
):
return None
return normalized_url
@staticmethod
def standardize_base_url(host: str) -> str:
"""

View File

@@ -755,7 +755,7 @@ flowchart LR
| 指标 | 当前值 |
|---|---:|
| Python 模块 | 986 |
| 内部导入边 | 8,380 |
| 内部导入边 | 8,384 |
| 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) |
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
| Direct egress | 53(债务已清零,53 条精确 containment) |

View File

@@ -94,7 +94,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁
| 指标 | 当前值 | 解释 |
|---|---:|---|
| 宿主 Python 模块 / 内部依赖边 | 986 / 8,380 | `dependency-baseline.json` 当前快照;分类、下载资源归类、订阅搜索与整理任务恢复模块的受控依赖 |
| 宿主 Python 模块 / 内部依赖边 | 986 / 8,384 | `dependency-baseline.json` 当前快照;分类、下载资源归类、订阅搜索与整理任务恢复模块的受控依赖 |
| 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 |
| 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 |
| Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 |

View File

@@ -338,6 +338,11 @@ site extension owns the configured catalog/authentication/index capability and
lives in `app/application/site/`; only its download and file installation
mechanism remains in `app/adapters/system/resource.py`.
HTTP(S) 地址的无 I/O 格式校验归属 `app/foundation/url.py` 的
`UrlUtils.normalize_http_url()`,只去除首尾空白,不补协议或改写地址。
RSS 用例在入口调用该能力,并拥有无效地址的跳过行为与返回约定;
Foundation 不承担 RSS 内容判断、站点续期或运行日志职责。
可选的进程级技术资源使用 Managed Resource 合同:实现及其 data-only
`capability.toml` 与适配器同目录,`runtime/extensions` 只解释通用的同步/异步
`start`、`stop` 生命周期,`startup` 负责构建 Capability Runtime。声明必须使用

View File

@@ -1074,8 +1074,8 @@
"runtime_only": true
}
},
"edge_count": 8380,
"edge_sha256": "85f2c071926270095a086e1358127133b8201742690c6694c2b75d504a304e26",
"edge_count": 8384,
"edge_sha256": "c88056aac8684ffe28e7bb8eac494d9a8218f98ce120ff58b4aa7d8c7f88c9fd",
"edges": [
"app -> app.foundation",
"app -> app.foundation.environment",
@@ -3527,6 +3527,8 @@
"app.application.recognition -> app.schemas.types",
"app.application.rss -> app.application",
"app.application.rss -> app.application.configuration",
"app.application.rss -> app.foundation",
"app.application.rss -> app.foundation.url",
"app.application.rss -> app.runtime",
"app.application.rss -> app.runtime.log",
"app.application.rules -> app.application",
@@ -5012,6 +5014,8 @@
"app.chain.torrents -> app.domain.meta.metamusic",
"app.chain.torrents -> app.domain.metainfo",
"app.chain.torrents -> app.domain.site",
"app.chain.torrents -> app.foundation",
"app.chain.torrents -> app.foundation.url",
"app.chain.torrents -> app.runtime",
"app.chain.torrents -> app.runtime.log",
"app.chain.torrents -> app.runtime.stop",

31
tests/test_url_utils.py Normal file
View File

@@ -0,0 +1,31 @@
import pytest
from app.foundation.url import UrlUtils
@pytest.mark.parametrize(
"url",
[None, 123, b"https://example.com/rss", "", " ", "#", "#fragment",
"/rss", "example.com/rss", "//example.com/rss", "ftp://example.com/rss",
"https:///rss", "https://", "https://bad host/rss", "https://example.com/a\nb",
"https://example.com:abc/rss", "https://example.com:65536/rss",
"https://example.com:-1/rss", "http://[::1/rss"],
)
def test_normalize_http_url_rejects_invalid_input(url):
assert UrlUtils.normalize_http_url(url) is None
@pytest.mark.parametrize(
"url",
["http://example.com", "https://example.com/rss", "HTTPS://Example.com/Rss",
"http://localhost:0/rss", "https://example.com:65535/rss",
"http://[::1]:8080/rss", "https://example.com/a%20b?key=a%2Fb&x=1&x=2#item"],
)
def test_normalize_http_url_preserves_address_except_outer_whitespace(url):
assert UrlUtils.normalize_http_url(f" \t{url}\r\n") == url
assert UrlUtils.normalize_http_url(url) == url
def test_standardize_base_url_keeps_permissive_contract():
assert UrlUtils.standardize_base_url("example.com") == "http://example.com/"
assert UrlUtils.normalize_http_url("example.com") is None