Files
fetch-mcp/tests/test_transport_edges.py
T
omar 5d36fddd30
ci / static (push) Failing after 27s
ci / test-3.12 (push) Skipped
ci / test-3.13 (push) Skipped
ci / image (push) Skipped
ci / smoke (push) Skipped
ci / publish (push) Skipped
Add fetch MCP server with proxy routing, challenge solving and failure reports
Live reads go through an operator proxy pool (round-robin over the newest 100
entries, cooling on connect failures, no direct fallback); stored clearances are
replayed only on the exit that earned them. Identity, clearance, solver and
Turnstile rungs escalate automatically. fetch_pages reads up to 12 URLs four at
a time with per-item isolation. report/reports/reports_update keep a durable
queue of unreadable pages for the operator.

Ships a pinned multi-stage image (non-root 10001, data in /data), an ordered CI
with static gates, tests on 3.12 and 3.13 at 85% coverage, an offline image
smoke, and sha/latest publishing gated on main.
2026-11-28 19:29:46 +03:00

230 lines
8.1 KiB
Python

import socket
from datetime import UTC, datetime
import pytest
import proxy
import transport
def reply(status=200, *, body=b"", ctype=b"text/plain", headers=None) -> transport._Reply:
made = transport._Reply()
made.status = status
made.headers_complete = True
made.content_type = ctype
made.discard_body = not 200 <= status < 300
for name, value in (headers or {}).items():
made.headers_lower[name] = value
if name == "cf-mitigated":
made.cf_mitigated = True
if name == "location":
made.location = value.encode()
made.body.extend(body)
return made
def patch(monkeypatch, replies):
seq = iter(replies)
def fake(target, proxy_entry, deadline, headers, cookies, allow_private, identity=None):
value = next(seq)
if isinstance(value, Exception):
raise value
return value
monkeypatch.setattr(transport, "_request", fake)
@pytest.mark.parametrize(
"url",
[
"http://user:pass@example.com/",
"ftp://example.com/",
"http://exa mple.com/",
"http://example.com/%zz",
"http://[::1]:99999/",
"http://example.com/" + "a" * 9000,
"http://localhost/",
"http://example.com\\",
],
)
def test_url_validation_rejects(pool, url):
pool("http://127.0.0.1:1")
with pytest.raises(transport.FetchError):
transport.download(url)
def test_private_literal_and_private_resolution(monkeypatch):
with pytest.raises(transport.FetchError) as caught:
transport._resolve(transport._target("http://10.0.0.1/"), 10**9, allow_private=False)
assert caught.value.code == "private"
assert transport._target("http://10.0.0.1/", allow_private=True).host == "10.0.0.1"
monkeypatch.setattr(
transport, "_lookup", lambda host, port, allow_private: (_ for _ in ()).throw(transport.FetchError("dns", "no"))
)
with pytest.raises(transport.FetchError):
transport._resolve(transport._target("https://example.com/"), 10**9, allow_private=False)
assert caught is not None
def test_public_address_matrix():
assert transport._public(transport.ip_address("1.1.1.1"))
assert not transport._public(transport.ip_address("192.0.0.9"))
assert not transport._public(transport.ip_address("2001:db8::1"))
assert transport._public(transport.ip_address("2606:4700::1111"))
def test_status_500_and_protocol_invalid(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(500)])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "status"
empty = transport._Reply()
patch(monkeypatch, [empty])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "protocol"
def test_407_is_proxy_fault(monkeypatch, pool):
pool("http://127.0.0.1:1", "http://127.0.0.1:2")
patch(monkeypatch, [reply(407), reply(200, body=b"ok")])
assert transport.download("https://example.com/").body == b"ok"
def test_challenge_header_sets_flag(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(403, headers={"cf-mitigated": "challenge"})])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert "Challenge" in str(caught.value)
def test_redirect_rules(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(302), reply(200, body=b"ok")])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "redirect"
steps = [reply(302, headers={"location": f"/h{i}"}) for i in range(8)]
patch(monkeypatch, steps)
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "redirect"
patch(monkeypatch, [reply(302, headers={"location": "/a"}), reply(302, headers={"location": "/"})])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert "loop" in str(caught.value)
def test_duplicate_location_rejected(monkeypatch, pool):
pool("http://127.0.0.1:1")
made = reply(302)
made.duplicate_location = True
patch(monkeypatch, [made])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert "exactly one" in str(caught.value)
def test_header_and_body_caps(monkeypatch):
made = transport._Reply()
for _ in range(200):
made.receive_header(b"X-Pad: " + b"y" * 900 + b"\r\n")
assert made.too_large == "headers"
body = transport._Reply()
body.status = 200
assert body.receive_body(b"z" * (transport._MAX_BODY + 1)) == transport.CURL_WRITEFUNC_ERROR
assert body.too_large == "body"
def test_receive_header_ignores_undecodable(monkeypatch):
made = transport._Reply()
made.receive_header(b"HTTP/1.1 200 OK\r\n")
made.receive_header(b"X-Bin: \xff\xfe\r\n")
assert made.headers_lower["x-bin"] == "\xff\xfe"
def test_curl_error_mapping():
class Err:
def __init__(self, code):
self.code = code
assert transport._curl_error(Err(transport.CurlECode.OPERATION_TIMEDOUT), True).code == "proxy"
assert transport._curl_error(Err(transport.CurlECode.OPERATION_TIMEDOUT), False).code == "timeout"
assert transport._curl_error(Err(transport.CurlECode.PEER_FAILED_VERIFICATION), True).code == "tls"
assert transport._curl_error(Err(transport.CurlECode.BAD_CONTENT_ENCODING), False).code == "encoding"
assert transport._curl_error(Err(transport.CurlECode.COULDNT_CONNECT), True).code == "proxy"
assert transport._curl_error(Err(transport.CurlECode.COULDNT_CONNECT), False).code == "network"
assert transport._curl_error(Err(999), False).code == "network"
def test_content_metadata_fallbacks():
assert transport._content_metadata(b"garbage")[0] == "application/octet-stream"
media, charset = transport._content_metadata(b"text/html; charset=latin-1")
assert media == "text/html" and charset == "latin-1"
def test_fetch_text_errors(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(503)])
with pytest.raises(transport.FetchError) as caught:
transport.fetch_text("https://example.com/")
assert caught.value.code == "status"
patch(monkeypatch, [reply(429, headers={"retry-after": "0"}) for _ in range(4)])
with pytest.raises(transport.FetchError):
transport.fetch_text("https://example.com/")
def test_retry_after_overflow_is_clamped(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(429, headers={"retry-after": "999999999999"})])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/", deadline=5)
assert caught.value.code == "rate_limited"
assert caught.value.retry_at.year > 2000
def test_pause_wait_inside_deadline(monkeypatch, pool):
pool("http://127.0.0.1:1")
transport._pauses.set("example.com", 0.05)
patch(monkeypatch, [reply(200, body=b"ok")])
assert transport.download("https://example.com/", deadline=5).body == b"ok"
def test_proxy_bundle_reads_and_caches(monkeypatch, tmp_path):
ca = tmp_path / "ca.pem"
ca.write_text("PEM", "utf-8")
monkeypatch.setenv("MCP_PROXY_CA", str(ca))
monkeypatch.setattr(transport, "_bundle", None)
path = transport._proxy_bundle()
assert path and "fetch-mcp-trust" in path
assert transport._proxy_bundle() == path
def test_headers_skip_multiline_values():
assert transport._headers({"a": "1\n2"}) == []
def test_pool_start_loads_list(monkeypatch):
made = proxy.Pool(_route="proxy", _list_url="https://list.example/", _token="t", refresh_minutes=0)
assert made.start(lambda url, token: "http://a:1\n") is True
assert len(made) == 1
assert made.start(lambda url, token: "") is False
def test_pool_stop_sets_event():
made = proxy.Pool()
made.stop()
assert made._stop.is_set()
def test_now_helper_timezone():
assert datetime.now(UTC).tzinfo is UTC
assert socket is not None