Files
vuln-mcp/tests/test_transport.py
T
omar cf301042fa
CI / Python 3.13 (push) Successful in 41s
CI / Python 3.12 (push) Successful in 47s
CI / Build and smoke-test image (push) Successful in 15s
Let a geo-blocked index source fetch through the proxy pool
2026-11-29 09:39:40 +03:00

896 lines
38 KiB
Python

from __future__ import annotations
import asyncio
import base64
import logging
import ssl
import traceback
from collections.abc import Callable
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass
from datetime import UTC, datetime
from email.utils import format_datetime
from pathlib import Path
from types import SimpleNamespace
from typing import Literal
import anyio
import certifi
import httpcore
import httpx
import pytest
import trustme
from vuln_mcp import transport
from vuln_mcp.store import Store
from vuln_mcp.transport import HttpClients, HttpError
SIEMENS = "https://cert-portal.siemens.com/productcert/csaf/ssa-563922.json"
ALT_SIEMENS = SIEMENS.replace("563922", "563923")
MSRC = "https://msrc.microsoft.com/csaf/advisories/2025/msrc_cve-2025-43715.json"
KEV = "https://www.cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv"
NVD = "https://services.nvd.nist.gov/rest/json/cves/2.0"
EPSS = "https://api.first.org/data/v1/epss"
CVE = "https://cveawg.mitre.org/api/cve/CVE-2025-43715"
ASSET = "https://github.com/CVEProject/cvelistV5/releases/download/cve_2025-06-01_0000Z/2025-06-01_all_CVEs_at_midnight.zip.zip"
CDN = "https://release-assets.githubusercontent.com/github-production-release-asset/123/aa-bb?sig=original"
PROXIES = ("http://proxy-a.test:8080", "http://proxy-b.test:8080")
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
@pytest.fixture
async def store(tmp_path: Path, anyio_backend: str):
db = Store(tmp_path / "data")
await db.open()
try:
yield db
finally:
await db.close()
@dataclass
class Clock:
mono: float = 1000.0
utc: float = 1_750_000_000.0
def advance(self, seconds: float) -> None:
self.mono += seconds
self.utc += seconds
@pytest.fixture
def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
clock = Clock()
monkeypatch.setattr(transport, "monotonic", lambda: clock.mono)
monkeypatch.setattr(transport, "time", lambda: clock.utc)
return clock
def settings(
proxies: tuple[str, ...] = PROXIES, retries: int = 0, *, live_route: Literal["direct", "proxy"] = "proxy",
) -> SimpleNamespace:
return SimpleNamespace(proxies=proxies, max_retries=retries, live_route=live_route, live_timeout=9.5)
def routed_clients(
monkeypatch: pytest.MonkeyPatch, handler: Callable, *, direct_routes: tuple[str, ...] = (),
) -> list[str]:
original = httpx.AsyncClient
direct_labels = iter(direct_routes)
created = []
def create(*, proxy: str | None, trust_env: bool) -> httpx.AsyncClient:
assert trust_env is False
label = next(direct_labels, "direct") if proxy is None else httpx.URL(proxy).host
created.append(label)
async def dispatch(request: httpx.Request) -> httpx.Response:
return await handler(label, request)
return original(proxy=None, trust_env=False, transport=httpx.MockTransport(dispatch))
monkeypatch.setattr(transport.httpx, "AsyncClient", create)
return created
async def status(operation, expected: str) -> HttpError:
with pytest.raises(HttpError) as caught:
await operation
assert caught.value.status == expected
return caught.value
@pytest.mark.anyio
async def test_proxy_list_swap_does_not_interrupt_inflight_send(monkeypatch, store):
started, release = asyncio.Event(), asyncio.Event()
async def respond(route, request):
if route == "proxy-a.test":
started.set()
await release.wait()
return httpx.Response(200, json={"route": route})
created = routed_clients(monkeypatch, respond)
async with HttpClients(settings(), store) as clients, asyncio.TaskGroup() as tasks:
first = tasks.create_task(clients.live.json("siemens", SIEMENS))
async with asyncio.timeout(3):
await started.wait()
try:
urls = (PROXIES[1], "http://proxy-c.test:8080")
await clients.update_proxies(urls)
await clients.update_proxies(urls)
assert (await clients.live.json("epss", EPSS))[0] == {"route": "proxy-b.test"}
assert (await clients.live.json("epss", EPSS))[0] == {"route": "proxy-c.test"}
finally:
release.set()
assert (await first)[0] == {"route": "proxy-a.test"}
assert created == ["direct", "proxy-a.test", "proxy-b.test", "proxy-c.test"]
@pytest.mark.anyio
async def test_channels_round_robin_and_revalidate(monkeypatch, store, tmp_path):
seen = []
async def respond(route, request):
seen.append((route, str(request.url), request.headers.get("If-None-Match")))
if route == "direct" and str(request.url) == SIEMENS:
return httpx.Response(302, headers={"Location": ALT_SIEMENS})
if route == "direct" and len(seen) == 3:
return httpx.Response(502)
if request.headers.get("If-None-Match"):
return httpx.Response(304)
return httpx.Response(200, json={"public": "advisory"}, headers={"ETag": '"v1"'})
delays = []
async def sleep(delay):
delays.append(delay)
monkeypatch.setattr(transport, "sleep", sleep)
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=1), store) as clients:
assert (await clients.live.json("siemens", SIEMENS))[0] == {"public": "advisory"}
target = tmp_path / "index.tmp"
assert (await clients.index.download("siemens", SIEMENS, target))[0] == 200
assert target.read_bytes() == b'{"public":"advisory"}'
assert (await clients.live.json("siemens", SIEMENS))[0] == {"public": "advisory"}
assert seen == [
("proxy-a.test", SIEMENS, None), ("direct", SIEMENS, None),
("direct", ALT_SIEMENS, None), ("direct", ALT_SIEMENS, None),
("proxy-b.test", SIEMENS, '"v1"'),
]
assert delays == [0.5]
@pytest.mark.anyio
@pytest.mark.parametrize("retries", [0, 1])
async def test_only_a_proven_proxy_tcp_error_rotates_immediately(monkeypatch, store, retries):
seen = []
async def respond(route, request):
seen.append(route)
if route == "proxy-a.test":
trace = request.extensions["trace"]
await trace("connection.connect_tcp.started", {"host": route, "port": 8080})
await trace("connection.connect_tcp.failed", {"exception": httpcore.ConnectError()})
raise httpx.ConnectError("not an origin failure")
return httpx.Response(200, json={"ok": True})
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=retries), store) as clients:
if retries:
assert (await clients.live.json("siemens", SIEMENS))[0] == {"ok": True}
assert seen == ["proxy-a.test", "proxy-b.test"]
else:
await status(clients.live.json("siemens", SIEMENS), "proxy_unavailable")
assert seen == ["proxy-a.test"]
# A's quarantine applies to another publisher too; only B may be chosen.
assert (await clients.live.json("epss", EPSS))[0] == {"ok": True}
assert seen[-1] == "proxy-b.test"
@pytest.mark.anyio
@pytest.mark.parametrize("failure", [httpx.ProxyError, httpx.ConnectError, 403, 408, 500, 502, 504])
async def test_a_route_failure_moves_to_the_next_proxy(monkeypatch, store, failure):
seen = []
async def respond(route, request):
seen.append(route)
if len(seen) == 1:
if isinstance(failure, int):
return httpx.Response(failure)
raise failure("never print this credential-like secret")
return httpx.Response(200, json={})
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=3), store) as clients:
value, _headers = await clients.live.json("siemens", SIEMENS)
assert value == {}
await clients.live.json("siemens", SIEMENS)
await clients.live.json("siemens", SIEMENS)
# The failed attempt moved on, and an unproven failure did not disable the route.
assert seen[:2] == ["proxy-a.test", "proxy-b.test"]
assert "proxy-a.test" in seen[2:]
assert all(route in {httpx.URL(url).host for url in PROXIES} for route in seen)
@pytest.mark.anyio
async def test_no_egress_fallback_in_either_direction(monkeypatch, store, tmp_path):
seen = []
async def respond(route, request):
seen.append(route)
return httpx.Response(502)
async def sleep(delay):
return
monkeypatch.setattr(transport, "sleep", sleep)
routed_clients(monkeypatch, respond)
async with HttpClients(settings((), retries=1), store) as clients:
await status(clients.live.json("siemens", SIEMENS), "proxy_unavailable")
assert not seen
async with HttpClients(settings(retries=1), store) as clients:
await status(clients.index.download("siemens", SIEMENS, tmp_path / "data"), "unavailable")
assert seen == ["direct", "direct"]
@pytest.mark.anyio
async def test_explicit_direct_live_isolated_and_revalidates(monkeypatch, store, clock):
seen = []
delays = []
async def sleep(delay):
delays.append(delay)
async def respond(route, request):
seen.append((route, str(request.url), request.headers.get("If-None-Match")))
limits = request.extensions["timeout"]
assert limits["read"] == (9.5 if route == "live-direct" else 60)
assert limits["connect"] == (9.5 if route == "live-direct" else 3)
match len(seen):
case 1:
trace = request.extensions["trace"]
await trace("connection.connect_tcp.started", {"host": request.url.host, "port": 443})
await trace("connection.connect_tcp.failed", {"exception": httpcore.ConnectError("refused")})
raise httpx.ConnectError("refused")
case 2:
raise httpx.ReadTimeout("connection stalled")
case 3:
return httpx.Response(200, json={"channel": "live"}, headers={"ETag": '"v1"'})
case 4:
return httpx.Response(200, json={"channel": "index"})
case 5:
return httpx.Response(304)
case 6:
return httpx.Response(302, headers={"Location": "/productcert/csaf/provider-metadata.json"})
pytest.fail("unexpected egress")
monkeypatch.setattr(transport, "sleep", sleep)
created = routed_clients(monkeypatch, respond, direct_routes=("index-direct", "live-direct"))
async with HttpClients(settings(retries=1, live_route="direct"), store) as clients:
await status(clients.live.json("kev", KEV), "invalid_data")
await status(clients.index.json("nvd", NVD), "invalid_data")
await status(clients.live.json("epss", EPSS, deadline=clock.mono), "timeout")
await status(clients.live.json("siemens", SIEMENS), "timeout")
assert (await clients.live.json("siemens", SIEMENS))[0] == {"channel": "live"}
assert (await clients.index.json("siemens", SIEMENS))[0] == {"channel": "index"}
assert (await clients.live.json("siemens", SIEMENS))[0] == {"channel": "live"}
await status(clients.live.json("siemens", ALT_SIEMENS), "invalid_data")
assert created == ["index-direct", "live-direct"]
assert delays == [0.5]
assert seen == [
("live-direct", SIEMENS, None), ("live-direct", SIEMENS, None), ("live-direct", SIEMENS, None),
("index-direct", SIEMENS, None), ("live-direct", SIEMENS, '"v1"'), ("live-direct", ALT_SIEMENS, None),
]
@pytest.mark.anyio
@pytest.mark.parametrize("use_date", [False, True])
@pytest.mark.parametrize("live_route", ["direct", "proxy"])
async def test_quota_shared_both_channels_persisted_and_isolated_by_publisher(monkeypatch, clock, tmp_path, use_date, live_route):
entered = asyncio.Event()
release = asyncio.Event()
seen = []
retry_at = datetime.fromtimestamp(clock.utc + 120, UTC)
async def respond(route, request):
seen.append((route, request.url.host))
if len(seen) == 1:
return httpx.Response(200, json={"public": "advisory"}, headers={"ETag": '"earlier"'})
if len(seen) == 2:
assert request.headers["If-None-Match"] == '"earlier"'
entered.set()
await release.wait()
return httpx.Response(429, headers={"Retry-After": format_datetime(retry_at, usegmt=True) if use_date else "120"})
if request.url.host == "cert-portal.siemens.com":
assert request.headers["If-None-Match"] == '"earlier"'
return httpx.Response(304)
return httpx.Response(200, json={})
async def queued(clients, started, deadline):
started.set()
return await status(
clients.index.download("siemens", SIEMENS, tmp_path / "advisory.json", deadline=deadline), "rate_limited"
)
routed_clients(monkeypatch, respond)
directory = tmp_path / "database"
db = Store(directory)
await db.open()
try:
async with HttpClients(settings(retries=1, live_route=live_route), db) as clients:
await clients.live.json("siemens", SIEMENS)
async with asyncio.timeout(3):
async with asyncio.TaskGroup() as group:
first = group.create_task(status(clients.live.json("siemens", SIEMENS), "rate_limited"))
await entered.wait()
started = asyncio.Event()
other_channel = group.create_task(queued(clients, started, clock.mono + 9))
await started.wait()
# A different publisher proceeds via the same proxy pool while Siemens is busy.
await clients.live.json("epss", EPSS)
release.set()
assert first.result().retry_at == other_channel.result().retry_at == retry_at.isoformat()
if live_route == "direct":
assert await db.quota("siemens", route="direct") == retry_at.timestamp()
assert seen == [
("direct", "cert-portal.siemens.com"), ("direct", "cert-portal.siemens.com"),
("direct", "api.first.org"),
]
else:
assert await db.quota("siemens", route="proxy:1") == retry_at.timestamp()
assert seen == [
("proxy-a.test", "cert-portal.siemens.com"), ("proxy-b.test", "cert-portal.siemens.com"),
("proxy-a.test", "api.first.org"),
]
# A process waits by monotonic time; a new process reconstructs the pause from UTC.
clock.mono += 120
assert (await clients.live.json("siemens", SIEMENS))[0] == {"public": "advisory"}
finally:
await db.close()
assert seen[-1] == ("direct" if live_route == "direct" else "proxy-b.test", "cert-portal.siemens.com")
reopened = Store(directory)
await reopened.open()
try:
async with HttpClients(settings(), reopened) as clients:
await status(clients.live.json("siemens", SIEMENS), "rate_limited")
await status(clients.index.json("siemens", SIEMENS, deadline=clock.mono + 9), "rate_limited")
finally:
await reopened.close()
assert len(seen) == 4
@pytest.mark.anyio
async def test_github_rate_limit_403_waits_at_publisher_instead_of_changing_route(monkeypatch, clock, store):
seen = []
releases = "https://api.github.com/repos/CVEProject/cvelistV5/releases"
until = int(clock.utc) + 120
async def respond(route, request):
seen.append((route, request.url.host))
return httpx.Response(403, headers={"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": str(until)})
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=3), store) as clients:
error = await status(clients.index.json("cvelist", releases, deadline=clock.mono + 8), "rate_limited")
assert error.retry_at == datetime.fromtimestamp(until, UTC).isoformat()
assert await store.quota("cvelist", route="direct") == until
await status(clients.live.json("cvelist", CVE), "rate_limited")
assert seen == [("direct", "api.github.com")]
@pytest.mark.anyio
async def test_rate_limit_fallback_growth_and_success_reset(monkeypatch, clock, store):
replies = iter([429, 429, 200, 429, 503, 200])
async def respond(route, request):
code = next(replies)
return httpx.Response(code, json={}, headers={"Retry-After": "29" if code == 503 else "invalid"})
routed_clients(monkeypatch, respond)
async with HttpClients(settings(), store) as clients:
for delay in (60, 120):
error = await status(clients.live.json("epss", EPSS), "rate_limited")
assert error.retry_at == datetime.fromtimestamp(clock.utc + delay, UTC).isoformat()
clock.advance(delay)
await clients.live.json("epss", EPSS)
for delay in (60, 29):
error = await status(clients.live.json("epss", EPSS), "rate_limited")
assert error.retry_at == datetime.fromtimestamp(clock.utc + delay, UTC).isoformat()
clock.advance(delay)
await clients.live.json("epss", EPSS)
@pytest.mark.anyio
@pytest.mark.parametrize("ecosystem", ["%5BEMPTY%5D", "Rock%20%26%20Roll"])
async def test_osv_manifest_ecosystem_paths_are_escaped(monkeypatch, store, tmp_path, ecosystem):
seen = []
async def respond(route, request):
seen.append((route, request.url.raw_path))
return httpx.Response(200, content=b"{}")
routed_clients(monkeypatch, respond)
host = "https://storage.googleapis.com/osv-vulnerabilities/"
async with HttpClients(settings(), store) as clients:
await clients.index.download("osv", f"{host}{ecosystem}/TEST-1.json", tmp_path / "response")
for invalid in ("%2e%2e", "bad%2fpath", "%252E%252E"):
await status(clients.index.json("osv", f"{host}{invalid}/TEST-1.json"), "invalid_data")
assert seen == [("direct", f"/osv-vulnerabilities/{ecosystem}/TEST-1.json".encode("ascii"))]
@pytest.mark.anyio
async def test_no_store_discards_previous_representation(monkeypatch, store):
seen = []
async def respond(route, request):
seen.append(request.headers.get("If-None-Match"))
headers = {"ETag": '"revision"'}
if len(seen) == 2:
headers["Cache-Control"] = "private, NO-STORE"
return httpx.Response(200, json={"revision": len(seen)}, headers=headers)
routed_clients(monkeypatch, respond)
async with HttpClients(settings(), store) as clients:
for revision in (1, 2, 3):
assert (await clients.live.json("siemens", SIEMENS))[0] == {"revision": revision}
assert seen == [None, '"revision"', None]
@pytest.mark.anyio
async def test_304_without_body_retries_without_validator(monkeypatch, store):
seen = []
async def respond(route, request):
seen.append(request.headers.get("If-None-Match"))
if len(seen) == 1:
return httpx.Response(304)
return httpx.Response(200, json={"revision": 2})
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=1), store) as clients:
data, _ = await clients.live.json("siemens", SIEMENS, headers={"If-None-Match": '"no-local-body"'})
assert data == {"revision": 2}
assert seen == ['"no-local-body"', None]
@pytest.mark.anyio
async def test_only_registered_urls_methods_and_redirects(monkeypatch, store, tmp_path):
seen = []
async def respond(route, request):
seen.append((route, str(request.url), request.method))
if request.url.host == "github.com":
return httpx.Response(302, headers={"Location": CDN})
if str(request.url) == SIEMENS:
return httpx.Response(302, headers={"Location": "https://intranet.test/secret"})
return httpx.Response(200, json={})
routed_clients(monkeypatch, respond)
async with HttpClients(settings(), store) as clients:
for url in (
SIEMENS.replace("https://", "http://"), SIEMENS.replace("https://", "https://secret@"),
SIEMENS.replace(".com/", ".com:8443/"), SIEMENS + "#fragment",
SIEMENS.replace("/ssa-", "/%2Fssa-"), "https://cert-portal.siemens.com/login",
):
await status(clients.live.json("siemens", url), "invalid_data")
await status(clients.live.json("siemens", SIEMENS, body={}), "invalid_data")
await status(clients.index.json("nvd", NVD), "invalid_data")
await status(clients.index.json("cvelist", CDN), "invalid_data")
await status(clients.index.json("cvelist", CVE), "invalid_data")
await status(clients.live.json("cvelist", ASSET), "invalid_data")
assert seen == []
await status(clients.live.json("siemens", SIEMENS), "invalid_data")
await clients.index.download("cvelist", ASSET, tmp_path / "asset")
await clients.live.json("osv", "https://api.osv.dev/v1/query", body={"package": {"purl": "pkg:pypi/example"}})
assert seen == [
("proxy-a.test", SIEMENS, "GET"), ("direct", ASSET, "GET"), ("direct", CDN, "GET"),
("proxy-b.test", "https://api.osv.dev/v1/query", "POST"),
]
@pytest.mark.anyio
async def test_nvd_spacing_checked_before_redirect_and_page(monkeypatch, clock, store):
seen = []
async def respond(route, request):
seen.append((route, request.url.query))
if len(seen) == 1:
return httpx.Response(302, headers={"Location": NVD + "?startIndex=14"})
return httpx.Response(200, json={})
routed_clients(monkeypatch, respond)
async with HttpClients(settings(), store) as clients:
await status(clients.live.json("nvd", NVD + "?cpeName=x&isVulnerable", deadline=clock.mono + 3), "timeout")
await status(clients.live.json("nvd", NVD + "?startIndex=20", deadline=clock.mono + 3), "timeout")
clock.advance(6.1)
await clients.live.json("nvd", NVD + "?startIndex=20")
assert seen == [("proxy-a.test", b"cpeName=x&isVulnerable"), ("proxy-b.test", b"startIndex=20")]
@pytest.mark.anyio
@pytest.mark.parametrize("live_route", ["direct", "proxy"])
async def test_live_waiter_precedes_background_and_does_not_cancel_transfer(monkeypatch, store, tmp_path, live_route):
seen = []
active = {source: asyncio.Event() for source in ("siemens", "msrc")}
release = {source: asyncio.Event() for source in active}
live_sent = asyncio.Event()
async def respond(route, request):
source = {httpx.URL(url).host: name for url, name in [(SIEMENS, "siemens"), (MSRC, "msrc"), (KEV, "kev")]}
name = source[request.url.host]
seen.append((route, name))
if route == "direct" and name in active:
active[name].set()
await release[name].wait()
if route != "direct":
live_sent.set()
return httpx.Response(200, json={})
async def queued(ready, call):
ready.set()
return await call
direct_routes = ("direct", "live-direct") if live_route == "direct" else ()
routed_clients(monkeypatch, respond, direct_routes=direct_routes)
async with HttpClients(settings(live_route=live_route), store) as clients:
await clients.index.download("kev", KEV, tmp_path / "warmup")
seen.clear()
async with asyncio.timeout(3):
async with asyncio.TaskGroup() as group:
for name, url in (("siemens", SIEMENS), ("msrc", MSRC)):
group.create_task(clients.index.download(name, url, tmp_path / name))
await active[name].wait()
bg = asyncio.Event()
group.create_task(queued(bg, clients.index.download("kev", KEV, tmp_path / "kev")))
await bg.wait()
live = asyncio.Event()
group.create_task(queued(live, clients.live.json("siemens", SIEMENS)))
await live.wait()
assert seen == [("direct", "siemens"), ("direct", "msrc")]
release["siemens"].set()
await live_sent.wait()
release["msrc"].set()
assert seen[2:] == [("live-direct" if live_route == "direct" else "proxy-a.test", "siemens"), ("direct", "kev")]
assert (tmp_path / "siemens").read_bytes() == b"{}"
class Interrupted(httpx.AsyncByteStream):
async def __aiter__(self):
yield b"a" * (256 * 1024)
raise httpx.ReadTimeout("connection went idle")
@pytest.mark.anyio
async def test_download_restarts_file_and_rejects_stream_over_limit(monkeypatch, store, tmp_path):
count = 0
async def respond(route, request):
nonlocal count
count += 1
if count == 1:
return httpx.Response(200, stream=Interrupted())
return httpx.Response(200, content=b"complete")
async def sleep(delay):
return
monkeypatch.setattr(transport, "sleep", sleep)
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=1), store) as clients:
path = tmp_path / "staged"
await clients.index.download("siemens", SIEMENS, path)
assert path.read_bytes() == b"complete"
path = tmp_path / "too-large"
await status(clients.index.download("siemens", SIEMENS, path, limit=5), "invalid_data")
assert not path.exists()
assert count == 3
async def read_request(reader: asyncio.StreamReader) -> tuple[bytes, dict[bytes, bytes]]:
request, *headers = (await reader.readuntil(b"\r\n\r\n"))[:-4].split(b"\r\n")
fields = dict((name.lower(), value.lstrip()) for name, _, value in (header.partition(b":") for header in headers))
return request, fields
async def close_writer(writer: asyncio.StreamWriter) -> None:
writer.close()
with suppress(ConnectionError, ssl.SSLError):
await writer.wait_closed()
@asynccontextmanager
async def listener(callback, *, tls: ssl.SSLContext | None = None):
connections = set()
def connected(reader, writer):
task = asyncio.create_task(callback(reader, writer))
connections.add(task)
server = await asyncio.start_server(connected, "127.0.0.1", 0, ssl=tls)
try:
async with server:
yield server.sockets[0].getsockname()[1]
finally:
if connections:
async with asyncio.timeout(3):
await asyncio.gather(*connections)
async def relay(reader, writer, origin, peer):
async def pump(source, destination):
while block := await source.read(65536):
destination.write(block)
await destination.drain()
tasks = {asyncio.create_task(pump(reader, peer)), asyncio.create_task(pump(origin, writer))}
try:
done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in done:
with suppress(ConnectionError):
task.result()
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
def tunnel_proxy(label, endpoint, journal, *, reject=False):
async def proxy(reader, writer):
peer = None
try:
request, headers = await read_request(reader)
assert request == b"CONNECT cert-portal.siemens.com:443 HTTP/1.1"
journal.append((label, headers.get(b"proxy-authorization")))
if reject:
writer.write(b"HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
await writer.drain()
return
origin, peer = await asyncio.open_connection("127.0.0.1", endpoint)
writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
await writer.drain()
await relay(reader, writer, origin, peer)
finally:
if peer is not None:
await close_writer(peer)
await close_writer(writer)
return proxy
def advisory_origin(upstream):
async def origin(reader, writer):
try:
request, headers = await read_request(reader)
assert request == b"GET /productcert/csaf/ssa-563922.json HTTP/1.1"
upstream.append(headers)
if b"if-none-match" in headers:
writer.write(b"HTTP/1.1 304 Not Modified\r\nConnection: close\r\n\r\n")
else:
writer.write(
b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\nETag: "origin-1"\r\n'
b'Set-Cookie: origin_ticket=never_send; Path=/\r\nConnection: close\r\n\r\n{}'
)
await writer.drain()
finally:
await close_writer(writer)
return origin
@pytest.mark.anyio
async def test_real_connect_credentials_tls_cookie_isolation_and_confirmed_407(monkeypatch, store, caplog):
ca = trustme.CA()
ca_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ca.configure_trust(ca_context)
origin_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ca.issue_cert("cert-portal.siemens.com").configure_cert(origin_context)
upstream = []
proxy_headers = []
original_client = httpx.AsyncClient
original_connect = anyio.connect_tcp
def client_factory(**kwargs):
return original_client(**kwargs, verify=ca_context)
monkeypatch.setattr(transport.httpx, "AsyncClient", client_factory)
caplog.set_level(logging.WARNING)
async with listener(advisory_origin(upstream), tls=origin_context) as endpoint:
async def loopback_connect(remote_host, remote_port, **kwargs):
if remote_host == "cert-portal.siemens.com" and remote_port == 443:
remote_host, remote_port = "127.0.0.1", endpoint
assert remote_host == "127.0.0.1", "test attempted external network access"
return await original_connect(remote_host, remote_port, **kwargs)
monkeypatch.setattr(anyio, "connect_tcp", loopback_connect)
async with (
listener(tunnel_proxy("A", endpoint, proxy_headers)) as a,
listener(tunnel_proxy("B", endpoint, proxy_headers)) as b,
listener(tunnel_proxy("reject", endpoint, proxy_headers, reject=True)) as reject,
):
monkeypatch.setenv("HTTPS_PROXY", f"http://127.0.0.1:{reject}")
monkeypatch.setenv("ALL_PROXY", f"http://127.0.0.1:{reject}")
monkeypatch.setenv("NO_PROXY", "*")
proxies = (f"http://alice:p%40ss%3AA@127.0.0.1:{a}", f"http://bob:s3cret%20B@127.0.0.1:{b}")
async with asyncio.timeout(5):
async with HttpClients(settings(proxies), store) as clients:
await clients.live.json("siemens", SIEMENS)
await clients.index.json("siemens", SIEMENS, headers={"Cookie": "user=secret", "Proxy-Authorization": "forged"})
await clients.live.json("siemens", SIEMENS)
await clients.live.json("siemens", SIEMENS)
retired = (f"http://user:forbidden-secret@127.0.0.1:{reject}", proxies[1])
async with HttpClients(settings(retired, retries=1), store) as clients:
# A confirmed 407 retires that route and the call moves to the next proxy.
await clients.live.json("siemens", SIEMENS)
await clients.live.json("siemens", SIEMENS)
await clients.live.json("siemens", SIEMENS)
assert [label for label, _ in proxy_headers] == ["A", "B", "A", "reject", "B", "B", "B"]
assert proxy_headers[:2] == [
("A", b"Basic " + base64.b64encode(b"alice:p@ss:A")),
("B", b"Basic " + base64.b64encode(b"bob:s3cret B")),
]
assert len(upstream) == 7
assert all(b"proxy-authorization" not in headers and b"cookie" not in headers for headers in upstream)
assert [headers.get(b"if-none-match") for headers in upstream] == [
None, None, b'"origin-1"', b'"origin-1"', None, b'"origin-1"', b'"origin-1"',
]
assert all(secret not in caplog.text for secret in ("forbidden-secret", "p@ss:A", "s3cret B", "user=secret"))
@pytest.fixture
def loopback_ca(monkeypatch, tmp_path):
ca = trustme.CA()
bundle = tmp_path / "local-ca.pem"
ca.cert_pem.write_to_path(bundle)
monkeypatch.setattr(certifi, "where", lambda: str(bundle))
original_connect = anyio.connect_tcp
async def connect(remote_host, remote_port, **kwargs):
assert remote_host == "127.0.0.1", "test attempted external network access"
return await original_connect(remote_host, remote_port, **kwargs)
monkeypatch.setattr(anyio, "connect_tcp", connect)
return ca
@pytest.mark.anyio
@pytest.mark.parametrize("certificate", ["valid", "untrusted", "wrong-proxy-name", "wrong-origin-name"])
async def test_real_https_proxy_verifies_both_tls_hops(store, loopback_ca, certificate):
origin_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
origin_name = "other.test" if certificate == "wrong-origin-name" else "cert-portal.siemens.com"
loopback_ca.issue_cert(origin_name).configure_cert(origin_context)
proxy_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
proxy_ca = trustme.CA() if certificate == "untrusted" else loopback_ca
proxy_name = "other.test" if certificate == "wrong-proxy-name" else "127.0.0.1"
proxy_ca.issue_cert(proxy_name).configure_cert(proxy_context)
upstream = []
proxy_headers = []
async with listener(advisory_origin(upstream), tls=origin_context) as endpoint:
async with listener(tunnel_proxy("TLS", endpoint, proxy_headers), tls=proxy_context) as port:
async with HttpClients(settings((f"https://alice:p%40ss@127.0.0.1:{port}",), retries=1), store) as clients:
if certificate == "valid":
assert (await clients.live.json("siemens", SIEMENS))[0] == {}
else:
# A certificate verdict is the same on every egress IP: no rotation.
await status(clients.live.json("siemens", SIEMENS), "unavailable")
credentials = ("TLS", b"Basic " + base64.b64encode(b"alice:p@ss"))
if certificate == "wrong-origin-name":
# The tunnel came up, so the origin certificate failure was retried once.
assert proxy_headers == [credentials, credentials]
elif certificate == "valid":
assert proxy_headers == [credentials]
else:
assert proxy_headers == []
if certificate == "valid":
assert len(upstream) == 1
assert b"proxy-authorization" not in upstream[0]
else:
assert upstream == []
def socks_proxy(endpoint, journal):
async def proxy(reader, writer):
peer = None
try:
assert await reader.readexactly(3) == b"\x05\x01\x02" # SOCKS5, one method: username/password.
writer.write(b"\x05\x02")
await writer.drain()
version, length = await reader.readexactly(2)
assert version == 1 # Username/password subnegotiation per RFC 1929.
user = await reader.readexactly(length)
password = await reader.readexactly((await reader.readexactly(1))[0])
writer.write(b"\x01\x00")
await writer.drain()
assert await reader.readexactly(4) == b"\x05\x01\x00\x03" # CONNECT with a domain name, not an IP.
host = await reader.readexactly((await reader.readexactly(1))[0])
port = int.from_bytes(await reader.readexactly(2), "big")
journal.append((user, password, host, port))
origin, peer = await asyncio.open_connection("127.0.0.1", endpoint)
writer.write(b"\x05\x00\x00\x01\x7f\x00\x00\x01" + endpoint.to_bytes(2, "big"))
await writer.drain()
await relay(reader, writer, origin, peer)
finally:
if peer is not None:
await close_writer(peer)
await close_writer(writer)
return proxy
@pytest.mark.anyio
@pytest.mark.parametrize("scheme", ["socks5", "socks5h"])
async def test_real_socks_resolves_origin_at_proxy_and_sends_decoded_credentials(store, loopback_ca, scheme):
origin_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
loopback_ca.issue_cert("cert-portal.siemens.com").configure_cert(origin_context)
upstream = []
journal = []
async with listener(advisory_origin(upstream), tls=origin_context) as endpoint:
async with listener(socks_proxy(endpoint, journal)) as port:
proxies = (f"{scheme}://alice%40example.test:p%3Ass%20word@127.0.0.1:{port}",)
async with HttpClients(settings(proxies), store) as clients:
assert (await clients.live.json("siemens", SIEMENS))[0] == {}
assert journal == [(b"alice@example.test", b"p:ss word", b"cert-portal.siemens.com", 443)]
assert len(upstream) == 1
assert b"proxy-authorization" not in upstream[0] and b"authorization" not in upstream[0]
@pytest.mark.anyio
async def test_configured_timeout_bounds_the_attempt_including_the_proxy_connect(monkeypatch, store):
seen = {}
async def respond(route, request):
seen.update(request.extensions["timeout"])
return httpx.Response(200, json={})
routed_clients(monkeypatch, respond)
tuning = settings(retries=0)
tuning.live_timeout = 4.5
async with HttpClients(tuning, store) as clients:
assert clients.live.budget == 5.0
await clients.live.json("siemens", SIEMENS)
assert {seen["connect"], seen["read"], seen["write"], seen["pool"]} == {4.5}
@pytest.mark.anyio
async def test_file_download_reports_bytes_rate_and_eta(monkeypatch, store, tmp_path, caplog):
caplog.set_level(logging.INFO, logger="vuln_mcp.transport")
body = b"x" * (9 * 1024**2)
async def respond(route, request):
return httpx.Response(200, content=body, headers={"Content-Length": str(len(body))})
async def sleep(delay):
return
monkeypatch.setattr(transport, "sleep", sleep)
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=0), store) as clients:
await clients.index.download("msrc", MSRC, tmp_path / "advisory.json")
lines = [r.getMessage() for r in caplog.records if r.name == "vuln_mcp.transport"]
assert any("9.0 MiB/9.0 MiB" in line and "eta" in line and "(100%)" in line for line in lines)
assert all("http" not in line for line in lines)
@pytest.mark.anyio
async def test_index_fetch_can_borrow_the_pool_and_keeps_bulk_limits(monkeypatch, store, tmp_path):
seen = {}
async def respond(route, request):
seen["route"] = route
seen["timeout"] = request.extensions["timeout"]
return httpx.Response(200, content=b"{}")
routed_clients(monkeypatch, respond)
async with HttpClients(settings(), store) as clients:
await clients.index.download("fortinet", "https://filestore.fortinet.com/fortiguard/rss/ir.xml",
tmp_path / "f.xml", via="live")
assert seen["route"] in {httpx.URL(url).host for url in PROXIES}
# Only the egress changed: bulk limits still apply.
assert (seen["timeout"]["read"], seen["timeout"]["connect"]) == (60, 3)