Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix(api): block SSRF in URL source downloads

myhlolid020a553505e
diff --git a/docs/en/usage/tasks.md b/docs/en/usage/tasks.md
index a39981d3..83ccedff 100644
--- a/docs/en/usage/tasks.md
+++ b/docs/en/usage/tasks.md
@@ -154,6 +154,8 @@ PUT raw bytes using the returned `upload.url/headers`; no completion call is req
- Valid hash-based cache hits skip uploads. Only source bytes are reused; each task parses with its own parameters. Concurrent first uploads may transfer duplicate bytes, but source storage is deduplicated.
- URL inputs are downloaded by the server without an upload action, HEAD requirement, or Content-Length requirement. `file_name` determines the format; actual bytes are populated after download and supplied sizes/hashes are checked. URLs are downloaded each time, without hash-based download skipping.
- Local URL sources default to HTTPS only. HTTP requires `--allow-http-source`; defaults are a 60-second download timeout and a 200 MiB size limit. Direct client uploads have no fixed size or PDF page limit, though deployments may impose gateway limits.
+- URL sources must resolve exclusively to public unicast addresses. Workers validate all IPv4/IPv6 results and connect to a validated IP. Private, loopback, link-local, cloud metadata, and special addresses fail the file with `unsupported_source`. Downloads use direct connections and reject redirects. `HTTP_PROXY`, `HTTPS_PROXY`, and `ALL_PROXY` are ignored for URL source downloads. TLS verification honors `SSL_CERT_FILE` / `SSL_CERT_DIR`. Clients can upload documents from internal storage. Externally accessible deployments should configure `--api-key` and restrict worker egress.
+- When using a Fake-IP proxy, configure worker DNS to return actual public addresses. Reserved ranges such as `198.18.0.0/15` are rejected.
- Upload links expire 3600 seconds after creation and are not renewed by polling. Uploads admitted before the deadline may finish; files not yet admitted become `failed/upload_expired`. Processing of successfully uploaded files is not limited by this deadline.
- Do not repeat successful PUTs. Query after a lost response: skip upload for `pending/running/completed`, poll `waiting-file` without an upload object, and retry within bounds only after failure when a valid upload action remains. Expired uploads need a new task. Chunk-level resumable uploads are not supported.
diff --git a/docs/next/cli/mineru-kit-api-server.md b/docs/next/cli/mineru-kit-api-server.md
index c57da6e7..c605fe2c 100644
--- a/docs/next/cli/mineru-kit-api-server.md
+++ b/docs/next/cli/mineru-kit-api-server.md
@@ -221,6 +221,11 @@ Python 可使用 `create_app(vlm_config=VlmConfig(...))` 完整覆盖全局配
本地 api-server 默认监听 loopback。它可以通过 `--api-key` 设置固定 API Key;默认不设置 API Key。设置后,客户端必须发送 `Authorization: Bearer <api-key>`。
+URL 来源仅允许公网单播目标。worker 校验全部 DNS 地址并固定连接已校验的 IP,内网、回环、
+链路本地、云元数据和特殊地址返回逐文件 `unsupported_source` 错误。`--allow-http-source` 仅放行
+公网 HTTP。URL 下载使用直连并拒绝重定向,环境代理对此下载无效,环境 CA 配置继续用于 TLS 校验。
+对外部署应配置 API Key 和 worker 出站限制。内网文档可以通过客户端上传。
+
## 6. API 覆盖范围
`mineru-kit api-server` 目标是实现 v1 API(非 doclib API)中的绝大多数 path。
diff --git a/docs/zh/usage/tasks.md b/docs/zh/usage/tasks.md
index 2e2fc00a..064dbb8d 100644
--- a/docs/zh/usage/tasks.md
+++ b/docs/zh/usage/tasks.md
@@ -642,6 +642,12 @@ TASK_ID=job_... MINERU_API_URL=http://127.0.0.1:8000 \
本地不设固定客户端上传大小或 PDF 页数上限;`usage.limits.max_file_size_bytes/max_pages_per_file` 为 `null`。
URL 下载沿用服务的来源策略:默认 HTTPS;HTTP 需启用 `--allow-http-source`,下载超时默认 60 秒、大小默认 200 MiB。
+URL 目标必须解析为公网单播地址。worker 在连接前校验全部 IPv4/IPv6 地址,并固定连接已校验的 IP。
+内网、回环、链路本地、云元数据及特殊地址会使对应文件以 `unsupported_source` 失败。
+下载使用直连并拒绝重定向。部署中的 `HTTP_PROXY`、`HTTPS_PROXY` 和 `ALL_PROXY` 对 URL 来源下载无效,
+HTTPS 证书校验继续读取 `SSL_CERT_FILE` / `SSL_CERT_DIR`。内网文档可以通过客户端上传。
+使用 Fake-IP 代理时,应让 worker 的 DNS 返回真实公网地址;`198.18.0.0/15` 等保留网段会被拒绝。
+对外提供解析服务时,应配置 `--api-key` 并限制 worker 的出站网络访问。
任务记录和上传索引仍为进程内状态,重启不保证恢复。
Router 按就绪文件独立选择 worker 并预占负载,同一父 Task 可使用多个 worker。
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 43d59807..de226bc8 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -71,6 +71,7 @@ from .page_range import (
)
from .process_control import ManagedProcessControlWatcher
from .server_tiers import model_tier_for_server_tiers, parse_server_tier, resolve_server_tiers
+from .url_source import UrlSourceTransport
from .tier import (
ParserRuntimeOptions,
TierDependencyError,
@@ -1156,7 +1157,9 @@ async def _extract_bytes(
raise ValueError("File has no content")
return _ExtractedSource(file_store.read_blob(sha))
if isinstance(source, _UrlSource):
- async with httpx.AsyncClient(timeout=url_timeout) as cli:
+ async with httpx.AsyncClient(
+ timeout=url_timeout, transport=UrlSourceTransport(), trust_env=False, follow_redirects=False
+ ) as cli:
# 流式读取并在超过 max_url_bytes 时中止,避免无上限响应被整包缓冲进内存。
async with cli.stream("GET", source.url) as r:
r.raise_for_status()
diff --git a/mineru/parser/url_source.py b/mineru/parser/url_source.py
new file mode 100644
index 00000000..ce9c0f78
--- /dev/null
+++ b/mineru/parser/url_source.py
@@ -0,0 +1,100 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""用户提供的 URL 仅直连已校验的公网地址,避免 DNS 重绑定和代理绕过。"""
+
+from __future__ import annotations
+
+import asyncio
+import ipaddress
+import socket
+import time
+
+import httpx
+
+from ..errors import MineruError
+
+# 补齐不同 Python 版本的特殊地址分类,并拒绝可嵌入内网 IPv4 的转换地址。
+_BLOCKED_NETWORKS = (
+ ipaddress.ip_network("192.0.0.0/24"),
+ ipaddress.ip_network("192.88.99.0/24"),
+ ipaddress.ip_network("168.63.129.16/32"), # Azure 平台虚拟地址。
+ ipaddress.ip_network("64:ff9b::/96"),
+ ipaddress.ip_network("64:ff9b:1::/48"),
+ ipaddress.ip_network("2001::/23"),
+ ipaddress.ip_network("2002::/16"),
+)
+
+
+def _public_address(value: str) -> str:
+ """归一化映射地址,只接受公网单播地址并拒绝 IPv6 zone identifier。"""
+ address = ipaddress.ip_address(value)
+ if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
+ address = address.ipv4_mapped
+ if (
+ "%" in value
+ or not address.is_global
+ or address.is_multicast
+ or address.is_reserved
+ or any(address in network for network in _BLOCKED_NETWORKS)
+ ):
+ raise MineruError("unsupported_source", "URL sources must resolve only to public unicast IP addresses")
+ return str(address)
+
+
+async def _resolve_public_addresses(request: httpx.Request) -> list[str]:
+ """在连接超时内解析全部地址,整组校验成功后才允许建立任何连接。"""
+ host = request.url.raw_host.decode("ascii")
+ if "%" in host:
+ raise MineruError("unsupported_source", "URL sources must not contain an IPv6 zone identifier")
+ port = request.url.port if request.url.port is not None else (443 if request.url.scheme == "https" else 80)
+ timeout = request.extensions.get("timeout", {}).get("connect")
+ try:
+ async with asyncio.timeout(timeout):
+ resolved = await asyncio.get_running_loop().getaddrinfo(
+ host, port, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP
+ )
+ except TimeoutError as exc:
+ raise httpx.ConnectTimeout("URL source DNS resolution timed out", request=request) from exc
+ except OSError as exc:
+ raise httpx.ConnectError("URL source DNS resolution failed", request=request) from exc
+ if not resolved:
+ raise httpx.ConnectError("URL source DNS resolution returned no addresses", request=request)
+ return list(dict.fromkeys(_public_address(item[4][0]) for item in resolved))
+
+
+class UrlSourceTransport(httpx.AsyncHTTPTransport):
+ """每次下载固定已校验的目标 IP,Host、SNI 和证书校验仍使用原域名。"""
+
+ def __init__(self) -> None:
+ """直接连接目标并保留环境 CA 配置,关闭跨域名共享 IP 的连接复用。"""
+ super().__init__(trust_env=True, limits=httpx.Limits(max_keepalive_connections=0))
+
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ """验证全部候选地址,再依次连接;仅连接阶段失败时尝试下一地址。"""
+ timeouts = request.extensions.get("timeout", {})
+ timeout = timeouts.get("connect")
+ deadline = time.monotonic() + timeout if timeout is not None else None
+ addresses = await _resolve_public_addresses(request)
+ for index, address in enumerate(addresses):
+ remaining = deadline - time.monotonic() if deadline is not None else None
+ if remaining is not None and remaining <= 0:
+ raise httpx.ConnectTimeout("URL source connection timed out", request=request)
+ pinned = httpx.Request(
+ method=request.method,
+ url=request.url.copy_with(host=address),
+ headers=request.headers,
+ stream=request.stream,
+ extensions={
+ **request.extensions,
+ "sni_hostname": request.url.raw_host.decode("ascii"),
+ "timeout": {**timeouts, "connect": remaining},
+ },
+ )
+ try:
+ return await super().handle_async_request(pinned)
+ except (httpx.ConnectError, httpx.ConnectTimeout):
+ if index == len(addresses) - 1:
+ raise
+ raise httpx.ConnectError("URL source has no reachable public address", request=request)
+
+
+__all__ = ["UrlSourceTransport"]
diff --git a/tests/unittest/test_task_api.py b/tests/unittest/test_task_api.py
index 46635d35..e2f5e58b 100644
--- a/tests/unittest/test_task_api.py
+++ b/tests/unittest/test_task_api.py
@@ -13,7 +13,6 @@ import time
import zipfile
from collections.abc import AsyncIterator, Iterator
from pathlib import Path
-from types import SimpleNamespace
from typing import Any
import httpx
@@ -46,11 +45,11 @@ def url_downloads(monkeypatch: pytest.MonkeyPatch) -> list[httpx.Request]:
headers={"content-type": "text/html; charset=utf-8"},
)
- def download_client(**kwargs: Any) -> httpx.AsyncClient:
- """使用真实 httpx 流式客户端,隔离源站网络而不替换下载业务实现。"""
- return httpx.AsyncClient(transport=httpx.MockTransport(respond), **kwargs)
+ def download_transport() -> httpx.MockTransport:
+ """仅隔离源站传输,保留真实 httpx 客户端和下载业务实现。"""
+ return httpx.MockTransport(respond)
- monkeypatch.setattr(api_server, "httpx", SimpleNamespace(AsyncClient=download_client))
+ monkeypatch.setattr(api_server, "UrlSourceTransport", download_transport)
return requests
@@ -873,11 +872,11 @@ def test_cancel_url_download_closes_stream_and_releases_worker(
"""返回实际异步流,使取消发生在读取源字节期间。"""
return httpx.Response(200, stream=SlowSource(), headers={"content-type": "text/html"})
- def download_client(**kwargs: Any) -> httpx.AsyncClient:
+ def download_transport() -> httpx.MockTransport:
"""仅隔离 URL 来源网络,不改变任务和 Router 的生命周期实现。"""
- return httpx.AsyncClient(transport=httpx.MockTransport(respond), **kwargs)
+ return httpx.MockTransport(respond)
- monkeypatch.setattr(api_server, "httpx", SimpleNamespace(AsyncClient=download_client))
+ monkeypatch.setattr(api_server, "UrlSourceTransport", download_transport)
response = client.post("/v1/tasks", json={"files": [_url_manifest()]})
assert response.status_code == 202
task = response.json()
diff --git a/tests/unittest/test_task_http.py b/tests/unittest/test_task_http.py
index 2f8efe30..a1dcecf6 100644
--- a/tests/unittest/test_task_http.py
+++ b/tests/unittest/test_task_http.py
@@ -32,7 +32,7 @@ from test_http_api_example_script import _Server
from mineru.kit.router import RouterSettings
from mineru.kit.router import create_app as create_router
-from mineru.parser import api_server
+from mineru.parser import api_server, url_source
from mineru.filetypes import batch_effective_parse_tier
from mineru.tasks.contracts import TaskFileInput, UploadTaskOptions
from mineru.tasks.errors import ApiServerError
@@ -535,8 +535,15 @@ def test_real_documents_match_local_parser_outputs(live_service: _LiveService, d
@pytest.mark.parametrize("document", ["html", "pdf"])
-def test_url_task_over_http_downloads_chunked_source(live_service: _LiveService, document: str) -> None:
+def test_url_task_over_http_downloads_chunked_source(
+ live_service: _LiveService, document: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
"""真实 TCP URL 无需 HEAD 或长度头,保留文件页范围且不向源站发送 API Key。"""
+ async def resolve_test_source(request: httpx.Request) -> list[str]:
+ """用本机源站模拟已获准的公网目标;默认阻断策略由 SSRF 专项回归覆盖。"""
+ return ["127.0.0.1"]
+
+ monkeypatch.setattr(url_source, "_resolve_public_addresses", resolve_test_source)
if document == "pdf":
sample = Path(__file__).resolve().parents[2] / "demo" / "pdfs" / "demo1.pdf"
if sample.is_file():
diff --git a/tests/unittest/test_url_source_security.py b/tests/unittest/test_url_source_security.py
new file mode 100644
index 00000000..4e9b9aea
--- /dev/null
+++ b/tests/unittest/test_url_source_security.py
@@ -0,0 +1,290 @@
+"""URL 来源的公网边界、DNS 固定、代理隔离及 API/Router 回显回归。"""
+
+from __future__ import annotations
+
+import asyncio
+import socket
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+from fastapi import FastAPI, Request, Response
+from fastapi.testclient import TestClient
+import test_task_api
+from test_http_api_example_script import _Server
+from test_task_api import _archive, _execution_apps, _terminal
+
+from mineru.errors import MineruError
+from mineru.parser import api_server, url_source
+
+HTML = b"<h1>Public source</h1><p>Validated download content.</p>"
+service = test_task_api.service
+
+
+def dns(monkeypatch: pytest.MonkeyPatch) -> tuple[list[str], list[str]]:
+ """模拟确定的 DNS 应答并记录解析次数,实际地址策略仍由生产代码执行。"""
+ addresses = ["93.184.216.34"]
+ calls: list[str] = []
+
+ async def resolve(
+ self: asyncio.BaseEventLoop, host: str, port: int, **kwargs: Any
+ ) -> list[tuple[int, int, int, str, tuple[str, int]]]:
+ """允许测试混合 A/AAAA、重复地址和 DNS 重绑定后的第二次响应。"""
+ calls.append(host)
+ return [
+ (socket.AF_INET6 if ":" in address else socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (address, port))
+ for address in addresses
+ ]
+
+ monkeypatch.setattr(asyncio.BaseEventLoop, "getaddrinfo", resolve)
+ return addresses, calls
+
+
+def connections(monkeypatch: pytest.MonkeyPatch) -> list[httpx.Request]:
+ """仅替换最底层 HTTP 发送,观察安全传输最终交给网络的目标和 TLS 参数。"""
+ calls: list[httpx.Request] = []
+
+ async def respond(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:
+ """记录已固定的网络请求,并返回可由真实解析器处理的 HTML。"""
+ calls.append(request)
+ return httpx.Response(200, content=HTML, headers={"content-type": "text/html; charset=utf-8"})
+
+ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", respond)
+ return calls
+
+
+ "address",
+ [
+ "127.0.0.1",
+ "10.0.0.1",
+ "172.16.0.1",
+ "192.168.0.1",
+ "169.254.169.254",
+ "169.254.170.2",
+ "100.100.100.200",
+ "0.0.0.0",
+ "192.0.0.8",
+ "192.88.99.1",
+ "192.0.2.1",
+ "198.18.0.1",
+ "224.0.0.1",
+ "240.0.0.1",
+ "255.255.255.255",
+ "168.63.129.16",
+ "::",
+ "::1",
+ "fe80::1",
+ "fd00:ec2::254",
+ "ff02::1",
+ "2001:db8::1",
+ "::ffff:127.0.0.1",
+ "::ffff:169.254.169.254",
+ "64:ff9b::7f00:1",
+ "64:ff9b:1::7f00:1",
+ "2002:7f00:1::",
+ "2001::7f00:1",
+ "2001:4860:4860::8888%eth0",
+ ],
+)
+def test_reject_non_public_addresses(address: str) -> None:
+ """覆盖内网、元数据、IPv4 映射、转换机制和作用域地址的常见绕过。"""
+ with pytest.raises(MineruError) as caught:
+ url_source._public_address(address)
+ assert caught.value.code == "unsupported_source"
+
+
[email protected]("address", ["93.184.216.34", "2606:4700:4700::1111", "::ffff:93.184.216.34"])
+def test_accept_public_addresses(address: str) -> None:
+ """允许公网 IPv4/IPv6,并把映射公网 IPv4 归一化为同一连接目标。"""
+ result = url_source._public_address(address)
+ assert result == ("93.184.216.34" if address.startswith("::ffff:") else address)
+
+
[email protected]("host", ["127.1", "2130706433", "0x7f000001", "[::ffff:127.0.0.1]", "[::1]"])
+def test_system_resolver_cannot_bypass_loopback_policy(host: str, tmp_path: Path) -> None:
+ """真实系统解析器把缩写、整数和映射形式归一化后,仍必须拒绝回环目标。"""
+ with pytest.raises(MineruError, match="public unicast"):
+ asyncio.run(
+ api_server._extract_bytes(api_server._UrlSource(url=f"https://{host}/internal"), api_server.FileStore(tmp_path))
+ )
+
+
+def test_scoped_ipv6_is_rejected_before_dns(dns: tuple[list[str], list[str]], tmp_path: Path) -> None:
+ """拒绝带接口编号的 IPv6,避免解析器剥离作用域后丢失原始限制信息。"""
+ with pytest.raises(MineruError, match="zone identifier"):
+ asyncio.run(
+ api_server._extract_bytes(
+ api_server._UrlSource(url="https://[2001:4860:4860::8888%251]/"), api_server.FileStore(tmp_path)
+ )
+ )
+ assert dns[1] == []
+
+
[email protected]("private", ["127.0.0.1", "10.0.0.5", "::1", "::ffff:169.254.169.254"])
+def test_reject_entire_mixed_dns_answer(
+ dns: tuple[list[str], list[str]], connections: list[httpx.Request], tmp_path: Path, private: str
+) -> None:
+ """任一解析结果受限时,在建立首个公网连接前拒绝整个 URL。"""
+ addresses, calls = dns
+ addresses.append(private)
+ with pytest.raises(MineruError, match="public unicast"):
+ asyncio.run(
+ api_server._extract_bytes(
+ api_server._UrlSource(url="https://source.example/opaque"), api_server.FileStore(tmp_path)
+ )
+ )
+ assert calls == ["source.example"]
+ assert connections == []
+
+
+def test_pin_ip_preserve_host_sni_and_signed_url(
+ dns: tuple[list[str], list[str]], connections: list[httpx.Request], tmp_path: Path
+) -> None:
+ """连接使用校验后的 IP,原始域名、签名路径、查询串和来源上下文完整传递。"""
+ original = "https://source.example:8443/a%2Fb?signature=a%2Fb&part=1"
+ extracted = asyncio.run(api_server._extract_bytes(api_server._UrlSource(url=original), api_server.FileStore(tmp_path)))
+ assert dns[1] == ["source.example"]
+ assert len(connections) == 1
+ request = connections[0]
+ assert str(request.url) == "https://93.184.216.34:8443/a%2Fb?signature=a%2Fb&part=1"
+ assert request.headers["host"] == "source.example:8443"
+ assert request.extensions["sni_hostname"] == "source.example"
+ assert request.extensions["timeout"]["connect"] <= 60
+ assert request.extensions["timeout"]["read"] == 60
+ assert extracted.source_uri == original
+ assert extracted.data == HTML
+
+
+def test_dns_rebinding_and_connection_fallback(
+ dns: tuple[list[str], list[str]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """首个地址失败后仅使用首次校验过的候选地址,DNS 变更不会重新进入连接。"""
+ addresses, dns_calls = dns
+ addresses[:] = ["2606:4700:4700::1111", "93.184.216.34", "93.184.216.34"]
+ connections: list[httpx.Request] = []
+
+ async def respond(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:
+ """首个 IPv6 连接失败时把后续 DNS 应答改成回环地址。"""
+ connections.append(request)
+ if len(connections) == 1:
+ addresses[:] = ["127.0.0.1"]
+ raise httpx.ConnectError("simulated unreachable IPv6")
+ return httpx.Response(200, content=HTML)
+
+ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", respond)
+ extracted = asyncio.run(
+ api_server._extract_bytes(api_server._UrlSource(url="https://source.example/a.html"), api_server.FileStore(tmp_path))
+ )
+ assert extracted.data == HTML
+ assert dns_calls == ["source.example"]
+ assert [request.url.host for request in connections] == ["2606:4700:4700::1111", "93.184.216.34"]
+ assert connections[1].extensions["timeout"]["connect"] <= connections[0].extensions["timeout"]["connect"]
+
+
+def test_redirect_target_is_never_requested(
+ dns: tuple[list[str], list[str]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """公网响应重定向至内网时停止下载,重定向目标不会收到请求。"""
+ calls: list[httpx.Request] = []
+
+ async def redirect(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:
+ """模拟公网源站把下载重定向至回环管理端口。"""
+ calls.append(request)
+ return httpx.Response(302, headers={"location": "https://127.0.0.1/admin"})
+
+ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", redirect)
+ with pytest.raises(httpx.HTTPStatusError):
+ asyncio.run(
+ api_server._extract_bytes(
+ api_server._UrlSource(url="https://source.example/redirect"), api_server.FileStore(tmp_path)
+ )
+ )
+ assert len(calls) == 1
+ assert dns[1] == ["source.example"]
+
+
+def test_dns_timeout_and_cancellation(monkeypatch: pytest.MonkeyPatch) -> None:
+ """DNS 等待受连接预算限制,任务取消也能直接中断解析等待。"""
+
+ async def resolve(self: asyncio.BaseEventLoop, host: str, port: int, **kwargs: Any) -> list[Any]:
+ """模拟 DNS 服务一直没有应答。"""
+ await asyncio.Future()
+ return []
+
+ monkeypatch.setattr(asyncio.BaseEventLoop, "getaddrinfo", resolve)
+
+ async def check() -> None:
+ """分别验证超时异常与取消异常,确保没有转成无限等待。"""
+ request = httpx.Request("GET", "https://source.example/", extensions={"timeout": {"connect": 0.01}})
+ with pytest.raises(httpx.ConnectTimeout):
+ await url_source._resolve_public_addresses(request)
+ task = asyncio.create_task(url_source._resolve_public_addresses(request))
+ await asyncio.sleep(0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ asyncio.run(check())
+
+
[email protected]("api_key", [None, "test-key"])
[email protected]("scheme", ["http", "https"])
+def test_api_and_router_block_loopback_before_contact(
+ service: tuple[TestClient, FastAPI], api_key: str | None, scheme: str
+) -> None:
+ """直接 API 与 Router 在匿名及已认证调用下均拦截本机源站,阻止内容回显。"""
+ client, app = service
+ calls: list[str] = []
+ source = FastAPI()
+
+ @source.get("/internal")
+ async def internal(request: Request) -> Response:
+ """仅提供合成敏感标记,任何实际访问都视为防护失败。"""
+ calls.append(request.url.path)
+ return Response(b'{"secret":"SSRF_LOCAL_CANARY"}', media_type="application/json")
+
+ server = _Server(source)
+ server.start()
+ try:
+ for worker in _execution_apps(app):
+ worker.state.allow_http_source = True
+ worker.state.api_key = api_key
+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
+ response = client.post(
+ "/v1/tasks",
+ json={"files": [{"file_name": "internal.html", "url": f"{scheme}://127.0.0.1:{server.port}/internal"}]},
+ headers=headers,
+ )
+ assert response.status_code == 202, response.text
+ result = _terminal(client, response.json(), headers=headers)
+ assert result["status"] == "failed"
+ assert result["files"][0]["error"]["code"] == "unsupported_source"
+ assert result["files"][0].get("result_url") is None
+ assert calls == []
+ finally:
+ server.stop()
+
+
+def test_api_and_router_allow_public_download_with_proxy_environment(
+ service: tuple[TestClient, FastAPI],
+ dns: tuple[list[str], list[str]],
+ connections: list[httpx.Request],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """环境代理不会接管下载,API/Router 仍通过校验后的公网连接产出真实结果。"""
+ client, _ = service
+ for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
+ monkeypatch.setenv(key, "http://127.0.0.1:9")
+ monkeypatch.setenv("NO_PROXY", "")
+ monkeypatch.setenv("no_proxy", "")
+ response = client.post("/v1/tasks", json={"files": [{"file_name": "public.html", "url": "https://source.example/opaque"}]})
+ assert response.status_code == 202
+ result = _terminal(client, response.json())
+ assert result["status"] == "completed", result
+ assert b"Validated download content." in _archive(client, result)["markdown.md"]
+ assert dns[1] == ["source.example"]
+ assert len(connections) == 1 and connections[0].url.host == "93.184.216.34"