Refresh authenticated proxy inventory without interrupting live requests
CI / Python 3.13 (push) Successful in 24s
CI / Python 3.12 (push) Successful in 28s
CI / Build and smoke-test image (push) Successful in 12s

This commit is contained in:
omar committed 2026-11-28 14:07:29 +03:00
1 parent 8b83b1c681
commit e57ea40ede
9 files changed
+181 -33

No files matched your search

+2
View File
@@ -5,4 +5,6 @@ MCP_PROXY_URLS=[]
# Alternatively, leave MCP_PROXY_URLS=[] and supply both values below.
# MCP_PROXY_LIST_URL=https://proxy-service.example/v1/proxies?proxy_type=http&format=proxy-url-list-txt
# MCP_PROXY_LIST_TOKEN=your-new-token
# Poll the list every N minutes (0 = startup only).
MCP_PROXY_LIST_REFRESH_MINUTES=15
MCP_HTTP_MAX_RETRIES=3
+3 -2
View File
@@ -18,13 +18,14 @@ uv run --locked vuln-mcp
| `MCP_DATA_DIR` | Каталог частных данных. По умолчанию каталог приложения `vuln-mcp` текущего пользователя. Один процесс на каталог; сетевые файловые системы не поддерживаются. |
| `MCP_LIVE_ROUTE` | `proxy` по умолчанию; `direct` разрешает live-запросы без прокси. Ошибка прокси сама по себе не включает прямой маршрут. |
| `MCP_PROXY_URLS` | JSON-массив доверенных `http://`, `https://`, `socks5://` или `socks5h://` прокси. При `MCP_LIVE_ROUTE=proxy` пустой список отключает live-доступ. |
| `MCP_PROXY_LIST_URL` | Вместо статического списка: адрес HTTP(S) API, возвращающего UTF-8 текст с одним полным URL прокси на строку. GET выполняется напрямую один раз при старте в режиме `proxy`; параметры запроса сохраняются. |
| `MCP_PROXY_LIST_URL` | Вместо статического списка: адрес HTTP(S) API, возвращающего UTF-8 текст с одним полным URL прокси на строку. GET выполняется напрямую при старте и далее по интервалу только в режиме `proxy`. |
| `MCP_PROXY_LIST_TOKEN` | Токен для `Authorization: Bearer …` только на запрос списка. Для HTTP токен идёт открытым текстом: используйте HTTPS или доверенную изолированную сеть. |
| `MCP_PROXY_LIST_REFRESH_MINUTES` | Интервал обновления списка в минутах: целое число от `0` до `1440`, по умолчанию `15`. Значение `0` отключает периодический опрос, но не начальную загрузку. |
| `MCP_HTTP_MAX_RETRIES` | Число повторов после первой попытки: `0`–`8`, по умолчанию `3`. Не умножается на число прокси. |
Пример запроса: `search("6ES7823-0FE30-1AA0", asset={"version":"1.3.0"})`. Для пакета можно передать PURL, для деталей бюллетеня — `get_advisory("SSA-563922")`. Продолжение выдачи использует ту же строку, факты об активе и `next_cursor` предыдущей страницы.
Для API списка задайте `MCP_PROXY_LIST_URL` (например, `https://proxy-service.example/v1/proxies?proxy_type=http&format=proxy-url-list-txt`) и `MCP_PROXY_LIST_TOKEN` через окружение или приватный env-файл. Для Docker передайте его через `docker run --env-file …`. Оставьте `MCP_PROXY_URLS` пустым массивом или не задавайте. Допускаются до 256 адресов (1 МиБ текста); пустые строки игнорируются. При недоступном или некорректном списке индекс продолжает работать, live-запросы не переключаются на прямое соединение. Для повторной загрузки перезапустите MCP.
Для API списка задайте `MCP_PROXY_LIST_URL` (например, `https://proxy-service.example/v1/proxies?proxy_type=http&format=proxy-url-list-txt`) и `MCP_PROXY_LIST_TOKEN` через окружение или приватный env-файл. Для Docker передайте его через `docker run --env-file …`. Оставьте `MCP_PROXY_URLS` пустым массивом или не задавайте. Допускаются до 256 адресов (1 МиБ текста); пустые строки игнорируются. При ошибке или пустом ответе сохраняется предыдущий список. Если загрузка ни разу не удалась, пул остаётся пустым до следующей успешной попытки: индекс доступен, прямого fallback нет.
## Как приходят данные
+5
View File
@@ -18,6 +18,7 @@ class Settings:
live_route: Literal["direct", "proxy"] = "proxy"
proxy_list_url: str | None = field(default=None, repr=False)
proxy_list_token: str | None = field(default=None, repr=False)
proxy_list_refresh_minutes: int = 15
@classmethod
def load(cls) -> "Settings":
@@ -37,6 +38,9 @@ class Settings:
directory = values.get("MCP_DATA_DIR")
if "MCP_DATA_DIR" in values and not directory:
raise ValueError("MCP_DATA_DIR cannot be empty")
minutes = values.get("MCP_PROXY_LIST_REFRESH_MINUTES", "15")
if not minutes or not re.fullmatch(r"[0-9]{1,4}", minutes) or int(minutes) > 1440:
raise ValueError("MCP_PROXY_LIST_REFRESH_MINUTES must be an integer from 0 to 1440")
proxies = _proxies(values.get("MCP_PROXY_URLS", "[]"))
endpoint = values.get("MCP_PROXY_LIST_URL")
token = values.get("MCP_PROXY_LIST_TOKEN")
@@ -58,6 +62,7 @@ class Settings:
max_retries=int(count),
proxy_list_url=endpoint,
proxy_list_token=token,
proxy_list_refresh_minutes=int(minutes),
live_route=live_route,
)
+19 -10
View File
@@ -1,6 +1,7 @@
"""Fetch the operator's proxy inventory once, without using publisher transports."""
"""Fetch the operator's proxy inventory without using publisher transports."""
import asyncio
from dataclasses import replace
from asyncio import sleep
from collections.abc import Awaitable, Callable
import logging
import httpx
@@ -10,10 +11,9 @@ from .config import Settings, validate_proxy_urls
_LOG = logging.getLogger(__name__)
async def resolve_proxy_list(settings: Settings) -> Settings:
if settings.live_route == "direct" or settings.proxy_list_url is None:
return settings
async def fetch_proxy_list(settings: Settings) -> tuple[str, ...] | None:
if settings.live_route != "proxy" or not settings.proxy_list_url:
return None
try:
async with asyncio.timeout(5), httpx.AsyncClient(trust_env=False, follow_redirects=False) as client:
headers = {"Authorization": f"Bearer {settings.proxy_list_token}", "Accept": "text/plain", "Accept-Encoding": "identity"}
@@ -27,9 +27,18 @@ async def resolve_proxy_list(settings: Settings) -> Settings:
entries = [s for line in data.decode("utf-8-sig").splitlines() if (s := line.strip())]
if not 1 <= len(entries) <= 256:
raise ValueError("invalid proxy list size")
proxies = validate_proxy_urls(entries)
return validate_proxy_urls(entries)
except (httpx.HTTPError, httpx.InvalidURL, TimeoutError, ValueError):
# The response, URL and exception can contain credentials. Never print them.
_LOG.warning("proxy_list unavailable; live proxy pool disabled until restart")
proxies = ()
return replace(settings, proxies=proxies, proxy_list_url=None, proxy_list_token=None)
_LOG.warning("proxy_list unavailable; retaining existing pool")
return None
async def refresh_proxy_list(settings: Settings, update: Callable[[tuple[str, ...]], Awaitable[None]]) -> None:
if not settings.proxy_list_refresh_minutes or settings.live_route != "proxy" or not settings.proxy_list_url:
return
while True:
await sleep(60 * settings.proxy_list_refresh_minutes)
proxies = await fetch_proxy_list(settings)
if proxies is not None:
await update(proxies)
+12 -2
View File
@@ -11,7 +11,7 @@ from mcp.server.mcpserver.exceptions import ToolError
from pydantic import StringConstraints
from .config import Settings
from .proxy_list import resolve_proxy_list
from .proxy_list import fetch_proxy_list, refresh_proxy_list
from .models import AdvisoryResult, AssetFacts, SearchPage
from .search import Search
from .store import Store
@@ -38,13 +38,23 @@ def build_server(settings: Settings) -> MCPServer:
store = Store(settings.data_dir)
await store.open()
stack.push_async_callback(store.close)
http = await stack.enter_async_context(HttpClients(await resolve_proxy_list(settings), store))
http = await stack.enter_async_context(HttpClients(settings, store))
inventory = settings.live_route == "proxy" and settings.proxy_list_url is not None
if inventory:
proxies = await fetch_proxy_list(settings)
if proxies is not None:
await http.update_proxies(proxies)
async with asyncio.TaskGroup() as group:
background = group.create_task(Sync(store, http.index).run(), name="feed-sync")
refresh = None
if inventory and settings.proxy_list_refresh_minutes:
refresh = group.create_task(refresh_proxy_list(settings, http.update_proxies), name="proxy-list")
try:
yield Search(store, http.live)
finally:
background.cancel()
if refresh is not None:
refresh.cancel()
server = AdvisoryServer("vuln-mcp", lifespan=lifespan, instructions=(
"Search published advisories and remediation. A partial result is not a clean bill of health. "
+61 -11
View File
@@ -314,15 +314,50 @@ class _Route:
client: httpx.AsyncClient
proxy: tuple[str, int] | None = None
unhealthy_until: float = 0.0
in_flight: int = 0
retired: bool = False
def healthy(self) -> bool:
return self.unhealthy_until <= monotonic()
class _ProxyPool:
def __init__(self, routes: tuple[_Route, ...]) -> None:
self.routes = routes
def __init__(self) -> None:
self.routes: tuple[_Route, ...] = ()
self._by_url: dict[str, _Route] = {}
self._next = 0
self._serial = 0
async def replace(self, urls: tuple[str, ...]) -> None:
if tuple(self._by_url) == urls:
return
updated: dict[str, _Route] = {}
added: list[_Route] = []
try:
for url in urls:
route = self._by_url.get(url)
if route is None:
address = _proxy_address(url)
route = _Route(f"proxy:{self._serial}", httpx.AsyncClient(proxy=url, trust_env=False), address)
self._serial += 1
added.append(route)
updated[url] = route
except Exception:
for route in added:
await route.client.aclose()
raise
# No awaits during the swap: new sends see either the old or the new list.
following = self.routes[self._next] if self.routes else None
removed = [route for url, route in self._by_url.items() if url not in updated]
self._by_url = updated
self.routes = tuple(updated.values())
self._next = next((i for i, route in enumerate(self.routes) if route is following), 0)
for route in removed:
route.retired = True
idle = [route.client for route in removed if not route.in_flight]
for client in idle:
await client.aclose()
def take(self) -> _Route:
for offset in range(len(self.routes)):
@@ -457,15 +492,21 @@ class _Sender:
try:
async with self.gate.slot(source, live, deadline):
if isinstance(routing, _ProxyPool):
if route is None:
if route is None or route.retired:
route = routing.take()
elif not route.healthy():
raise _Retry(HttpError("proxy_unavailable"))
if route is None:
raise HttpError("proxy_unavailable")
response = await self._send(
source, route, url, method, body, headers, limit, path, live=live
)
route.in_flight += 1
try:
response = await self._send(
source, route, url, method, body, headers, limit, path, live=live
)
finally:
route.in_flight -= 1
if route.retired and not route.in_flight:
await _finish(route.client.aclose())
if response.status == 304 and not allow_304:
if replayed_304:
raise HttpError("invalid_data")
@@ -721,6 +762,17 @@ class HttpClients:
self._stack = AsyncExitStack()
self.live: LiveHttp
self.index: IndexHttp
self._pool: _ProxyPool | None = None
async def update_proxies(self, urls: tuple[str, ...]) -> None:
if self._pool is None:
raise RuntimeError("no live proxy pool")
try:
await _finish(self._pool.replace(urls))
except (ValueError, httpx.InvalidURL):
# A malformed provider URL must not stop the server or expose credentials.
import logging
logging.getLogger(__name__).warning("proxy_list invalid; retaining existing pool")
async def __aenter__(self) -> HttpClients:
async with AsyncExitStack() as opening:
@@ -730,11 +782,9 @@ class HttpClients:
live_direct = await opening.enter_async_context(httpx.AsyncClient(proxy=None, trust_env=False))
routing = _Route("direct", live_direct)
else:
routes = []
for ordinal, proxy in enumerate(self._settings.proxies):
client = await opening.enter_async_context(httpx.AsyncClient(proxy=proxy, trust_env=False))
routes.append(_Route(f"proxy:{ordinal}", client, _proxy_address(proxy)))
routing = _ProxyPool(tuple(routes))
self._pool = routing = _ProxyPool()
opening.push_async_callback(routing.replace, ())
await routing.replace(self._settings.proxies)
self._stack = opening.pop_all()
sender = _Sender(_PublisherGate(self._store), self._settings.max_retries)
self.live = LiveHttp(sender, routing)
+17
View File
@@ -7,6 +7,7 @@ from vuln_mcp.config import Settings
def clean_env(monkeypatch):
for name in ("MCP_ENV_FILE", "MCP_LIVE_ROUTE", "MCP_PROXY_URLS", "MCP_PROXY_LIST_URL", "MCP_PROXY_LIST_TOKEN", "MCP_HTTP_MAX_RETRIES", "MCP_DATA_DIR"):
monkeypatch.delenv(name, raising=False)
monkeypatch.delenv("MCP_PROXY_LIST_REFRESH_MINUTES", raising=False)
def test_env_file_only_when_explicit(tmp_path, monkeypatch):
@@ -68,3 +69,19 @@ def test_explicit_direct_still_validates_proxy_configuration(monkeypatch):
monkeypatch.setenv("MCP_PROXY_URLS", "invalid")
with pytest.raises(ValueError, match="Invalid MCP_PROXY_URLS"):
Settings.load()
def test_configurable_inventory_interval(tmp_path, monkeypatch):
path = tmp_path / '.env'
path.write_text('MCP_PROXY_LIST_REFRESH_MINUTES=10\n')
monkeypatch.setenv('MCP_ENV_FILE', str(path))
assert Settings.load().proxy_list_refresh_minutes == 10
monkeypatch.setenv('MCP_PROXY_LIST_REFRESH_MINUTES', '0')
assert Settings.load().proxy_list_refresh_minutes == 0
@pytest.mark.parametrize('value', ['-1', '0.5', '1441', ''])
def test_inventory_interval_rejects_invalid_values(monkeypatch, value):
monkeypatch.setenv('MCP_PROXY_LIST_REFRESH_MINUTES', value)
with pytest.raises(ValueError, match='MCP_PROXY_LIST_REFRESH_MINUTES'):
Settings.load()
+35 -8
View File
@@ -5,7 +5,7 @@ from dataclasses import replace
import pytest
from vuln_mcp.config import Settings
from vuln_mcp.proxy_list import resolve_proxy_list
from vuln_mcp.proxy_list import fetch_proxy_list, refresh_proxy_list
@pytest.fixture
@@ -42,10 +42,8 @@ async def test_authenticated_inventory_request_preserves_order_and_query(monkeyp
cfg = Settings.load()
assert 'fixture-token' not in repr(cfg)
direct = replace(cfg, live_route='direct')
assert await resolve_proxy_list(direct) is direct and not calls
resolved = await resolve_proxy_list(cfg)
assert resolved.proxies == ('http://one:8000', 'socks5h://two:1080')
assert resolved.proxy_list_token is None
assert await fetch_proxy_list(direct) is None and not calls
assert await fetch_proxy_list(cfg) == ('http://one:8000', 'socks5h://two:1080')
request, = calls
assert request.startswith(b'GET /v1/proxies?proxy_type=http&format=proxy-url-list-txt HTTP/1.1\r\n')
assert b'\r\nauthorization: bearer fixture-token\r\n' in request.lower()
@@ -57,8 +55,8 @@ async def test_authenticated_inventory_request_preserves_order_and_query(monkeyp
async def test_inventory_failure_disables_pool_not_privacy(tmp_path, caplog, status, body):
async with inventory(body, status) as (url, calls):
cfg = Settings(tmp_path, proxy_list_url=url, proxy_list_token='fixture-token')
resolved = await resolve_proxy_list(cfg)
assert len(calls) == 1 and resolved.proxies == () and resolved.live_route == 'proxy'
assert await fetch_proxy_list(cfg) is None
assert len(calls) == 1
assert 'proxy_list unavailable' in caplog.text
assert 'fixture-token' not in caplog.text and 'sensitive-content' not in caplog.text
@@ -68,5 +66,34 @@ async def test_inventory_redirect_does_not_forward_token(tmp_path):
async with inventory(b'http://unexpected') as (target, received):
async with inventory(b'', '302 Found', f'Location: {target}\r\n'.encode()) as (url, _):
cfg = Settings(tmp_path, proxy_list_url=url, proxy_list_token='fixture-token')
assert (await resolve_proxy_list(cfg)).proxies == ()
assert await fetch_proxy_list(cfg) is None
assert received == []
@pytest.mark.anyio
async def test_periodic_refresh_keeps_last_success_then_recovers(tmp_path, monkeypatch):
results = iter([('http://first',), None, ('https://second',)])
delays, installed = [], []
async def tick(seconds):
delays.append(seconds)
if len(delays) == 4:
raise asyncio.CancelledError
async def fetch(_):
return next(results)
async def install(urls):
installed.append(urls)
monkeypatch.setattr('vuln_mcp.proxy_list.sleep', tick)
monkeypatch.setattr('vuln_mcp.proxy_list.fetch_proxy_list', fetch)
cfg = Settings(tmp_path, proxy_list_url='https://inventory.test/list', proxy_list_refresh_minutes=7)
for disabled in (replace(cfg, live_route='direct'), replace(cfg, proxy_list_url=None),
replace(cfg, proxy_list_refresh_minutes=0)):
await refresh_proxy_list(disabled, install)
assert not delays
with pytest.raises(asyncio.CancelledError):
await refresh_proxy_list(cfg, install)
assert delays == [420] * 4
assert installed == [('http://first',), ('https://second',)]
+27
View File
@@ -104,6 +104,33 @@ async def status(operation, expected: str) -> HttpError:
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 = []