From aed9685cf77e42af2903acf41640a01dcfe3ecea Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 08:35:54 +0000 Subject: [PATCH 01/31] Run approved MCP reads in a separate source worker Signed-off-by: zlareb1 (cherry picked from commit b1fa6bb7fad061a58f264bc372417829394365df) Signed-off-by: zlareb1 --- .github/workflows/mcp-source-worker.yml | 44 + source_worker/.dockerignore | 5 + source_worker/Dockerfile | 9 + source_worker/loom_source_worker/__init__.py | 1 + .../loom_source_worker/_mcp_transport.py | 80 ++ .../loom_source_worker/credential_store.py | 161 +++ .../loom_source_worker/direct_backend.py | 145 ++ .../loom_source_worker/http_service.py | 81 ++ source_worker/loom_source_worker/main.py | 343 +++++ .../loom_source_worker/mcp_client.py | 1211 +++++++++++++++++ source_worker/loom_source_worker/protocol.py | 140 ++ .../loom_source_worker/read_service.py | 182 +++ source_worker/pyproject.toml | 29 + source_worker/tests/test_credential_store.py | 122 ++ source_worker/tests/test_main.py | 224 +++ source_worker/tests/test_mcp_client.py | 395 ++++++ source_worker/tests/test_protocol.py | 116 ++ source_worker/tests/test_protocol_servers.py | 179 +++ source_worker/tests/test_read_service.py | 147 ++ 19 files changed, 3614 insertions(+) create mode 100644 .github/workflows/mcp-source-worker.yml create mode 100644 source_worker/.dockerignore create mode 100644 source_worker/Dockerfile create mode 100644 source_worker/loom_source_worker/__init__.py create mode 100644 source_worker/loom_source_worker/_mcp_transport.py create mode 100644 source_worker/loom_source_worker/credential_store.py create mode 100644 source_worker/loom_source_worker/direct_backend.py create mode 100644 source_worker/loom_source_worker/http_service.py create mode 100644 source_worker/loom_source_worker/main.py create mode 100644 source_worker/loom_source_worker/mcp_client.py create mode 100644 source_worker/loom_source_worker/protocol.py create mode 100644 source_worker/loom_source_worker/read_service.py create mode 100644 source_worker/pyproject.toml create mode 100644 source_worker/tests/test_credential_store.py create mode 100644 source_worker/tests/test_main.py create mode 100644 source_worker/tests/test_mcp_client.py create mode 100644 source_worker/tests/test_protocol.py create mode 100644 source_worker/tests/test_protocol_servers.py create mode 100644 source_worker/tests/test_read_service.py diff --git a/.github/workflows/mcp-source-worker.yml b/.github/workflows/mcp-source-worker.yml new file mode 100644 index 0000000000..b47a6e9385 --- /dev/null +++ b/.github/workflows/mcp-source-worker.yml @@ -0,0 +1,44 @@ +name: MCP source worker qualification + +on: + pull_request: + paths: + - .github/workflows/mcp-source-worker.yml + - source_worker/** + +permissions: + contents: read + +jobs: + protocol: + name: Installed external worker (${{ matrix.python }}) + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + python: ["3.12", "3.14"] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + sparse-checkout: /source_worker/ + sparse-checkout-cone-mode: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python }} + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: "0.12.19" + enable-cache: false + - name: Build and install the worker wheel + run: | + uv build --wheel source_worker --out-dir "$RUNNER_TEMP/source-worker-wheel" + uv venv "$RUNNER_TEMP/source-worker" + uv pip install --python "$RUNNER_TEMP/source-worker/bin/python" \ + "$RUNNER_TEMP/source-worker-wheel"/*.whl pytest pytest-asyncio + - name: Verify the installed worker with owned SDK servers + run: | + git rev-parse HEAD + "$RUNNER_TEMP/source-worker/bin/python" -m pytest -q source_worker/tests diff --git a/source_worker/.dockerignore b/source_worker/.dockerignore new file mode 100644 index 0000000000..4a9ddfe253 --- /dev/null +++ b/source_worker/.dockerignore @@ -0,0 +1,5 @@ +* +!Dockerfile +!pyproject.toml +!loom_source_worker/ +!loom_source_worker/*.py diff --git a/source_worker/Dockerfile b/source_worker/Dockerfile new file mode 100644 index 0000000000..bbb6c3325b --- /dev/null +++ b/source_worker/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.12-slim + +WORKDIR /opt/loom-source-worker +COPY pyproject.toml ./ +COPY loom_source_worker/ ./loom_source_worker/ +RUN pip install --no-cache-dir . + +USER 10001:10001 +ENTRYPOINT ["python", "-IBu", "-m", "loom_source_worker.main"] diff --git a/source_worker/loom_source_worker/__init__.py b/source_worker/loom_source_worker/__init__.py new file mode 100644 index 0000000000..8ec346e50c --- /dev/null +++ b/source_worker/loom_source_worker/__init__.py @@ -0,0 +1 @@ +"""Companion process for approved MCP document reads.""" diff --git a/source_worker/loom_source_worker/_mcp_transport.py b/source_worker/loom_source_worker/_mcp_transport.py new file mode 100644 index 0000000000..96b5dd9dd0 --- /dev/null +++ b/source_worker/loom_source_worker/_mcp_transport.py @@ -0,0 +1,80 @@ +"""Network and logging boundaries for the outbound MCP client.""" + +from __future__ import annotations + +import asyncio +import ipaddress +import logging +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +import dns.asyncresolver +import dns.exception + +_PRIVATE = ContextVar("mcp_private_work", default=False) +_NAT64 = ipaddress.IPv6Network("64:ff9b::/96") +_Address = ipaddress.IPv4Address | ipaddress.IPv6Address + + +class _PrivateFilter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + return not _PRIVATE.get() + + +_PRIVATE_FILTER = _PrivateFilter() + + +@contextmanager +def private_work() -> Iterator[None]: + """Drop SDK diagnostics in this context and tasks spawned from it.""" + root = logging.getLogger() + handlers = set(root.handlers) + if logging.lastResort is not None: + handlers.add(logging.lastResort) + for logger in root.manager.loggerDict.copy().values(): + if isinstance(logger, logging.Logger): + handlers.update(logger.handlers) + for handler in handlers: + handler.addFilter(_PRIVATE_FILTER) + token = _PRIVATE.set(True) + try: + yield + finally: + _PRIVATE.reset(token) + + +def _is_public(address: _Address) -> bool: + if isinstance(address, ipaddress.IPv6Address): + if address.ipv4_mapped is not None: + address = address.ipv4_mapped + elif address in _NAT64 or (1 < int(address) < 2**32): + address = ipaddress.IPv4Address(int(address) & 0xFFFFFFFF) + return address.is_global and not address.is_multicast + + +async def resolve_public_address(host: str) -> _Address | None: + """Vet all A and AAAA answers, then return one literal to pin for the session.""" + try: + addresses = [ipaddress.ip_address(host)] + except ValueError: + addresses = [] + if not addresses: + try: + resolver = dns.asyncresolver.Resolver() + answers = await asyncio.gather( + *( + resolver.resolve(host, family, search=False, raise_on_no_answer=False) + for family in ("A", "AAAA") + ), + return_exceptions=True, + ) + for answer in answers: + if isinstance(answer, asyncio.CancelledError): + raise answer + if isinstance(answer, BaseException): + return None + addresses.extend(ipaddress.ip_address(record.to_text()) for record in answer) + except (ValueError, OSError, dns.exception.DNSException): + return None + return addresses[0] if addresses and all(map(_is_public, addresses)) else None diff --git a/source_worker/loom_source_worker/credential_store.py b/source_worker/loom_source_worker/credential_store.py new file mode 100644 index 0000000000..ea043ba298 --- /dev/null +++ b/source_worker/loom_source_worker/credential_store.py @@ -0,0 +1,161 @@ +"""Read connections from a worker-owned KV v2 secret mount.""" + +from __future__ import annotations + +import math +import re +import ssl +import time +from collections.abc import Callable +from typing import Annotated, Literal +from uuid import UUID + +import httpx +from pydantic import BaseModel, ConfigDict, Field, SecretStr, ValidationError + +from .protocol import ConnectionBinding +from .read_service import ReadFailure + +_RESPONSE_BYTES = 32_768 +_MAX_TOKEN_BYTES = 8192 + + +class CredentialRecord(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True, strict=True) + + binding: ConnectionBinding + state: Literal["active", "revoked"] + auth: Literal["anonymous", "bearer"] + audience: Annotated[str, Field(min_length=1, max_length=2048)] | None = None + token: SecretStr | None = None + expires_at: Annotated[int, Field(ge=1, le=2**63 - 1)] | None = None + + +class _Metadata(BaseModel): + model_config = ConfigDict(strict=True, hide_input_in_errors=True) + + version: Annotated[int, Field(ge=1, le=2**63 - 1)] + destroyed: bool + deletion_time: str + + +class _Data(BaseModel): + model_config = ConfigDict(strict=True, hide_input_in_errors=True) + + data: CredentialRecord + metadata: _Metadata + + +class _Reply(BaseModel): + model_config = ConfigDict(strict=True, hide_input_in_errors=True) + + data: _Data + + +def _secret_token(value: str) -> bool: + return 0 < len(value) <= _MAX_TOKEN_BYTES and all(33 <= ord(char) <= 126 for char in value) + + +class VaultCredentialStore: + def __init__( + self, + *, + origin: str, + mount: str, + worker_id: UUID, + token: Callable[[], SecretStr], + timeout_seconds: float, + tls: ssl.SSLContext | None = None, + _transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + target = httpx.URL(origin) + if ( + not origin.isascii() + or target.scheme != "https" + or not target.host + or target.userinfo + or target.raw_path != b"/" + or target.fragment + or not re.fullmatch(r"[a-z][a-z0-9_-]{0,62}", mount) + ): + raise ValueError("invalid credential backend origin or mount") + if not math.isfinite(timeout_seconds) or not 0 < timeout_seconds <= 10: + raise ValueError("invalid credential backend deadline") + if tls is not None and (tls.verify_mode != ssl.CERT_REQUIRED or not tls.check_hostname): + raise ValueError("credential backend TLS verification is required") + self._url = target.copy_with(path=f"/v1/{mount}/data/{worker_id}/") + self._worker_id = worker_id + self._token = token + self._client = httpx.AsyncClient( + trust_env=False, + follow_redirects=False, + verify=tls or True, + transport=_transport, + timeout=httpx.Timeout(timeout_seconds), + ) + + async def aclose(self) -> None: + await self._client.aclose() + + async def _download(self, url: httpx.URL) -> bytearray: + try: + token = self._token().get_secret_value() + except OSError: + raise ReadFailure("unavailable") from None + if not _secret_token(token): + raise ReadFailure("unavailable") + headers = { + "X-Vault-Token": token, + "Accept": "application/json", + "Accept-Encoding": "identity", + } + output = bytearray() + try: + async with self._client.stream("GET", url, headers=headers) as response: + if response.status_code == 404: + raise ReadFailure("reconnect") + if response.status_code in {401, 403}: + raise ReadFailure("denied") + if ( + response.status_code != 200 + or response.headers.get("content-encoding", "identity") != "identity" + ): + raise ReadFailure("unavailable") + async for chunk in response.aiter_raw(): + if len(output) + len(chunk) > _RESPONSE_BYTES: + raise ReadFailure("unavailable") + output.extend(chunk) + except httpx.TimeoutException: + raise ReadFailure("timeout") from None + except httpx.HTTPError: + raise ReadFailure("unavailable") from None + return output + + async def get(self, connection_id: UUID) -> CredentialRecord: + payload = await self._download(self._url.copy_with(path=f"{self._url.path}{connection_id}")) + try: + envelope = _Reply.model_validate_json(payload).data + except ValidationError: + raise ReadFailure("unavailable") from None + record, metadata = envelope.data, envelope.metadata + if ( + record.binding.worker_id != self._worker_id + or record.binding.connection_id != connection_id + or record.binding.generation != metadata.version + ): + raise ReadFailure("denied") + if record.state != "active" or metadata.destroyed or metadata.deletion_time: + raise ReadFailure("denied") + if record.auth == "anonymous": + attributes = (record.token, record.audience, record.expires_at) + if any(value is not None for value in attributes): + raise ReadFailure("denied") + elif ( + record.token is None + or not _secret_token(record.token.get_secret_value()) + or record.audience is None + or record.expires_at is None + or record.expires_at <= time.time() + ): + raise ReadFailure("reconnect") + return record diff --git a/source_worker/loom_source_worker/direct_backend.py b/source_worker/loom_source_worker/direct_backend.py new file mode 100644 index 0000000000..0f3a3fb8f8 --- /dev/null +++ b/source_worker/loom_source_worker/direct_backend.py @@ -0,0 +1,145 @@ +"""A worker backend for operator-approved direct MCP accounts.""" + +from __future__ import annotations + +import copy +import hashlib +import json +from dataclasses import asdict, dataclass, replace +from typing import Protocol +from uuid import UUID + +import httpx + +from .credential_store import CredentialRecord +from .mcp_client import MCPBearer, MCPSourceClient, MCPSourceConfig, MCPSourceError +from .protocol import ConnectionBinding, ReadBinding +from .read_service import BoundReader, CurrentAccess, Document, FailureCode, ReadFailure + + +@dataclass(frozen=True, repr=False) +class ApprovedProfile: + config: MCPSourceConfig + organizations: tuple[str, ...] + link_origins: tuple[str, ...] = () + + def __post_init__(self) -> None: + if self.config.approved_resource_ids or not self.organizations: + raise ValueError("profile must scope the tenant without selecting resources") + if any(_link_origin(value) != value for value in self.link_origins): + raise ValueError("invalid approved link origin") + + @property + def digest(self) -> str: + payload = json.dumps( + asdict(self), allow_nan=False, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + return hashlib.sha256(payload).hexdigest() + + +def _link_origin(value: str) -> str | None: + if not value or not value.isascii() or any(not 33 <= ord(char) <= 126 for char in value): + return None + try: + url = httpx.URL(value) + except httpx.InvalidURL: + return None + if url.scheme != "https" or not url.host or url.userinfo: + return None + return str(url.copy_with(path="/", query=None, fragment=None)).removesuffix("/") + + +class CredentialStore(Protocol): + async def get(self, connection_id: UUID) -> CredentialRecord: ... + + +@dataclass(frozen=True, repr=False) +class _MCPReader: + record: CredentialRecord + profile: ApprovedProfile + resource_id: str + + @property + def binding(self) -> ConnectionBinding: + return self.record.binding + + async def read_exact(self, resource_id: str, *, authorize: CurrentAccess) -> Document: + if resource_id != self.resource_id: + raise ReadFailure("denied") + config = replace(self.profile.config, approved_resource_ids=(self.resource_id,)) + bearer = self._bearer() + if bearer is not None and bearer.token in resource_id: + raise ReadFailure("denied") + refusal: ReadFailure | None = None + + async def require_current() -> None: + nonlocal refusal + try: + await authorize() + except ReadFailure as error: + refusal = error + raise MCPSourceError("denied") from None + + try: + async with MCPSourceClient(config, bearer, validate_access=require_current) as client: + await client.discover() + item = await client.read(self.resource_id) + receipt = item.receipt + if ( + receipt is None + or not receipt.identity_verified + or receipt.requested_id != self.resource_id + or receipt.config_sha256 != client.config_sha256 + ): + raise ReadFailure("denied") + except MCPSourceError as error: + if refusal is not None: + raise refusal from None + mapped: dict[str, FailureCode] = { + "denied": "denied", + "reconnect": "reconnect", + "timeout": "timeout", + } + raise ReadFailure(mapped.get(error.code, "unsupported")) from None + returned = (item.text, item.title, item.uri, item.mime_type, item.revision or "") + if bearer is not None and any(bearer.token in value for value in returned): + raise ReadFailure("unsupported") + link = item.uri if _link_origin(item.uri) in self.profile.link_origins else None + return Document( + item.resource_id, item.title, item.text, item.revision, link, item.mime_type + ) + + def _bearer(self) -> MCPBearer | None: + if self.record.auth == "anonymous": + if self.profile.config.bearer_audience is not None: + raise ReadFailure("denied") + return None + if self.record.token is None or self.record.audience != self.profile.config.bearer_audience: + raise ReadFailure("denied") + assert self.record.audience is not None + return MCPBearer(self.record.token.get_secret_value(), self.record.audience) + + +class DirectBackend: + def __init__(self, store: CredentialStore, profiles: tuple[ApprovedProfile, ...]) -> None: + if not 1 <= len(profiles) <= 4096: + raise ValueError("invalid worker profile count") + self._store = store + self._profiles = {profile.digest: profile for profile in copy.deepcopy(profiles)} + if len(self._profiles) != len(profiles): + raise ValueError("duplicate worker profile") + + async def _resolve(self, binding: ReadBinding) -> tuple[CredentialRecord, ApprovedProfile]: + profile = self._profiles.get(binding.profile_digest) + if profile is None or binding.org not in profile.organizations: + raise ReadFailure("denied") + record = await self._store.get(binding.connection_id) + return record, profile + + async def resolve(self, binding: ReadBinding) -> BoundReader: + record, profile = await self._resolve(binding) + return _MCPReader(record, profile, binding.resource_id) + + async def current(self, binding: ReadBinding) -> ConnectionBinding: + record, _ = await self._resolve(binding) + return record.binding diff --git a/source_worker/loom_source_worker/http_service.py b/source_worker/loom_source_worker/http_service.py new file mode 100644 index 0000000000..6fcad13563 --- /dev/null +++ b/source_worker/loom_source_worker/http_service.py @@ -0,0 +1,81 @@ +"""Private HTTP callback for Loom's transient reads.""" + +from __future__ import annotations + +import asyncio +from dataclasses import asdict +from typing import Literal + +from starlette.applications import Starlette +from starlette.requests import Request +from starlette.responses import JSONResponse, Response +from starlette.routing import Route + +from .read_service import ReadFailure, ReadService + +_CACHE_HEADERS = {"Cache-Control": "no-store"} +_STATUSES = { + "denied": 403, + "reconnect": 409, + "overloaded": 429, + "timeout": 504, + "unavailable": 503, + "unsupported": 422, +} + + +async def _disconnect(request: Request) -> None: + while (await request.receive())["type"] != "http.disconnect": + pass + + +def create_app(service: ReadService) -> Starlette: + async def invoke(request: Request, operation: Literal["live", "check_access"]) -> Response: + if ( + request.url.query + or request.headers.get("content-length", "0") != "0" + or "transfer-encoding" in request.headers + ): + return JSONResponse({"status": "denied"}, 400, headers=_CACHE_HEADERS) + auth = request.headers.getlist("authorization") + if len(auth) != 1 or not auth[0].startswith("Bearer "): + return JSONResponse({"status": "denied"}, 403, headers=_CACHE_HEADERS) + result = asyncio.create_task(service.execute(auth[0][7:], operation)) + disconnect = asyncio.create_task(_disconnect(request)) + try: + await asyncio.wait((result, disconnect), return_when=asyncio.FIRST_COMPLETED) + if disconnect.done(): + return Response(status_code=499, headers=_CACHE_HEADERS) + reading = result.result() + response = { + "status": "ok", + "request_id": str(reading.request_id), + "fetched_at": reading.fetched_at, + "content_sha256": reading.content_sha256, + "document": asdict(reading.document) if reading.document else None, + } + return JSONResponse(response, headers=_CACHE_HEADERS) + except ReadFailure as error: + return JSONResponse( + {"status": error.code}, _STATUSES[error.code], headers=_CACHE_HEADERS + ) + except Exception: # noqa: BLE001 — adapter failure text can expose credential or document data + return JSONResponse({"status": "unavailable"}, 503, headers=_CACHE_HEADERS) + finally: + for task in (result, disconnect): + if not task.done(): + task.cancel() + await asyncio.gather(result, disconnect, return_exceptions=True) + + async def live(request: Request) -> Response: + return await invoke(request, "live") + + async def check_access(request: Request) -> Response: + return await invoke(request, "check_access") + + return Starlette( + routes=[ + Route("/v1/live", live, methods=["POST"]), + Route("/v1/check-access", check_access, methods=["POST"]), + ] + ) diff --git a/source_worker/loom_source_worker/main.py b/source_worker/loom_source_worker/main.py new file mode 100644 index 0000000000..62e8248f76 --- /dev/null +++ b/source_worker/loom_source_worker/main.py @@ -0,0 +1,343 @@ +"""Start the companion behind a TLS proxy on a private Unix socket.""" + +from __future__ import annotations + +import fcntl +import json +import logging +import os +import re +import socket +import ssl +import stat +import sys +from collections.abc import AsyncIterator, Iterator +from contextlib import asynccontextmanager, contextmanager +from dataclasses import fields +from functools import partial +from pathlib import Path +from typing import Annotated, Any, Literal +from uuid import UUID + +import httpx +import uvicorn +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_pem_public_key +from pydantic import BaseModel, ConfigDict, Field, SecretStr +from starlette.applications import Starlette + +from .credential_store import VaultCredentialStore +from .direct_backend import ApprovedProfile, DirectBackend +from .http_service import create_app +from .mcp_client import ( + MCPBearer, + MCPDataPolicy, + MCPLimits, + MCPSourceClient, + MCPSourceConfig, + MCPSourceError, + MCPToolMapping, +) +from .read_service import ReadLimits, ReadService + +_CONFIG = Path("/etc/loom-source-worker/config.json") +_VERIFIER = Path("/etc/loom-source-worker/grant-verifier.pem") +_VAULT_CA = Path("/etc/loom-source-worker/vault-ca.pem") +_VAULT_TOKEN = Path("/run/loom-source-worker/credentials/vault-token") +_SOCKET = Path("/run/loom-source-worker/socket/worker.sock") +_CONFIG_BYTES = 2 * 1024 * 1024 +_TOKEN_BYTES = 8192 +_BACKLOG = 64 +_CERTIFICATE = rb"-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+-----END CERTIFICATE-----" + + +class StartupError(Exception): + """A startup refusal whose message contains no configuration values.""" + + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True, strict=True) + + +class _Vault(_Strict): + origin: Annotated[str, Field(min_length=1, max_length=2048)] + mount: Annotated[str, Field(pattern=r"^[a-z][a-z0-9_-]{0,62}$")] + timeout_seconds: Annotated[float, Field(gt=0, le=10, allow_inf_nan=False)] = 3 + custom_ca: bool = False + + +class _Settings(_Strict): + transport: Literal["tls_proxy_unix"] + worker_id: UUID + issuer: Annotated[str, Field(min_length=1, max_length=255)] + vault: _Vault + read_limits: ReadLimits + profiles: Annotated[tuple[ApprovedProfile, ...], Field(min_length=1, max_length=4096)] + + +def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for name, value in pairs: + if name in result: + raise ValueError("duplicate configuration field") + result[name] = value + return result + + +def _known_fields(value: Any, model: Any) -> None: + if not isinstance(value, dict) or value.keys() - {field.name for field in fields(model)}: + raise ValueError("unknown configuration field") + + +def _visible_ascii(value: str, maximum: int) -> bool: + return 0 < len(value) <= maximum and all(33 <= ord(char) <= 126 for char in value) + + +def _https_origin(value: str) -> bool: + if not _visible_ascii(value, 2048) or any(char in value for char in "%\\?#@"): + return False + url = httpx.URL(value) + return ( + url.scheme == "https" + and bool(url.host) + and (url.port is None or 1 <= url.port <= 65_535) + and url.raw_path == b"/" + and str(url).removesuffix("/") == value + ) + + +async def _deny_validation_read() -> None: + raise MCPSourceError("denied") + + +def _parse_settings(raw: bytes) -> _Settings: + try: + if not 0 < len(raw) <= _CONFIG_BYTES: + raise ValueError("configuration size") + document = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs) + if not isinstance(document, dict): + raise ValueError("configuration object") + profiles = document.get("profiles") + if not isinstance(profiles, list) or not 1 <= len(profiles) <= 4096: + raise ValueError("profile count") + _known_fields(document.get("read_limits"), ReadLimits) + for profile in profiles: + _known_fields(profile, ApprovedProfile) + source = profile.get("config") + _known_fields(source, MCPSourceConfig) + if "approved_resource_ids" in source: + raise ValueError("profile cannot select resources") + for name, model in (("limits", MCPLimits), ("data_policy", MCPDataPolicy)): + if name in source: + _known_fields(source[name], model) + for name in ("read", "search"): + if source.get(name) is not None: + _known_fields(source[name], MCPToolMapping) + settings = _Settings.model_validate_json(json.dumps(document, allow_nan=False)) + if ( + settings.worker_id.int == 0 + or not _visible_ascii(settings.issuer, 255) + or not _https_origin(settings.vault.origin) + ): + raise ValueError("invalid worker identity or Vault origin") + digests = set() + for profile in settings.profiles: + if ( + not 1 <= len(profile.organizations) <= 256 + or len(set(profile.organizations)) != len(profile.organizations) + or not all(_visible_ascii(org, 255) for org in profile.organizations) + or len(profile.link_origins) > 32 + or len(set(profile.link_origins)) != len(profile.link_origins) + or not all(_https_origin(origin) for origin in profile.link_origins) + ): + raise ValueError("invalid profile scope") + audience = profile.config.bearer_audience + if audience is not None and not _https_origin(audience): + raise ValueError("invalid profile audience") + credential = MCPBearer("profile-validation", audience) if audience is not None else None + client = MCPSourceClient( + profile.config, credential, validate_access=_deny_validation_read + ) + _ = client.config_sha256 + digest = profile.digest + if digest in digests: + raise ValueError("duplicate profile") + digests.add(digest) + return settings + except (ValueError, TypeError, OverflowError, RecursionError, MCPSourceError, httpx.InvalidURL): + raise StartupError("invalid worker configuration") from None + + +def _read_file(path: Path, maximum: int, *, secret: bool = False) -> bytes: + with open(path, "rb", opener=_open_nonblocking) as source: + info = os.fstat(source.fileno()) + if ( + not stat.S_ISREG(info.st_mode) + or info.st_size > maximum + or ( + secret + and ( + info.st_uid not in {0, os.geteuid()} + or stat.S_IMODE(info.st_mode) not in {0o400, 0o440} + ) + ) + ): + raise OSError("invalid worker file") + value = source.read(maximum + 1) + if not 0 < len(value) <= maximum: + raise OSError("invalid worker file size") + return value + + +def _open_nonblocking(path: str, flags: int) -> int: + return os.open(path, flags | os.O_NONBLOCK | os.O_CLOEXEC) + + +def _read_verifier(path: Path) -> Ed25519PublicKey: + try: + pem = _read_file(path, 4096).replace(b"\r\n", b"\n").removesuffix(b"\n") + key = load_pem_public_key(pem) + if not isinstance(key, Ed25519PublicKey) or pem != key.public_bytes( + Encoding.PEM, PublicFormat.SubjectPublicKeyInfo + ).removesuffix(b"\n"): + raise ValueError("invalid verifier type or encoding") + return key + except (OSError, ValueError, UnsupportedAlgorithm): + raise StartupError("invalid grant verifier file") from None + + +def _read_vault_token(path: Path) -> SecretStr: + try: + token = _read_file(path, _TOKEN_BYTES + 1, secret=True).removesuffix(b"\n").decode("ascii") + if not _visible_ascii(token, _TOKEN_BYTES): + raise ValueError("invalid token format") + return SecretStr(token) + except (OSError, ValueError): + raise OSError("invalid Vault token file") from None + + +def _vault_tls(path: Path) -> ssl.SSLContext: + try: + pem = _read_file(path, 65_536) + if not re.fullmatch(rb"\s*(?:" + _CERTIFICATE + rb"\s*)+", pem): + raise ValueError("invalid CA encoding") + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.load_verify_locations(cadata=pem.decode("ascii")) + return context + except (OSError, ValueError): + raise StartupError("invalid Vault CA file") from None + + +def _application(settings: _Settings) -> Starlette: + verifier = _read_verifier(_VERIFIER) + token = partial(_read_vault_token, _VAULT_TOKEN) + try: + token() + except OSError: + raise StartupError("invalid Vault token file") from None + store = VaultCredentialStore( + origin=settings.vault.origin, + mount=settings.vault.mount, + worker_id=settings.worker_id, + token=token, + timeout_seconds=settings.vault.timeout_seconds, + tls=_vault_tls(_VAULT_CA) if settings.vault.custom_ca else None, + ) + service = ReadService( + worker_id=settings.worker_id, + issuer=settings.issuer, + verifier=verifier, + backend=DirectBackend(store, settings.profiles), + limits=settings.read_limits, + ) + app = create_app(service) + + @asynccontextmanager + async def lifespan(_app: Starlette) -> AsyncIterator[None]: + try: + yield + finally: + await store.aclose() + + app.router.lifespan_context = lifespan + return app + + +@contextmanager +def _listen(path: Path) -> Iterator[socket.socket]: + directory = os.open(path.parent, os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) + try: + info = os.fstat(directory) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700: + raise StartupError("worker socket directory must be worker-owned mode 0700") + fcntl.flock(directory, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + prior = path.lstat() + except FileNotFoundError: + pass + else: + if not stat.S_ISSOCK(prior.st_mode) or prior.st_uid != os.geteuid(): + raise StartupError("worker socket path is occupied") + path.unlink() + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener: + listener.bind(str(path)) + try: + path.chmod(0o600) + listener.listen(_BACKLOG) + listener.setblocking(False) + yield listener + finally: + path.unlink(missing_ok=True) + finally: + os.close(directory) + + +def _server_config(app: Starlette, limits: ReadLimits) -> uvicorn.Config: + return uvicorn.Config( + app, + uds=str(_SOCKET), + workers=1, + loop="asyncio", + http="h11", + ws="none", + lifespan="on", + access_log=False, + log_config=None, + proxy_headers=False, + forwarded_allow_ips="", + server_header=False, + backlog=_BACKLOG, + limit_concurrency=limits.concurrent + _BACKLOG, + h11_max_incomplete_event_size=32_768, + timeout_keep_alive=1, + timeout_graceful_shutdown=30, + ) + + +def main() -> None: + logging.disable(sys.maxsize) + os.environ.pop("SSLKEYLOGFILE", None) + os.umask(0o077) + try: + if len(sys.argv) != 1: + raise StartupError("no arguments are accepted") + try: + raw = _read_file(_CONFIG, _CONFIG_BYTES) + except OSError: + raise StartupError("invalid worker configuration file") from None + settings = _parse_settings(raw) + app = _application(settings) + with _listen(_SOCKET) as listener: + server = uvicorn.Server(_server_config(app, settings.read_limits)) + server.run(sockets=[listener]) + if not server.started: + raise StartupError("worker listener did not start") + except StartupError as error: + raise SystemExit(f"loom-source-worker: {error}") from None + except Exception: # noqa: BLE001 — dependency errors can expose configuration or request data + raise SystemExit("loom-source-worker: worker startup or listener failed") from None + + +if __name__ == "__main__": + main() diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py new file mode 100644 index 0000000000..1359165474 --- /dev/null +++ b/source_worker/loom_source_worker/mcp_client.py @@ -0,0 +1,1211 @@ +"""Bounded reads from an explicitly configured remote MCP source. + +The caller supplies an approved connection and, if required, a preissued bearer. +It owns credential storage, authorization, and the use of the returned evidence. +""" + +from __future__ import annotations + +import asyncio +import copy +import hashlib +import json +import math +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import AsyncExitStack, ExitStack +from dataclasses import asdict, dataclass, field, replace +from datetime import timedelta +from typing import Any, Literal, TypeVar +from urllib.parse import urlsplit + +import anyio +import httpx +from jsonschema import Draft202012Validator, SchemaError +from mcp import ClientSession, types +from mcp.client.streamable_http import streamable_http_client +from mcp.shared.exceptions import McpError +from pydantic import AnyUrl +from referencing import Registry +from referencing.exceptions import Unresolvable + +from ._mcp_transport import private_work, resolve_public_address + +ErrorCode = Literal[ + "config", + "unsupported", + "denied", + "reconnect", + "protocol", + "schema", + "limit", + "timeout", + "closed", +] + + +class MCPSourceError(Exception): + """Only a fixed code may cross the client boundary.""" + + def __init__(self, code: ErrorCode) -> None: + if code not in { + "config", + "unsupported", + "denied", + "reconnect", + "protocol", + "schema", + "limit", + "timeout", + "closed", + }: + code = "protocol" + self.code = code + super().__init__("MCP source " + code) + + +def _error_code(error: BaseException) -> ErrorCode: + if isinstance(error, MCPSourceError): + return error.code + if isinstance(error, (TimeoutError, httpx.TimeoutException)): + return "timeout" + if isinstance(error, McpError) and error.error.code == httpx.codes.REQUEST_TIMEOUT: + return "timeout" + if isinstance(error, BaseExceptionGroup): + codes = {_error_code(child) for child in error.exceptions} + priorities: tuple[ErrorCode, ...] = ( + "denied", + "reconnect", + "limit", + "timeout", + "schema", + "unsupported", + "closed", + ) + for code in priorities: + if code in codes: + return code + return "protocol" + + +def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = True) -> None: + if failure is not None: + raise MCPSourceError(failure) + if not active: + raise MCPSourceError("closed") + if asyncio.get_running_loop().time() >= deadline: + raise MCPSourceError("timeout") + + +def _check_response(method: str, response: httpx.Response) -> None: + status = response.status_code + if status == 401: + raise MCPSourceError("reconnect") + if response.is_redirect or status == 403: + raise MCPSourceError("denied") + if status == 405 and method in {"GET", "DELETE"}: + return + if method == "DELETE": + if status not in {200, 204}: + raise MCPSourceError("protocol") + return + if method == "POST" and status == 202: + return + if status != 200: + raise MCPSourceError("protocol") + media = response.headers.get("content-type", "").partition(";")[0].strip().lower() + allowed = ( + {"text/event-stream"} if method == "GET" else {"application/json", "text/event-stream"} + ) + if media not in allowed: + raise MCPSourceError("protocol") + + +@dataclass(frozen=True) +class MCPLimits: + timeout_seconds: float = 30 + request_seconds: float = 10 + max_pages: int = 8 + max_results: int = 100 + max_content_bytes: int = 1_000_000 + max_wire_bytes: int = 4_000_000 + max_requests: int = 64 + + def __post_init__(self) -> None: + for value, ceiling in ((self.timeout_seconds, 120), (self.request_seconds, 30)): + if ( + type(value) not in (int, float) + or not math.isfinite(value) + or not 0 < value <= ceiling + ): + raise MCPSourceError("config") + for value, ceiling in ( + (self.max_pages, 32), + (self.max_results, 1000), + (self.max_content_bytes, 4_000_000), + (self.max_wire_bytes, 16_000_000), + (self.max_requests, 256), + ): + if type(value) is not int or not 0 < value <= ceiling: + raise MCPSourceError("config") + + +@dataclass(frozen=True) +class MCPDataPolicy: + """Per-connection parser caps; callers may lower but not raise the ceilings.""" + + max_nodes: int = 4096 + max_depth: int = 16 + max_items: int = 1000 + max_string_bytes: int = 1_000_000 + + def __post_init__(self) -> None: + for value, ceiling in ( + (self.max_nodes, 4096), + (self.max_depth, 16), + (self.max_items, 1000), + (self.max_string_bytes, 1_000_000), + ): + if type(value) is not int or not 0 < value <= ceiling: + raise MCPSourceError("config") + + +@dataclass(frozen=True, repr=False) +class MCPBearer: + token: str + audience: str + + +@dataclass(frozen=True, repr=False) +class MCPToolMapping: + name: str + input_schema: dict[str, Any] + output_schema: dict[str, Any] + argument_name: str + fixed_arguments: dict[str, Any] = field(default_factory=dict) + items_path: tuple[str, ...] = () + id_path: tuple[str, ...] = ("id",) + title_path: tuple[str, ...] | None = ("title",) + text_path: tuple[str, ...] | None = ("text",) + uri_path: tuple[str, ...] | None = ("uri",) + revision_path: tuple[str, ...] | None = None + cursor_argument: str | None = None + next_cursor_path: tuple[str, ...] | None = None + result_format: Literal["structured", "json_text", "text"] = "structured" + require_output_schema: bool = True + + +@dataclass(frozen=True, repr=False) +class MCPSourceConfig: + endpoint: str + bearer_audience: str | None = None + approved_tools: tuple[str, ...] = () + search: MCPToolMapping | None = None + read: MCPToolMapping | None = None + limits: MCPLimits = field(default_factory=MCPLimits) + approved_resource_ids: tuple[str, ...] = () + data_policy: MCPDataPolicy = field(default_factory=MCPDataPolicy) + + +@dataclass(frozen=True, repr=False) +class MCPEvidence: + resource_id: str + uri: str + title: str + text: str = "" + mime_type: str = "text/plain" + revision: str | None = None + receipt: MCPReadReceipt | None = None + + +@dataclass(frozen=True, repr=False) +class MCPReadReceipt: + operation: Literal["resources/read", "tools/call"] + requested_id: str + content_sha256: str + config_sha256: str + identity_verified: bool = True + + +@dataclass(frozen=True, repr=False) +class MCPPage: + items: tuple[MCPEvidence, ...] + next_cursor: str | None + complete: bool + + +@dataclass(frozen=True) +class MCPDiscovery: + resources: bool + tools: tuple[str, ...] + + +def _json(value: Any, maximum: int) -> bytes: + try: + encoded = json.dumps( + value, ensure_ascii=True, allow_nan=False, separators=(",", ":"), sort_keys=True + ).encode() + except (ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + if len(encoded) > maximum: + raise MCPSourceError("limit") + return encoded + + +def _string(value: Any, maximum: int = 2048, *, empty: bool = False) -> str: + if not isinstance(value, str) or (not value and not empty): + raise MCPSourceError("schema") + if len(value.encode()) > maximum or any(ord(c) < 32 or ord(c) == 127 for c in value): + raise MCPSourceError("limit") + return value + + +def _endpoint_url(url: str) -> httpx.URL: + try: + _string(url, 2048) + parts = urlsplit(url) + if ( + parts.scheme != "https" + or not parts.hostname + or parts.username is not None + or parts.password is not None + or "?" in url + or "#" in url + or "\\" in url + or "%" in url + or any(c.isspace() for c in url) + or parts.port == 0 + or any(p in (".", "..") for p in parts.path.split("/")) + ): + raise MCPSourceError("config") + return httpx.URL(url) + except (httpx.InvalidURL, ValueError, UnicodeError): + raise MCPSourceError("config") from None + + +def _origin(url: str) -> tuple[str, str, int]: + endpoint = _endpoint_url(url) + return endpoint.scheme, endpoint.raw_host.decode("ascii"), endpoint.port or 443 + + +_SCHEMA_ANNOTATIONS = frozenset({"title", "description", "default", "examples"}) +_SCHEMA_KEYS = _SCHEMA_ANNOTATIONS | {"enum", "const"} +_SCHEMA_TYPE_KEYS = { + "object": {"properties", "required", "additionalProperties", "minProperties", "maxProperties"}, + "array": {"items", "maxItems", "minItems"}, + "string": {"maxLength", "minLength"}, + "integer": {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"}, + "number": {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"}, + "boolean": set(), + "null": set(), +} + + +def _bounded_data( + value: Any, maximum: int, policy: MCPDataPolicy, *, config_strings: bool = False +) -> None: + remaining = policy.max_nodes + string_maximum = min(maximum, policy.max_string_bytes) + pending = [(value, 0)] + while pending: + node, depth = pending.pop() + remaining -= 1 + if remaining < 0 or depth > policy.max_depth: + raise MCPSourceError("limit") + if isinstance(node, dict): + if len(node) > 256 or any(not isinstance(key, str) for key in node): + raise MCPSourceError("limit") + pending.extend((item, depth + 1) for pair in node.items() for item in pair) + elif isinstance(node, list): + if len(node) > policy.max_items: + raise MCPSourceError("limit") + pending.extend((item, depth + 1) for item in node) + elif isinstance(node, str): + try: + if config_strings: + _string(node, string_maximum, empty=True) + if len(node.encode()) > string_maximum: + raise MCPSourceError("limit") + except UnicodeError: + raise MCPSourceError("schema") from None + elif type(node) is int: + if node.bit_length() > 4096: + raise MCPSourceError("limit") + elif node is not None and type(node) not in (bool, float): + raise MCPSourceError("schema") + _json(value, maximum) + + +def _schema_kind(node: dict[str, Any]) -> str | None: + kind = node.get("type") + if isinstance(kind, list): + if len(kind) != 2 or "null" not in kind: + raise MCPSourceError("schema") + non_null = [item for item in kind if item != "null"] + if len(non_null) != 1: + raise MCPSourceError("schema") + kind = non_null[0] + if kind is not None and (not isinstance(kind, str) or kind not in _SCHEMA_TYPE_KEYS): + raise MCPSourceError("schema") + return kind + + +def _schema_children(node: dict[str, Any], *, root: bool = False) -> list[Any]: + keys = set(node) - ({"$defs"} if root else set()) + if "enum" in node and (not isinstance(node["enum"], list) or len(node["enum"]) > 32): + raise MCPSourceError("schema") + if "$ref" in node: + if keys - (_SCHEMA_ANNOTATIONS | {"$ref"}): + raise MCPSourceError("schema") + return [] + if "anyOf" in node: + choices = node["anyOf"] + if ( + keys - (_SCHEMA_KEYS | {"anyOf"}) + or not isinstance(choices, list) + or len(choices) != 2 + or sum(choice == {"type": "null"} for choice in choices) != 1 + ): + raise MCPSourceError("schema") + return choices + kind = _schema_kind(node) + allowed = _SCHEMA_KEYS | ({"type"} | _SCHEMA_TYPE_KEYS[kind] if kind else set()) + if keys - allowed: + raise MCPSourceError("schema") + if kind == "object": + properties = node.get("properties", {}) + additional = node.get("additionalProperties", True) + if not isinstance(properties, dict) or len(properties) > 64: + raise MCPSourceError("schema") + for name in properties: + _string(name, 128) + if type(additional) is not bool and not isinstance(additional, dict): + raise MCPSourceError("schema") + return [*properties.values(), *([additional] if isinstance(additional, dict) else [])] + return [node["items"]] if kind == "array" and "items" in node else [] + + +def _schema(schema: dict[str, Any], policy: MCPDataPolicy) -> None: + if not isinstance(schema, dict): + raise MCPSourceError("schema") + _bounded_data(schema, 16_384, policy) + definitions = schema.get("$defs", {}) + if not isinstance(definitions, dict) or len(definitions) > 64: + raise MCPSourceError("schema") + for name in definitions: + _string(name, 128) + if any(char in name for char in "/~#%"): + raise MCPSourceError("schema") + remaining = 256 + + def visit(node: Any, depth: int, active: tuple[str, ...] = (), *, root: bool = False) -> None: + nonlocal remaining + remaining -= 1 + if remaining < 0 or depth > 16 or not isinstance(node, dict): + raise MCPSourceError("schema") + children = _schema_children(node, root=root) + if "$ref" in node: + ref = node["$ref"] + if not isinstance(ref, str) or not ref.startswith("#/$defs/"): + raise MCPSourceError("schema") + name = ref[len("#/$defs/") :] + if name not in definitions or name in active: + raise MCPSourceError("schema") + visit(definitions[name], depth + 1, (*active, name)) + for child in children: + visit(child, depth + 1, active) + + for name, definition in definitions.items(): + visit(definition, 1, (name,)) + visit(schema, 0, root=True) + try: + Draft202012Validator.check_schema(schema) + except (SchemaError, ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + + +def _validate(schema: dict[str, Any], value: Any, maximum: int, policy: MCPDataPolicy) -> None: + _bounded_data(value, maximum, policy) + try: + # An explicit empty registry never retrieves external schema resources. + valid = Draft202012Validator(schema, registry=Registry()).is_valid(value) + except (Unresolvable, ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + if not valid: + raise MCPSourceError("schema") + + +_DEFAULT_DATA_POLICY = MCPDataPolicy() + + +def validate_mcp_tool_mapping( + mapping: MCPToolMapping, *, search: bool = False, policy: MCPDataPolicy = _DEFAULT_DATA_POLICY +) -> None: + """Validate an operator contract without opening a session or granting authority.""" + if type(policy) is not MCPDataPolicy: + raise MCPSourceError("config") + _string(mapping.name, 128) + _string(mapping.argument_name, 128) + _schema(mapping.input_schema, policy) + _schema(mapping.output_schema, policy) + if ( + mapping.result_format not in ("structured", "json_text", "text") + or type(mapping.require_output_schema) is not bool + or mapping.input_schema.get("type") != "object" + or mapping.output_schema.get("type") + != ("string" if mapping.result_format == "text" else "object") + or (search and mapping.result_format == "text") + or (mapping.result_format == "text" and mapping.items_path) + ): + raise MCPSourceError("config") + if mapping.result_format == "text" and ( + (mapping.id_path, mapping.title_path, mapping.text_path, mapping.uri_path) + != (("id",), ("title",), ("text",), ("uri",)) + or mapping.revision_path is not None + or mapping.next_cursor_path is not None + or mapping.cursor_argument is not None + ): + raise MCPSourceError("config") + if not isinstance(mapping.fixed_arguments, dict): + raise MCPSourceError("config") + if mapping.cursor_argument is not None: + _string(mapping.cursor_argument, 128) + _bounded_data(mapping.fixed_arguments, 16_384, policy, config_strings=True) + if mapping.argument_name in mapping.fixed_arguments or ( + mapping.cursor_argument is not None + and ( + mapping.cursor_argument == mapping.argument_name + or mapping.cursor_argument in mapping.fixed_arguments + ) + ): + raise MCPSourceError("config") + for path in ( + mapping.items_path, + mapping.id_path, + mapping.title_path, + mapping.text_path, + mapping.uri_path, + mapping.revision_path, + mapping.next_cursor_path, + ): + if path is not None: + if not isinstance(path, tuple) or len(path) > 8: + raise MCPSourceError("config") + for part in path: + _string(part, 128) + + +def _json_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + if len(pairs) > 256: + raise MCPSourceError("limit") + result = {} + for key, value in pairs: + if key in result: + raise MCPSourceError("schema") + result[key] = value + return result + + +def _nonfinite(value: str) -> None: + raise MCPSourceError("schema") + + +def _text_json(text: str, maximum: int, policy: MCPDataPolicy) -> Any: + _bounded_data(text, maximum, policy) + try: + return json.loads(text, object_pairs_hook=_json_pairs, parse_constant=_nonfinite) + except (ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + + +def _tool_value( + result: types.CallToolResult, mapping: MCPToolMapping, limits: MCPLimits, policy: MCPDataPolicy +) -> Any: + if result.isError: + raise MCPSourceError("protocol") + _bounded_data(result.model_dump(mode="json"), limits.max_wire_bytes, policy) + if any(not isinstance(block, types.TextContent) for block in result.content): + raise MCPSourceError("unsupported") + if mapping.result_format == "structured": + value: Any = result.structuredContent + if value is None: + raise MCPSourceError("protocol") + else: + if result.structuredContent is not None or len(result.content) != 1: + raise MCPSourceError("protocol") + block = result.content[0] + if not isinstance(block, types.TextContent): + raise MCPSourceError("unsupported") + value = ( + _text_json(block.text, limits.max_content_bytes, policy) + if mapping.result_format == "json_text" + else block.text + ) + _validate(mapping.output_schema, value, limits.max_content_bytes, policy) + return value + + +def _check_tool_schema(tool: types.Tool, mapping: MCPToolMapping, policy: MCPDataPolicy) -> None: + _schema(tool.inputSchema, policy) + if tool.inputSchema != mapping.input_schema: + raise MCPSourceError("schema") + if tool.outputSchema is not None: + _schema(tool.outputSchema, policy) + expected = mapping.output_schema if mapping.require_output_schema else None + if tool.outputSchema != expected: + raise MCPSourceError("schema") + + +_MISSING_CURSOR = object() + + +def _path( + value: Any, path: tuple[str, ...] | None, default: Any = "", *, optional: bool = False +) -> Any: + if path is None: + return default + for key in path: + if not isinstance(value, dict): + raise MCPSourceError("schema") + if key not in value: + if optional: + return default + raise MCPSourceError("schema") + value = value[key] + return value + + +class _LimitedStream(httpx.AsyncByteStream): + def __init__(self, stream: httpx.AsyncByteStream, owner: _PinnedTransport) -> None: + self.stream, self.owner = stream, owner + + async def __aiter__(self) -> AsyncIterator[bytes]: + try: + async with asyncio.timeout_at(self.owner.deadline): + self.owner._check_state() + async for chunk in self.stream: + self.owner.received += len(chunk) + if self.owner.received > self.owner.limits.max_wire_bytes: + raise MCPSourceError("limit") + await self.owner._authorize() + yield chunk + except Exception as error: # noqa: BLE001 — only fixed diagnostics cross the transport boundary + self.owner.failure = self.owner.failure or _error_code(error) + raise MCPSourceError(self.owner.failure) from None + + async def aclose(self) -> None: + # The SDK cancels its task group before joining HTTP stream finalizers. + with anyio.CancelScope(shield=True): + await self.stream.aclose() + + +class _PinnedTransport(httpx.AsyncBaseTransport): + def __init__( + self, + config: MCPSourceConfig, + credential: MCPBearer | None, + deadline: float, + validate_access: Callable[[], Awaitable[None]], + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self.endpoint = _endpoint_url(config.endpoint) + self.credential, self.deadline, self.limits = credential, deadline, config.limits + self.validate_access = validate_access + self.inner = ( + transport + if transport is not None + else httpx.AsyncHTTPTransport(retries=0, trust_env=False) + ) + self.received, self.requests = 0, 0 + self.target: httpx.URL | None = None + self.pin_lock = asyncio.Lock() + self.failure: ErrorCode | None = None + + def _check_state(self) -> None: + _guard_state(self.deadline, self.failure) + + async def _authorize(self) -> None: + self._check_state() + await self.validate_access() + self._check_state() + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + try: + return await self._handle(request) + except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials + self.failure = self.failure or _error_code(error) + raise MCPSourceError(self.failure) from None + + async def _handle(self, request: httpx.Request) -> httpx.Response: + response: httpx.Response | None = None + handed_off = False + try: + async with asyncio.timeout_at(self.deadline): + self._check_state() + if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: + raise MCPSourceError("denied") + self.requests += 1 + if self.requests > self.limits.max_requests: + raise MCPSourceError("limit") + await self._authorize() + if self.target is None: + async with self.pin_lock: + if self.target is None: + address = await resolve_public_address( + self.endpoint.raw_host.decode("ascii") + ) + if address is None: + raise MCPSourceError("denied") + self.target = self.endpoint.copy_with(host=str(address)) + assert self.target is not None + # Construct an allowlist of protocol headers, never propagate inbound headers. + headers = { + key: value + for key, value in request.headers.items() + if key + in { + "accept", + "content-type", + "mcp-session-id", + "mcp-protocol-version", + "last-event-id", + "mcp-method", + "mcp-name", + } + } + if any(len(v) > 2048 for v in headers.values()): + raise MCPSourceError("limit") + headers.update( + {"host": self.endpoint.netloc.decode("ascii"), "accept-encoding": "identity"} + ) + if self.credential is not None: + headers["authorization"] = "Bearer " + self.credential.token + body = await request.aread() + if len(body) > 32_768: + raise MCPSourceError("limit") + outgoing = httpx.Request( + request.method, + self.target, + headers=headers, + content=body, + extensions={ + "timeout": request.extensions.get("timeout", {}), + "sni_hostname": self.endpoint.raw_host.decode("ascii"), + }, + ) + await self._authorize() + response = await self.inner.handle_async_request(outgoing) + await self._authorize() + _check_response(request.method, response) + # Reject compression so the wire budget bounds decoded protocol bytes. + if response.headers.get("content-encoding", "identity") != "identity": + raise MCPSourceError("protocol") + if not isinstance(response.stream, httpx.AsyncByteStream): + raise MCPSourceError("protocol") + response.stream = _LimitedStream(response.stream, self) + handed_off = True + return response + except Exception as error: # noqa: BLE001 — poison the session before awaiting private failure cleanup + self.failure = self.failure or _error_code(error) + raise MCPSourceError(self.failure) from None + finally: + if response is not None and not handed_off: + # Leave the deadline scope before joining an unclaimed response's finalizer. + with anyio.CancelScope(shield=True): + await response.aclose() + + async def aclose(self) -> None: + await self.inner.aclose() + + +_T = TypeVar("_T") + + +class MCPSourceClient: + """One bounded, single-use Streamable HTTP session. Call methods sequentially. + + ``validate_access`` must return only while the caller still has authority. + It may run concurrently for protocol I/O. It can raise ``MCPSourceError('denied')`` + to revoke access. Keep outbound SDK and HTTP tracing disabled in the worker. + """ + + def __init__( + self, + config: MCPSourceConfig, + credential: MCPBearer | None, + *, + validate_access: Callable[[], Awaitable[None]], + _transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + if type(config.limits) is not MCPLimits or type(config.data_policy) is not MCPDataPolicy: + raise MCPSourceError("config") + self._config = copy.deepcopy(config) + self._test_transport = _transport + self._credential = credential + self._validate_access = validate_access + origin = _origin(config.endpoint) + if credential is None: + if config.bearer_audience is not None: + raise MCPSourceError("config") + elif ( + config.bearer_audience is None + or origin != _origin(config.bearer_audience) + or credential.audience != config.bearer_audience + or not isinstance(credential.token, str) + or not 0 < len(credential.token) <= 8192 + or any(not 33 <= ord(c) <= 126 for c in credential.token) + ): + raise MCPSourceError("config") + if len(config.approved_tools) > 2 or len(set(config.approved_tools)) != len( + config.approved_tools + ): + raise MCPSourceError("config") + mappings = [m for m in (self._config.search, self._config.read) if m is not None] + if set(config.approved_tools) != {m.name for m in mappings}: + raise MCPSourceError("config") + for mapping in mappings: + validate_mcp_tool_mapping( + mapping, search=mapping is self._config.search, policy=self._config.data_policy + ) + self._privacy: ExitStack | None = None + self._owner_task: asyncio.Task[None] | None = None + self._ready: asyncio.Future[None] | None = None + self._closing = False + self._owner_failure: ErrorCode | None = None + self._session: ClientSession | None = None + self._transport: _PinnedTransport | None = None + self._operation_failure: ErrorCode | None = None + self._deadline = 0.0 + self._discovery: MCPDiscovery | None = None + self._schema_changed = False + self._pages, self._results = 0, 0 + self._issued_cursors: set[tuple[tuple[str, str], str]] = set() + self._used_cursors: set[tuple[tuple[str, str], str]] = set() + if len(config.approved_resource_ids) > config.limits.max_results: + raise MCPSourceError("config") + self._selected_ids = frozenset( + _string(identity) for identity in config.approved_resource_ids + ) + self._resource_titles: dict[str, str] = {} + + def __repr__(self) -> str: + return "MCPSourceClient()" + + @property + def config(self) -> MCPSourceConfig: + return copy.deepcopy(self._config) + + @property + def config_sha256(self) -> str: + return hashlib.sha256(_json(asdict(self._config), 131_072)).hexdigest() + + def _with_receipt( + self, + evidence: MCPEvidence, + operation: Literal["resources/read", "tools/call"], + *, + identity_verified: bool = True, + ) -> MCPEvidence: + receipt = MCPReadReceipt( + operation, + evidence.resource_id, + hashlib.sha256(evidence.text.encode()).hexdigest(), + self.config_sha256, + identity_verified, + ) + return replace(evidence, receipt=receipt) + + def _check_state(self, *, require_session: bool = False) -> None: + owner = self._owner_task + failure = self._operation_failure or self._owner_failure + if failure is None and self._transport is not None: + failure = self._transport.failure + # The lifecycle owner may perform SDK session termination during cleanup. + lifecycle = not require_session and asyncio.current_task() is owner + active = ( + owner is not None + and not owner.done() + and (not self._closing or lifecycle) + and (not require_session or self._session is not None) + ) + _guard_state(self._deadline, failure, active=active) + + async def _authorize(self) -> None: + self._check_state() + await self._validate_access() + self._check_state() + + async def _transport_authorize(self) -> None: + try: + await self._authorize() + except MCPSourceError as error: + if ( + error.code == "closed" + and self._closing + and asyncio.current_task() is not self._owner_task + ): + # Pending SDK notifications stop without poisoning expected shutdown. + raise asyncio.CancelledError from None + raise + + async def __aenter__(self) -> MCPSourceClient: + if self._owner_task is not None or self._deadline: + raise MCPSourceError("closed") + self._privacy = ExitStack() + self._privacy.enter_context(private_work()) + loop = asyncio.get_running_loop() + self._deadline = loop.time() + self._config.limits.timeout_seconds + self._ready = loop.create_future() + self._owner_task = asyncio.create_task(self._serve_session()) + try: + await self._ready + self._check_state(require_session=True) + return self + except asyncio.CancelledError: + try: + await self._close() + except asyncio.CancelledError: + pass + finally: + self._leave_private() + raise + except Exception as error: # noqa: BLE001 — only fixed initialization failures reach callers + try: + await self._close() + finally: + self._leave_private() + raise MCPSourceError(self._owner_failure or _error_code(error)) from None + + async def _serve_session(self) -> None: + # SDK AnyIO scopes are entered and exited by this one lifecycle owner. + with private_work(): + try: + async with AsyncExitStack() as stack: + async with asyncio.timeout_at(self._deadline): + await self._initialize(stack) + assert self._ready is not None + if not self._ready.done(): + self._ready.set_result(None) + await asyncio.Future[None]() + except ( + Exception, # noqa: BLE001 — SDK lifecycle failures must remain fixed codes + asyncio.CancelledError, + ) as error: + failure = self._transport.failure if self._transport else None + expected_close = self._closing and isinstance(error, asyncio.CancelledError) + if failure is not None or not expected_close: + self._owner_failure = failure or _error_code(error) + if self._ready is not None and not self._ready.done(): + self._ready.set_exception(MCPSourceError(self._owner_failure or "closed")) + finally: + self._session = None + + async def _initialize(self, stack: AsyncExitStack) -> None: + await self._authorize() + transport = _PinnedTransport( + self._config, + self._credential, + self._deadline, + self._transport_authorize, + transport=self._test_transport, + ) + self._transport = transport + client = await stack.enter_async_context( + httpx.AsyncClient( + transport=transport, + trust_env=False, + follow_redirects=False, + timeout=httpx.Timeout(self._config.limits.request_seconds), + ) + ) + read, write, _ = await stack.enter_async_context( + streamable_http_client(self._config.endpoint, http_client=client) + ) + self._session = await stack.enter_async_context( + ClientSession( + read, + write, + read_timeout_seconds=timedelta(seconds=self._config.limits.request_seconds), + message_handler=self._message_handler, + ) + ) + result = await self._session.initialize() + self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) + await self._authorize() + + async def _close(self) -> None: + owner = self._owner_task + if owner is None: + return + if not self._closing: + self._closing = True + owner.cancel() + interrupted: asyncio.CancelledError | None = None + while not owner.done(): + try: + await asyncio.shield(owner) + except asyncio.CancelledError as error: + interrupted = interrupted or error + if not owner.cancelled(): + owner.result() + if interrupted is not None: + raise interrupted + + def _leave_private(self) -> None: + privacy, self._privacy = self._privacy, None + if privacy is not None: + privacy.close() + + async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: Any) -> None: + try: + await self._close() + failure = self._owner_failure + if error is None and failure is not None and self._operation_failure is None: + raise MCPSourceError(failure) + finally: + self._leave_private() + + async def _message_handler(self, message: Any) -> None: + if isinstance(message, types.ServerNotification) and isinstance( + message.root, types.ToolListChangedNotification + ): + self._schema_changed = True + + async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + with private_work(): + return await self._execute(action) + + async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + try: + self._check_state(require_session=True) + async with asyncio.timeout_at(self._deadline): + await self._authorize() + self._check_state(require_session=True) + assert self._session is not None + result = await action(self._session) + await self._authorize() + self._check_state(require_session=True) + return result + except ( + Exception, # Terminal refusals must drain owned HTTP work before returning. + asyncio.CancelledError, + ) as error: + if isinstance(error, asyncio.CancelledError): + code: ErrorCode = "closed" + elif isinstance(error, MCPSourceError): + code = error.code + else: + code = (self._transport.failure if self._transport else None) or _error_code(error) + code = self._operation_failure or code + self._operation_failure = code + try: + await self._close() + except asyncio.CancelledError: + if not isinstance(error, asyncio.CancelledError): + raise + if isinstance(error, asyncio.CancelledError): + raise + raise MCPSourceError(code) from None + + async def discover(self) -> MCPDiscovery: + async def action(session: ClientSession) -> MCPDiscovery: + approved = set(self._config.approved_tools) + found: set[str] = set() + cursor: str | None = None + seen: set[str] = set() + if approved: + for _ in range(self._config.limits.max_pages): + result = await session.list_tools( + params=types.PaginatedRequestParams(cursor=cursor) + ) + if len(result.tools) > self._config.limits.max_results: + raise MCPSourceError("limit") + for tool in result.tools: + if tool.name in seen: + raise MCPSourceError("schema") + seen.add(tool.name) + if tool.name not in approved: + continue + for mapping in (self._config.search, self._config.read): + if mapping is not None and mapping.name == tool.name: + _check_tool_schema(tool, mapping, self._config.data_policy) + found.add(tool.name) + if len(seen) > self._config.limits.max_results: + raise MCPSourceError("limit") + cursor = result.nextCursor + if cursor is None: + break + _string(cursor) + else: + raise MCPSourceError("limit") + if found != approved: + raise MCPSourceError("unsupported") + assert self._discovery is not None + self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) + self._schema_changed = False + return self._discovery + + return await self._run(action) + + def _page_start(self, cursor: str | None, scope: tuple[str, str]) -> None: + if cursor is not None: + _string(cursor) + key = scope, cursor + if key not in self._issued_cursors or key in self._used_cursors: + raise MCPSourceError("denied") + self._used_cursors.add(key) + self._pages += 1 + if self._pages > self._config.limits.max_pages: + raise MCPSourceError("limit") + + def _page( + self, items: list[MCPEvidence], cursor: str | None, scope: tuple[str, str] + ) -> MCPPage: + self._results += len(items) + if self._results > self._config.limits.max_results: + raise MCPSourceError("limit") + if cursor is not None: + _string(cursor) + key = scope, cursor + if key in self._issued_cursors: + raise MCPSourceError("protocol") + self._issued_cursors.add(key) + return MCPPage(tuple(items), cursor, cursor is None) + + async def list_resources(self, cursor: str | None = None) -> MCPPage: + async def action(session: ClientSession) -> MCPPage: + if self._discovery is None or not self._discovery.resources: + raise MCPSourceError("unsupported") + self._page_start(cursor, ("resources", "")) + result = await session.list_resources( + params=types.PaginatedRequestParams(cursor=cursor) + ) + items = [] + for resource in result.resources: + identity = _string(str(resource.uri)) + title = _string(resource.title or resource.name) + items.append(MCPEvidence(identity, identity, title)) + self._resource_titles[identity] = title + return self._page(items, result.nextCursor, ("resources", "")) + + return await self._run(action) + + async def _tool( + self, session: ClientSession, mapping: MCPToolMapping, value: str, cursor: str | None = None + ) -> Any: + await self.discover() + if ( + self._schema_changed + or self._discovery is None + or mapping.name not in self._discovery.tools + ): + raise MCPSourceError("schema") + arguments = dict(mapping.fixed_arguments) + arguments[mapping.argument_name] = _string(value, 4096) + if cursor is not None: + if mapping.cursor_argument is None: + raise MCPSourceError("unsupported") + arguments[mapping.cursor_argument] = cursor + _validate(mapping.input_schema, arguments, 32_768, self._config.data_policy) + # Public SDK RPC path lets independent data bounds precede schema validation. + result = await session.send_request( + types.ClientRequest( + types.CallToolRequest( + params=types.CallToolRequestParams(name=mapping.name, arguments=arguments) + ) + ), + types.CallToolResult, + ) + if self._schema_changed: + raise MCPSourceError("schema") + return _tool_value(result, mapping, self._config.limits, self._config.data_policy) + + def _evidence(self, value: Any, mapping: MCPToolMapping) -> MCPEvidence: + identity = _string(_path(value, mapping.id_path)) + title = _string(_path(value, mapping.title_path, identity)) + text = _path(value, mapping.text_path) + if not isinstance(text, str) or len(text.encode()) > self._config.limits.max_content_bytes: + raise MCPSourceError("limit") + uri = _string(_path(value, mapping.uri_path, identity)) + try: + citation = urlsplit(uri) + if citation.username is not None or citation.password is not None: + raise MCPSourceError("schema") + except ValueError: + raise MCPSourceError("schema") from None + revision = _path(value, mapping.revision_path, None) + if revision is not None: + revision = _string(revision) + return MCPEvidence(identity, uri, title, text, revision=revision) + + async def search(self, query: str, cursor: str | None = None) -> MCPPage: + async def action(session: ClientSession) -> MCPPage: + mapping = self._config.search + if mapping is None: + raise MCPSourceError("unsupported") + self._page_start(cursor, ("search", query)) + result = await self._tool(session, mapping, query, cursor) + rows = _path(result, mapping.items_path) + if not isinstance(rows, list): + raise MCPSourceError("schema") + items = [self._evidence(row, mapping) for row in rows] + next_cursor = _path(result, mapping.next_cursor_path, _MISSING_CURSOR, optional=True) + return self._page( + items, + None if next_cursor is _MISSING_CURSOR else _string(next_cursor), + ("search", query), + ) + + return await self._run(action) + + async def _read_tool(self, session: ClientSession, identity: str) -> MCPEvidence: + mapping = self._config.read + assert mapping is not None + result = await self._tool(session, mapping, identity) + if mapping.result_format == "text": + evidence = MCPEvidence(identity, identity, identity, result) + return self._with_receipt(evidence, "tools/call", identity_verified=False) + evidence = self._evidence(_path(result, mapping.items_path), mapping) + if evidence.resource_id != identity: + raise MCPSourceError("protocol") + return self._with_receipt(evidence, "tools/call") + + async def read(self, resource_id: str) -> MCPEvidence: + async def action(session: ClientSession) -> MCPEvidence: + identity = _string(resource_id) + if identity not in self._selected_ids: + raise MCPSourceError("denied") + if self._config.read is not None: + return await self._read_tool(session, identity) + if self._discovery is None or not self._discovery.resources: + raise MCPSourceError("unsupported") + result = await session.read_resource(AnyUrl(identity)) + if not result.contents or len(result.contents) > self._config.limits.max_results: + raise MCPSourceError("limit") + texts: list[str] = [] + size = 0 + mime_type = result.contents[0].mimeType or "text/plain" + for content in result.contents: + if ( + not isinstance(content, types.TextResourceContents) + or str(content.uri) != identity + ): + raise MCPSourceError("unsupported") + if (content.mimeType or "text/plain") != mime_type: + raise MCPSourceError("unsupported") + size += len(content.text.encode()) + bool(texts) + if size > self._config.limits.max_content_bytes: + raise MCPSourceError("limit") + texts.append(content.text) + return self._with_receipt( + MCPEvidence( + identity, + identity, + self._resource_titles.get(identity, identity), + "\n".join(texts), + _string(mime_type, 128), + ), + "resources/read", + ) + + return await self._run(action) diff --git a/source_worker/loom_source_worker/protocol.py b/source_worker/loom_source_worker/protocol.py new file mode 100644 index 0000000000..a2b4d01617 --- /dev/null +++ b/source_worker/loom_source_worker/protocol.py @@ -0,0 +1,140 @@ +"""Caller and selection bindings for the transient worker read channel.""" + +from __future__ import annotations + +import json +import time +from typing import Annotated, Literal +from uuid import UUID + +import jwt +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from pydantic import BaseModel, ConfigDict, Field, StringConstraints, field_validator + +_Principal = Annotated[str, StringConstraints(min_length=1, max_length=255)] +_Digest = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] +_Generation = Annotated[int, Field(ge=1, le=2**63 - 1)] +_Resource = Annotated[str, StringConstraints(min_length=1, max_length=2048)] +_MAX_GRANT_BYTES = 24_576 +_MAX_GRANT_SECONDS = 30 + + +class ReadGrantRefused(Exception): + """The worker cannot authorize this read.""" + + +class _Wire(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True, strict=True) + + +class ReadBinding(_Wire): + worker_id: UUID + org: _Principal + namespace: _Principal + source_id: UUID + selection_generation: _Generation + requester: _Principal + connection_id: UUID + connection_generation: _Generation + profile_digest: _Digest + resource_id: _Resource + + @field_validator("resource_id") + @classmethod + def _bound_resource_bytes(cls, value: str) -> str: + if len(value.encode("utf-8")) > 2048: + raise ValueError("resource identity exceeds the byte limit") + return value + + +class ReadGrant(_Wire): + version: Literal[1] = 1 + request_id: UUID + operation: Literal["live", "check_access"] + binding: ReadBinding + + +class _GrantClaims(_Wire): + iss: _Principal + aud: str + iat: int + exp: int + grant: ReadGrant + + +class ConnectionBinding(_Wire): + worker_id: UUID + org: _Principal + owner: _Principal + connection_id: UUID + generation: _Generation + profile_digest: _Digest + + def authorize(self, grant: ReadGrant) -> None: + binding = grant.binding + expected = ( + binding.worker_id, + binding.org, + binding.requester, + binding.connection_id, + binding.connection_generation, + binding.profile_digest, + ) + actual = ( + self.worker_id, + self.org, + self.owner, + self.connection_id, + self.generation, + self.profile_digest, + ) + if actual != expected: + raise ReadGrantRefused("connection binding refused") + + +def _audience(worker_id: UUID) -> str: + return f"urn:loom:source-worker:{worker_id}" + + +def issue_read_grant( + grant: ReadGrant, *, issuer: str, key: Ed25519PrivateKey, lifetime_seconds: int +) -> str: + if type(lifetime_seconds) is not int or not 1 <= lifetime_seconds <= _MAX_GRANT_SECONDS: + raise ValueError("invalid read grant lifetime") + issued_at = int(time.time()) + claims = _GrantClaims( + iss=issuer, + aud=_audience(grant.binding.worker_id), + iat=issued_at, + exp=issued_at + lifetime_seconds, + grant=grant, + ) + signed = jwt.encode(claims.model_dump(mode="json"), key, algorithm="EdDSA") + if len(signed) > _MAX_GRANT_BYTES: + raise ValueError("read grant exceeds the byte limit") + return signed + + +def verify_read_grant( + token: str, *, issuer: str, worker_id: UUID, key: Ed25519PublicKey +) -> tuple[ReadGrant, int]: + if not token or not token.isascii() or len(token) > _MAX_GRANT_BYTES: + raise ReadGrantRefused("invalid read grant") + try: + payload = jwt.decode( + token, + key, + algorithms=["EdDSA"], + issuer=issuer, + audience=_audience(worker_id), + options={"require": ["iss", "aud", "iat", "exp", "grant"], "strict_aud": True}, + ) + claims = _GrantClaims.model_validate_json(json.dumps(payload)) + if ( + not 1 <= claims.exp - claims.iat <= _MAX_GRANT_SECONDS + or claims.grant.binding.worker_id != worker_id + ): + raise ReadGrantRefused("invalid read grant") + except (jwt.PyJWTError, ValueError, OverflowError, TypeError, RecursionError): + raise ReadGrantRefused("invalid read grant") from None + return claims.grant, claims.exp diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py new file mode 100644 index 0000000000..27ac385c62 --- /dev/null +++ b/source_worker/loom_source_worker/read_service.py @@ -0,0 +1,182 @@ +"""Transient delegated reads in the source worker.""" + +from __future__ import annotations + +import asyncio +import hashlib +import math +import time +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import asynccontextmanager +from dataclasses import dataclass +from typing import Literal, Protocol +from uuid import UUID + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + +from .protocol import ConnectionBinding, ReadBinding, ReadGrantRefused, verify_read_grant + +FailureCode = Literal["denied", "reconnect", "overloaded", "timeout", "unavailable", "unsupported"] +CurrentAccess = Callable[[], Awaitable[None]] + + +class ReadFailure(Exception): + def __init__(self, code: FailureCode) -> None: + super().__init__(code) + self.code = code + + +@dataclass(frozen=True, repr=False) +class Document: + resource_id: str + title: str + text: str + revision: str | None = None + source_link: str | None = None + mime_type: str = "text/plain" + + +class BoundReader(Protocol): + @property + def binding(self) -> ConnectionBinding: ... + + async def read_exact(self, resource_id: str, *, authorize: CurrentAccess) -> Document: ... + + +class ReadBackend(Protocol): + async def resolve(self, binding: ReadBinding) -> BoundReader: ... + + async def current(self, binding: ReadBinding) -> ConnectionBinding: ... + + +@dataclass(frozen=True, repr=False) +class ReadResult: + request_id: UUID + fetched_at: int + content_sha256: str + document: Document | None + + +@dataclass(frozen=True) +class ReadLimits: + concurrent: int + concurrent_per_org: int + timeout_seconds: float + content_bytes: int + + def __post_init__(self) -> None: + if ( + type(self.concurrent) is not int + or type(self.concurrent_per_org) is not int + or not 1 <= self.concurrent_per_org <= self.concurrent <= 256 + or type(self.content_bytes) is not int + or not 1 <= self.content_bytes <= 4_000_000 + or type(self.timeout_seconds) not in (float, int) + or not math.isfinite(self.timeout_seconds) + or not 0 < self.timeout_seconds <= 30 + ): + raise ValueError("invalid worker read limits") + + +class ReadService: + def __init__( + self, + *, + worker_id: UUID, + issuer: str, + verifier: Ed25519PublicKey, + backend: ReadBackend, + limits: ReadLimits, + ) -> None: + self._worker_id = worker_id + self._issuer = issuer + self._verifier = verifier + self._backend = backend + self._limits = limits + self._total = 0 + self._by_org: dict[str, int] = {} + + @asynccontextmanager + async def _slot(self, org: str) -> AsyncIterator[None]: + if ( + self._total >= self._limits.concurrent + or self._by_org.get(org, 0) >= self._limits.concurrent_per_org + ): + raise ReadFailure("overloaded") + self._total += 1 + self._by_org[org] = self._by_org.get(org, 0) + 1 + try: + yield + finally: + self._total -= 1 + self._by_org[org] -= 1 + if not self._by_org[org]: + del self._by_org[org] + + async def execute(self, token: str, operation: Literal["live", "check_access"]) -> ReadResult: + try: + grant, expires_at = verify_read_grant( + token, issuer=self._issuer, worker_id=self._worker_id, key=self._verifier + ) + if grant.operation != operation: + raise ReadGrantRefused("operation binding refused") + binding = grant.binding + + async def require_current() -> None: + if time.time() >= expires_at: + raise ReadFailure("timeout") + current = await self._backend.current(binding) + current.authorize(grant) + if time.time() >= expires_at: + raise ReadFailure("timeout") + + async with ( + self._slot(binding.org), + asyncio.timeout(min(self._limits.timeout_seconds, expires_at - time.time())), + ): + reader = await self._backend.resolve(binding) + reader.binding.authorize(grant) + await require_current() + document = await reader.read_exact(binding.resource_id, authorize=require_current) + fetched_at = int(time.time()) + content_sha256 = self._check_document(binding, document) + await require_current() + return ReadResult( + grant.request_id, + fetched_at, + content_sha256, + document if operation == "live" else None, + ) + except TimeoutError: + raise ReadFailure("timeout") from None + except ReadGrantRefused: + raise ReadFailure("denied") from None + + def _check_document(self, binding: ReadBinding, document: Document) -> str: + if document.resource_id != binding.resource_id: + raise ReadFailure("denied") + if len(document.text) > self._limits.content_bytes: + raise ReadFailure("unsupported") + metadata = ( + (document.title, 4096), + (document.revision, 2048), + (document.source_link, 2048), + (document.mime_type, 128), + ) + for value, limit in metadata: + if value is not None and not _fits_utf8(value, limit): + raise ReadFailure("unsupported") + try: + body = document.text.encode("utf-8") + except UnicodeError: + raise ReadFailure("unsupported") from None + if not body or len(body) > self._limits.content_bytes: + raise ReadFailure("unsupported") + return hashlib.sha256(body).hexdigest() + + +def _fits_utf8(value: str, maximum: int) -> bool: + try: + return len(value) <= maximum and len(value.encode("utf-8")) <= maximum + except UnicodeError: + return False diff --git a/source_worker/pyproject.toml b/source_worker/pyproject.toml new file mode 100644 index 0000000000..7496b40115 --- /dev/null +++ b/source_worker/pyproject.toml @@ -0,0 +1,29 @@ +[project] +name = "loom-source-worker" +version = "0.1.0" +description = "External MCP source worker for Loom." +requires-python = ">=3.12" +license = { text = "Apache-2.0" } +dependencies = [ + "anyio>=4", + "cryptography>=44", + "dnspython>=2.6", + "httpx>=0.27", + "jsonschema>=4.20", + "mcp>=1.30.0,<2", + "pydantic>=2.9", + "pyjwt>=2.10", + "referencing>=0.37.0", + "starlette>=0.52", + "uvicorn>=0.34,<1", +] + +[project.scripts] +loom-source-worker = "loom_source_worker.main:main" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["loom_source_worker"] diff --git a/source_worker/tests/test_credential_store.py b/source_worker/tests/test_credential_store.py new file mode 100644 index 0000000000..21547bcf33 --- /dev/null +++ b/source_worker/tests/test_credential_store.py @@ -0,0 +1,122 @@ +import json +import time +import unittest +from collections.abc import AsyncIterator +from uuid import uuid4 + +import httpx +from loom_source_worker.credential_store import VaultCredentialStore +from loom_source_worker.protocol import ConnectionBinding +from loom_source_worker.read_service import ReadFailure +from pydantic import SecretStr + + +class _Body(httpx.AsyncByteStream): + def __init__(self, data: bytes) -> None: + self.data = data + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield self.data + + +class TestCredentialStore(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.binding = ConnectionBinding( + worker_id=uuid4(), + org="one", + owner="alice", + connection_id=uuid4(), + generation=2, + profile_digest="a" * 64, + ) + self.seen: list[httpx.Request] = [] + self.status = 200 + self.body_override: bytes | None = None + self.record = { + "binding": self.binding.model_dump(mode="json"), + "state": "active", + "auth": "bearer", + "audience": "https://source.example.test/mcp", + "token": "synthetic-source", + "expires_at": int(time.time()) + 60, + } + self.metadata = {"version": 2, "destroyed": False, "deletion_time": ""} + + async def _reply(self, request: httpx.Request) -> httpx.Response: + self.seen.append(request) + body = self.body_override + if body is None: + body = json.dumps({"data": {"data": self.record, "metadata": self.metadata}}).encode() + return httpx.Response( + self.status, + headers={"Location": "https://other.example.test"}, + stream=_Body(body), + ) + + def _store(self, origin: str = "https://backend.example.test") -> VaultCredentialStore: + return VaultCredentialStore( + origin=origin, + mount="loom-sources", + worker_id=self.binding.worker_id, + token=lambda: SecretStr("synthetic-backend"), + timeout_seconds=1, + _transport=httpx.MockTransport(self._reply), + ) + + async def test_reads_only_configured_worker_and_exact_connection_path(self) -> None: + store = self._store() + self.addAsyncCleanup(store.aclose) + credential = await store.get(self.binding.connection_id) + self.assertEqual(credential.binding, self.binding) + self.assertNotIn("synthetic-source", repr(credential)) + [request] = self.seen + self.assertEqual(request.headers["X-Vault-Token"], "synthetic-backend") + pool = f"/v1/loom-sources/data/{self.binding.worker_id}" + self.assertEqual(request.url.path, f"{pool}/{self.binding.connection_id}") + self.assertEqual(request.url.host, "backend.example.test") + self.assertNotIn("synthetic-source", str(request.url)) + + async def test_refuses_old_versions_mismatched_ids_and_deletion(self) -> None: + store = self._store() + self.addAsyncCleanup(store.aclose) + for metadata_patch in ({"version": 3}, {"destroyed": True}, {"deletion_time": "deleted"}): + original = self.metadata + self.metadata = {**original, **metadata_patch} + with self.assertRaisesRegex(ReadFailure, "^denied$"): + await store.get(self.binding.connection_id) + self.metadata = original + with self.assertRaisesRegex(ReadFailure, "^denied$"): + await store.get(uuid4()) + + async def test_distinguishes_expiry_denial_and_backend_outage(self) -> None: + store = self._store() + self.addAsyncCleanup(store.aclose) + self.record["expires_at"] = int(time.time()) - 1 + with self.assertRaisesRegex(ReadFailure, "^reconnect$"): + await store.get(self.binding.connection_id) + for status, expected in ((403, "denied"), (404, "reconnect"), (503, "unavailable")): + self.status = status + with self.assertRaisesRegex(ReadFailure, f"^{expected}$"): + await store.get(self.binding.connection_id) + + async def test_rejects_redirect_or_unbounded_secret_envelope(self) -> None: + store = self._store() + self.addAsyncCleanup(store.aclose) + self.status = 302 + with self.assertRaisesRegex(ReadFailure, "^unavailable$"): + await store.get(self.binding.connection_id) + self.assertEqual(len(self.seen), 1) + self.status = 200 + self.body_override = b" " * 32_769 + with self.assertRaisesRegex(ReadFailure, "^unavailable$"): + await store.get(self.binding.connection_id) + + def test_requires_exact_tls_origin_without_auth_or_query(self) -> None: + for origin in ( + "http://backend.example.test", + "https://privileged@backend.example.test", + "https://backend.example.test/prefix", + "https://backend.example.test?scope=other", + ): + with self.assertRaisesRegex(ValueError, "invalid credential backend"): + self._store(origin) diff --git a/source_worker/tests/test_main.py b/source_worker/tests/test_main.py new file mode 100644 index 0000000000..47261f82f0 --- /dev/null +++ b/source_worker/tests/test_main.py @@ -0,0 +1,224 @@ +import json +import ssl +from dataclasses import FrozenInstanceError +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest +from cryptography import x509 +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, +) +from loom_source_worker.main import ( + _CONFIG_BYTES, + StartupError, + _parse_settings, + _read_vault_token, + _read_verifier, + _server_config, + _vault_tls, +) +from starlette.applications import Starlette + + +@pytest.fixture +def config(): + return { + "transport": "tls_proxy_unix", + "worker_id": "83d061b4-2542-4db7-adc0-4b81b3280c08", + "issuer": "deployment-source-grants", + "vault": {"origin": "https://vault.example:8200", "mount": "worker-connections"}, + "read_limits": { + "concurrent": 8, + "concurrent_per_org": 2, + "timeout_seconds": 20, + "content_bytes": 100_000, + }, + "profiles": [ + { + "organizations": ["tenant"], + "link_origins": ["https://docs.example"], + "config": {"endpoint": "https://mcp.example/rpc"}, + } + ], + } + + +def test_resource_profile_and_transport_settings(config): + settings = _parse_settings(json.dumps(config).encode()) + assert str(settings.worker_id) == config["worker_id"] + assert settings.vault.origin == "https://vault.example:8200" + assert settings.vault.timeout_seconds == 3 + assert settings.profiles[0].organizations == ("tenant",) + assert settings.profiles[0].config.approved_resource_ids == () + with pytest.raises(FrozenInstanceError): + settings.profiles[0].config.endpoint = "https://other.example/rpc" + + transport = _server_config(Starlette(), settings.read_limits) + assert transport.uds == "/run/loom-source-worker/socket/worker.sock" + assert transport.workers == 1 + assert transport.ws == "none" + assert not transport.access_log + assert transport.log_config is None + assert not transport.proxy_headers + + +def test_mapped_read_profile_is_validated_at_startup(config): + source = config["profiles"][0]["config"] + source.update( + bearer_audience="https://mcp.example", + approved_tools=["read_document"], + read={ + "name": "read_document", + "argument_name": "id", + "input_schema": { + "type": "object", + "properties": {"id": {"type": "string"}}, + "required": ["id"], + "additionalProperties": False, + }, + "output_schema": { + "type": "object", + "properties": {"id": {"type": "string"}, "text": {"type": "string"}}, + "required": ["id", "text"], + "additionalProperties": False, + }, + "id_path": ["id"], + "title_path": None, + "uri_path": None, + }, + ) + settings = _parse_settings(json.dumps(config).encode()) + assert settings.profiles[0].config.read.id_path == ("id",) + assert len(settings.profiles[0].digest) == 64 + source["read"]["argument_nam"] = "id" + with pytest.raises(StartupError, match="^invalid worker configuration$"): + _parse_settings(json.dumps(config).encode()) + + +@pytest.mark.parametrize( + ("path", "value"), + [ + (("transport",), "http"), + (("worker_id",), "00000000-0000-0000-0000-000000000000"), + (("issuer",), "issuer\n"), + (("vault", "origin"), "http://vault.example"), + (("vault", "origin"), "https://vault.example/path"), + (("vault", "origin"), "https://vault.example?"), + (("vault", "origin"), "https://user:password@vault.example"), + (("vault", "origin"), "https://vault.example:0"), + (("vault", "origin"), "https://vault.example:65536"), + (("vault", "mount"), "connections/team"), + (("vault", "token"), "unrecognized-secret"), + (("vault", "timeout_seconds"), 11), + (("vault", "timeout_seconds"), float("nan")), + (("vault", "custom_ca"), "true"), + (("read_limits", "concurrent"), "8"), + (("read_limits", "concurrent_per_org"), 9), + (("read_limits", "extra"), 1), + (("profiles",), []), + (("profiles", 0, "organizations"), ["tenant", "tenant"]), + (("profiles", 0, "link_origins"), ["https://docs.example/path"]), + (("profiles", 0, "config", "endpoint"), "http://mcp.example/rpc"), + (("profiles", 0, "config", "bearer_audience"), "https://other.example"), + (("profiles", 0, "config", "approved_resource_ids"), []), + (("profiles", 0, "config", "approved_tools"), ["unmapped"]), + (("profiles", 0, "config", "limits"), {"max_requests": 257}), + (("profiles", 0, "config", "data_policy"), {"unknown": 1}), + ], +) +def test_refuses_invalid_configuration_without_echo(config, path, value): + target = config + for field in path[:-1]: + target = target[field] + target[path[-1]] = value + with pytest.raises(StartupError, match="^invalid worker configuration$"): + _parse_settings(json.dumps(config).encode()) + + +def test_transport_is_required_and_duplicate_profiles_are_refused(config): + transport = config.pop("transport") + with pytest.raises(StartupError, match="^invalid worker configuration$"): + _parse_settings(json.dumps(config).encode()) + config["transport"] = transport + config["profiles"].append(config["profiles"][0]) + with pytest.raises(StartupError, match="^invalid worker configuration$"): + _parse_settings(json.dumps(config).encode()) + + +@pytest.mark.parametrize( + "raw", [b'{"vault":{"origin":"a","origin":"b"}}', b"{}\xff", b" " * (_CONFIG_BYTES + 1)] +) +def test_refuses_ambiguous_or_oversize_json(raw): + with pytest.raises(StartupError, match="^invalid worker configuration$"): + _parse_settings(raw) + + +def test_worker_loads_only_a_single_public_verifier(tmp_path: Path): + path = tmp_path / "verifier.pem" + signer = Ed25519PrivateKey.generate() + public = signer.public_key().public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) + private = signer.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + path.write_bytes(public) + assert ( + _read_verifier(path).public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) == public + ) + for value in (private, public + private, b"x" * 4097): + path.write_bytes(value) + with pytest.raises(StartupError, match="^invalid grant verifier file$"): + _read_verifier(path) + with pytest.raises(StartupError, match="^invalid Vault CA file$"): + _vault_tls(path) + + +def test_custom_vault_roots_preserve_hostname_verification(tmp_path: Path): + signer = Ed25519PrivateKey.generate() + name = x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME, "test CA")]) + now = datetime.now(UTC) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(signer.public_key()) + .serial_number(1) + .not_valid_before(now - timedelta(minutes=1)) + .not_valid_after(now + timedelta(minutes=1)) + .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) + .sign(signer, None) + ) + path = tmp_path / "vault-ca.pem" + path.write_bytes(certificate.public_bytes(Encoding.PEM)) + context = _vault_tls(path) + assert context.check_hostname + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.cert_store_stats()["x509_ca"] == 1 + + +def test_vault_token_is_read_from_restricted_file_on_each_use(tmp_path: Path): + mount = tmp_path / "vault-token" + current = tmp_path / "current" + rotated = tmp_path / "rotated" + current.write_bytes(b"test-first\n") + current.chmod(0o440) + mount.symlink_to(current) + assert _read_vault_token(mount).get_secret_value() == "test-first" + rotated.write_bytes(b"test-rotated") + rotated.chmod(0o400) + rotated.replace(current) + assert _read_vault_token(mount).get_secret_value() == "test-rotated" + current.chmod(0o444) + with pytest.raises(OSError, match="^invalid Vault token file$"): + _read_vault_token(mount) + + +@pytest.mark.parametrize("raw", [b"", b"test token", b"test\nsecond", b"a" * 8193]) +def test_invalid_token_file_does_not_echo_contents(tmp_path: Path, raw: bytes): + path = tmp_path / "vault-token" + path.write_bytes(raw) + path.chmod(0o400) + with pytest.raises(OSError, match="^invalid Vault token file$"): + _read_vault_token(path) diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py new file mode 100644 index 0000000000..202e029bc8 --- /dev/null +++ b/source_worker/tests/test_mcp_client.py @@ -0,0 +1,395 @@ +from __future__ import annotations + +import asyncio +import hashlib +import ipaddress +import json +import logging +from collections.abc import AsyncIterator +from dataclasses import FrozenInstanceError, replace +from typing import Any + +import dns.asyncresolver +import httpx +import pytest +from loom_source_worker import mcp_client +from loom_source_worker._mcp_transport import resolve_public_address +from loom_source_worker.mcp_client import ( + MCPBearer, + MCPDataPolicy, + MCPLimits, + MCPSourceClient, + MCPSourceConfig, + MCPSourceError, + MCPToolMapping, + validate_mcp_tool_mapping, +) + +_ENDPOINT = "https://source.example:8443/mcp" +_AUDIENCE = "https://source.example:8443/resource" +_DOCUMENT = "mcp://fixture/document" + + +async def _authorized() -> None: + return None + + +@pytest.fixture(autouse=True) +def _no_dns(monkeypatch: pytest.MonkeyPatch) -> None: + def refuse_resolver() -> None: + pytest.fail("unexpected DNS lookup") + + monkeypatch.setattr(dns.asyncresolver, "Resolver", refuse_resolver) + + +@pytest.fixture +def pin(monkeypatch: pytest.MonkeyPatch) -> list[str]: + resolutions: list[str] = [] + + async def resolve(host: str) -> ipaddress.IPv6Address: + resolutions.append(host) + return ipaddress.IPv6Address("2600::10") + + monkeypatch.setattr(mcp_client, "resolve_public_address", resolve) + return resolutions + + +class _Source(httpx.MockTransport): + def __init__(self) -> None: + super().__init__(self.respond) + self.calls: list[tuple[httpx.Request, str]] = [] + self.tool: dict[str, Any] | None = None + self.tool_result: dict[str, Any] = {"content": []} + self.read_started = asyncio.Event() + self.read_cancelled = asyncio.Event() + self.closed = False + self.stall = False + self.redirect = False + self.content_encoding = "identity" + self.resource_text = "synthetic text" + + async def aclose(self) -> None: + self.closed = True + + async def respond(self, request: httpx.Request) -> httpx.Response: + logging.getLogger("mcp.fixture").warning("synthetic private diagnostic") + if request.method != "POST": + self.calls.append((request, request.method)) + return httpx.Response(405 if request.method == "GET" else 204) + body = json.loads(request.content) + method = body["method"] + self.calls.append((request, method)) + if method == "initialize": + if self.redirect: + return httpx.Response(307, headers={"location": "https://other.example/mcp"}) + capabilities = {"resources": {}} if self.tool is None else {"tools": {}} + result = { + "protocolVersion": body["params"]["protocolVersion"], + "capabilities": capabilities, + "serverInfo": {"name": "fixture", "version": "1"}, + } + return _json_response(body["id"], result, **{"mcp-session-id": "synthetic-session"}) + if method == "notifications/initialized": + return httpx.Response(202) + if method == "resources/list": + result = ( + {"resources": []} + if body.get("params", {}).get("cursor") == "next" + else { + "resources": [{"uri": _DOCUMENT, "name": "Synthetic document"}], + "nextCursor": "next", + } + ) + elif method == "resources/read": + self.read_started.set() + if self.stall: + try: + await asyncio.Future[None]() + finally: + self.read_cancelled.set() + result = {"contents": [{"uri": _DOCUMENT, "text": self.resource_text}]} + envelope = json.dumps({"jsonrpc": "2.0", "id": body["id"], "result": result}) + return httpx.Response( + 200, + stream=_Body(f"event: message\ndata: {envelope}\n\n".encode()), + headers={ + "content-type": "text/event-stream", + "content-encoding": self.content_encoding, + }, + ) + elif method == "tools/list": + result = {"tools": [self.tool]} + elif method == "tools/call": + result = self.tool_result + else: + pytest.fail(f"unexpected RPC: {method}") + return _json_response(body["id"], result) + + +class _Body(httpx.AsyncByteStream): + def __init__(self, content: bytes) -> None: + self.content = content + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield self.content[:64] + yield self.content[64:] + + +def _json_response(request_id: int, result: dict[str, Any], **headers: str) -> httpx.Response: + content = json.dumps({"jsonrpc": "2.0", "id": request_id, "result": result}).encode() + return httpx.Response( + 200, stream=_Body(content), headers={"content-type": "application/json", **headers} + ) + + +def _client(source: _Source, **config: Any) -> MCPSourceClient: + return MCPSourceClient( + MCPSourceConfig(_ENDPOINT, **config), None, validate_access=_authorized, _transport=source + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("status", "code"), [(401, "reconnect"), (403, "denied")]) +async def test_preserves_the_upstream_auth_refusal(status: int, code: str, pin: list[str]) -> None: + def refuse(request: httpx.Request) -> httpx.Response: + return httpx.Response(status, text="private provider diagnostic") + + client = MCPSourceClient( + MCPSourceConfig(_ENDPOINT), + None, + validate_access=_authorized, + _transport=httpx.MockTransport(refuse), + ) + with pytest.raises(MCPSourceError, match=f"^MCP source {code}$"): + async with client: + pytest.fail("authentication refusal opened a client session") + assert pin == ["source.example"] + + +@pytest.mark.asyncio +async def test_resource_read_pins_origin_and_sends_only_exact_audience_bearer( + pin: list[str], caplog: pytest.LogCaptureFixture +) -> None: + source = _Source() + config = MCPSourceConfig(_ENDPOINT, _AUDIENCE, approved_resource_ids=(_DOCUMENT,)) + with pytest.raises(MCPSourceError, match="^MCP source config$"): + MCPSourceClient(config, MCPBearer("synthetic", _ENDPOINT), validate_access=_authorized) + client = MCPSourceClient( + config, MCPBearer("synthetic", _AUDIENCE), validate_access=_authorized, _transport=source + ) + async with client: + assert (await client.discover()).resources + first = await client.list_resources() + assert not first.complete and first.next_cursor == "next" + assert (await client.list_resources(first.next_cursor)).complete + item = await client.read(_DOCUMENT) + assert item.title == "Synthetic document" + assert item.receipt is not None + assert item.receipt.requested_id == _DOCUMENT + assert item.receipt.content_sha256 == hashlib.sha256(b"synthetic text").hexdigest() + assert item.receipt.config_sha256 == client.config_sha256 + assert item.receipt.identity_verified + assert pin == ["source.example"] + assert source.closed + assert "synthetic private diagnostic" not in caplog.text + logging.getLogger("mcp.fixture").warning("synthetic public diagnostic") + assert "synthetic public diagnostic" in caplog.text + for request, _method in source.calls: + assert str(request.url) == "https://[2600::10]:8443/mcp" + assert request.headers["host"] == "source.example:8443" + assert request.headers["authorization"] == "Bearer synthetic" + assert request.extensions["sni_hostname"] == "source.example" + + +@pytest.mark.asyncio +async def test_redirect_is_not_followed(pin: list[str]) -> None: + source = _Source() + source.redirect = True + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + async with _client(source): + pytest.fail("redirect accepted") + assert pin == ["source.example"] + assert [method for _, method in source.calls] == ["initialize"] + assert "authorization" not in source.calls[0][0].headers + assert source.closed + + +@pytest.mark.asyncio +async def test_unapproved_resource_id_poison_session(pin: list[str]) -> None: + source = _Source() + async with _client(source) as client: + first = await client.list_resources() + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await client.read(first.items[0].resource_id) + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await client.list_resources() + assert "resources/read" not in [method for _, method in source.calls] + + +@pytest.mark.asyncio +async def test_dns_rejects_mixed_public_and_nonpublic_answers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class Record: + def __init__(self, address: str) -> None: + self.address = address + + def to_text(self) -> str: + return self.address + + class Resolver: + async def resolve(self, host: str, family: str, **options: Any) -> list[Record]: + assert host == "source.example" + assert options == {"search": False, "raise_on_no_answer": False} + return [Record("8.8.8.8" if family == "A" else "64:ff9b::7f00:1")] + + monkeypatch.setattr(dns.asyncresolver, "Resolver", Resolver) + assert await resolve_public_address("source.example") is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("host", ["127.0.0.1", "::ffff:127.0.0.1", "::127.0.0.1", "ff02::1"]) +async def test_nonpublic_literals_are_refused(host: str) -> None: + assert await resolve_public_address(host) is None + + +def _mapped_source() -> tuple[_Source, MCPToolMapping]: + input_schema = {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]} + output_schema = {"type": "object"} + mapping = MCPToolMapping("read", input_schema, output_schema, "id") + source = _Source() + source.tool = {"name": "read", "inputSchema": input_schema, "outputSchema": output_schema} + source.tool_result = { + "content": [], + "structuredContent": {"id": _DOCUMENT, "title": "title", "text": "text", "uri": _DOCUMENT}, + } + return source, mapping + + +@pytest.mark.asyncio +async def test_mapping_snapshots_approved_schemas_and_refuses_drift(pin: list[str]) -> None: + source, mapping = _mapped_source() + async with _client( + source, approved_tools=("read",), read=mapping, approved_resource_ids=(_DOCUMENT,) + ) as client: + assert (await client.discover()).tools == ("read",) + item = await client.read(_DOCUMENT) + assert item.receipt is not None and item.receipt.operation == "tools/call" + assert source.tool is not None + mapping.output_schema["additionalProperties"] = False + with pytest.raises(MCPSourceError, match="^MCP source schema$"): + await client.read(_DOCUMENT) + assert sum(method == "tools/call" for _, method in source.calls) == 1 + + +@pytest.mark.parametrize( + ("policy", "value"), + [ + (MCPDataPolicy(max_nodes=13), list(range(12))), + (MCPDataPolicy(max_depth=4), [[[["deep"]]]]), + (MCPDataPolicy(max_items=1), [1, 2]), + (MCPDataPolicy(max_string_bytes=24), "é" * 13), + ], +) +def test_parser_policy_bounds_fixed_arguments(policy: MCPDataPolicy, value: Any) -> None: + mapping = MCPToolMapping("read", {"type": "object"}, {"type": "object"}, "id") + validate_mcp_tool_mapping(mapping, policy=policy) + with pytest.raises(MCPSourceError, match="^MCP source limit$"): + validate_mcp_tool_mapping(replace(mapping, fixed_arguments={"test": value}), policy=policy) + + +def test_parser_policy_is_immutable_and_cannot_raise_ceilings() -> None: + policy = MCPDataPolicy() + with pytest.raises(FrozenInstanceError): + policy.max_depth = 17 + for invalid in ( + {"max_depth": 17}, + {"max_items": True}, + {"max_string_bytes": 0}, + {"max_nodes": 4097}, + ): + with pytest.raises(MCPSourceError, match="^MCP source config$"): + replace(policy, **invalid) + + +@pytest.mark.asyncio +async def test_tool_response_is_bounded_even_with_permissive_schema(pin: list[str]) -> None: + source, mapping = _mapped_source() + source.tool_result["structuredContent"]["extra"] = [1, 2] + async with _client( + source, + approved_tools=("read",), + read=mapping, + approved_resource_ids=(_DOCUMENT,), + data_policy=MCPDataPolicy(max_items=1), + ) as client: + with pytest.raises(MCPSourceError, match="^MCP source limit$"): + await client.read(_DOCUMENT) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("limits", "encoding", "error"), + [ + (MCPLimits(max_wire_bytes=1024, request_seconds=1), "identity", "limit"), + (MCPLimits(request_seconds=1), "gzip", "protocol"), + ], +) +async def test_stream_rejects_over_budget_or_compressed_data( + pin: list[str], limits: MCPLimits, encoding: str, error: str +) -> None: + source = _Source() + source.content_encoding = encoding + source.resource_text = "x" * 1024 + async with _client(source, approved_resource_ids=(_DOCUMENT,), limits=limits) as client: + with pytest.raises(MCPSourceError, match=f"^MCP source {error}$"): + await client.read(_DOCUMENT) + assert source.closed + + +@pytest.mark.asyncio +async def test_revalidation_refusal_prevents_more_requests(pin: list[str]) -> None: + source = _Source() + revoked = asyncio.Event() + + async def validate_access() -> None: + if revoked.is_set(): + raise MCPSourceError("denied") + + config = MCPSourceConfig(_ENDPOINT, approved_resource_ids=(_DOCUMENT,)) + async with MCPSourceClient( + config, None, validate_access=validate_access, _transport=source + ) as client: + await client.list_resources() + revoked.set() + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await client.read(_DOCUMENT) + assert "resources/read" not in [method for _, method in source.calls] + assert source.closed + + +@pytest.mark.asyncio +async def test_session_deadline_cancels_stalled_read(pin: list[str]) -> None: + source = _Source() + source.stall = True + limits = MCPLimits(timeout_seconds=1, request_seconds=3) + async with _client(source, approved_resource_ids=(_DOCUMENT,), limits=limits) as client: + with pytest.raises(MCPSourceError, match="^MCP source timeout$"): + await client.read(_DOCUMENT) + assert source.read_started.is_set() and source.read_cancelled.is_set() and source.closed + + +@pytest.mark.asyncio +async def test_cancel_drains_owned_sdk_request_before_return(pin: list[str]) -> None: + source = _Source() + source.stall = True + async with _client(source, approved_resource_ids=(_DOCUMENT,)) as client: + read = asyncio.create_task(client.read(_DOCUMENT)) + async with asyncio.timeout(3): + await source.read_started.wait() + read.cancel() + with pytest.raises(asyncio.CancelledError): + await read + assert source.read_cancelled.is_set() and source.closed + with pytest.raises(MCPSourceError, match="^MCP source closed$"): + await client.read(_DOCUMENT) diff --git a/source_worker/tests/test_protocol.py b/source_worker/tests/test_protocol.py new file mode 100644 index 0000000000..75ec283e49 --- /dev/null +++ b/source_worker/tests/test_protocol.py @@ -0,0 +1,116 @@ +import time +import unittest +from uuid import uuid4 + +import jwt +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from loom_source_worker.protocol import ( + ConnectionBinding, + ReadBinding, + ReadGrant, + ReadGrantRefused, + issue_read_grant, + verify_read_grant, +) + + +class TestReadGrant(unittest.TestCase): + def setUp(self) -> None: + self.key = Ed25519PrivateKey.generate() + self.binding = ReadBinding( + worker_id=uuid4(), + org="org", + namespace="collection", + source_id=uuid4(), + selection_generation=5, + requester="alice", + connection_id=uuid4(), + connection_generation=3, + profile_digest="a" * 64, + resource_id="urn:document:Résumé", + ) + self.grant = ReadGrant(request_id=uuid4(), operation="live", binding=self.binding) + + def _verify(self, token: str) -> tuple[ReadGrant, int]: + return verify_read_grant( + token, issuer="loom", worker_id=self.binding.worker_id, key=self.key.public_key() + ) + + def _issue(self) -> str: + return issue_read_grant(self.grant, issuer="loom", key=self.key, lifetime_seconds=20) + + def _sign(self, **claims: object) -> str: + issued_at = int(time.time()) + return jwt.encode( + { + "iss": "loom", + "aud": f"urn:loom:source-worker:{self.binding.worker_id}", + "iat": issued_at, + "exp": issued_at + 20, + "grant": self.grant.model_dump(mode="json"), + **claims, + }, + self.key, + algorithm="EdDSA", + ) + + def test_preserves_exact_selection_and_binding(self) -> None: + actual, _ = self._verify(self._issue()) + self.assertEqual(actual, self.grant) + + def test_rejects_unsigned_or_another_worker_or_signer(self) -> None: + alien_key = Ed25519PrivateKey.generate() + for token in ( + jwt.encode({"grant": self.grant.model_dump(mode="json")}, "", algorithm="none"), + self._sign(aud="urn:loom:source-worker:other"), + issue_read_grant(self.grant, issuer="loom", key=alien_key, lifetime_seconds=20), + self._sign(iss="another-loom"), + self._sign(aud=[f"urn:loom:source-worker:{self.binding.worker_id}"]), + ): + with self.assertRaises(ReadGrantRefused): + self._verify(token) + + def test_refuses_expired_future_and_long_lived_claims(self) -> None: + now = int(time.time()) + cases = ({"exp": now - 1}, {"iat": now + 3}, {"exp": now + 90}, {"exp": str(now + 5)}) + for claims in cases: + with self.assertRaises(ReadGrantRefused): + self._verify(self._sign(**claims)) + + def test_refuses_credential_or_coerced_generation_in_signed_payload(self) -> None: + unsigned = self.grant.model_dump(mode="json") + cases = ( + {"credential": "arbitrary"}, + {"selection_generation": "5"}, + {"connection_generation": True}, + ) + for overrides in cases: + with self.assertRaises(ReadGrantRefused): + binding = {**unsigned["binding"], **overrides} + self._verify(self._sign(grant={**unsigned, "binding": binding})) + + def test_credential_can_only_resolve_for_the_exact_requester_and_generation(self) -> None: + connection = ConnectionBinding( + worker_id=self.binding.worker_id, + org=self.binding.org, + owner=self.binding.requester, + connection_id=self.binding.connection_id, + generation=self.binding.connection_generation, + profile_digest=self.binding.profile_digest, + ) + connection.authorize(self.grant) + variants = ( + {"worker_id": uuid4()}, + {"org": "other"}, + {"owner": "bob"}, + {"connection_id": uuid4()}, + {"generation": 4}, + {"profile_digest": "b" * 64}, + ) + for values in variants: + with self.subTest(fields=tuple(values)), self.assertRaises(ReadGrantRefused): + connection.model_copy(update=values).authorize(self.grant) + + +if __name__ == "__main__": + unittest.main() diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py new file mode 100644 index 0000000000..91d56ca3d2 --- /dev/null +++ b/source_worker/tests/test_protocol_servers.py @@ -0,0 +1,179 @@ +"""Installed worker against owned official SDK servers over ASGI HTTP.""" + +from __future__ import annotations + +import ipaddress +import time +from typing import Any +from uuid import UUID, uuid4 + +import httpx +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from loom_source_worker import direct_backend, mcp_client +from loom_source_worker.credential_store import CredentialRecord +from loom_source_worker.direct_backend import ApprovedProfile, DirectBackend +from loom_source_worker.mcp_client import MCPSourceConfig, MCPToolMapping +from loom_source_worker.protocol import ConnectionBinding, ReadBinding, ReadGrant, issue_read_grant +from loom_source_worker.read_service import ReadFailure, ReadLimits, ReadService +from mcp import types +from mcp.server import Server +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from pydantic import AnyUrl, SecretStr +from starlette.types import Receive, Scope, Send + +_ENDPOINT = "https://source.example.test/mcp" +_DOC = "urn:fixture:doc" +_INPUT = { + "type": "object", + "properties": {"id": {"type": "string"}}, + "required": ["id"], + "additionalProperties": False, +} +_OUTPUT = { + "type": "object", + "properties": {key: {"type": "string"} for key in ("id", "title", "uri", "text")}, + "required": ["id", "title", "uri", "text"], + "additionalProperties": False, +} + + +class _SyntheticAccounts: + def __init__(self, binding: ReadBinding) -> None: + self.records: dict[UUID, CredentialRecord] = {} + self.add(binding, "synthetic-alice") + + def add(self, binding: ReadBinding, token: str) -> None: + self.records[binding.connection_id] = CredentialRecord( + binding=ConnectionBinding( + worker_id=binding.worker_id, + org=binding.org, + owner=binding.requester, + connection_id=binding.connection_id, + generation=binding.connection_generation, + profile_digest=binding.profile_digest, + ), + auth="bearer", + state="active", + audience=_ENDPOINT, + token=SecretStr(token), + expires_at=int(time.time()) + 60, + ) + + async def get(self, connection_id: UUID) -> CredentialRecord: + return self.records[connection_id] + + +def _resource_server() -> StreamableHTTPSessionManager: + server: Server[Any, Any] = Server("synthetic-resources") + + @server.list_resources() + async def list_resources() -> list[types.Resource]: + return [types.Resource(uri=AnyUrl(_DOC), name="Resource")] + + @server.read_resource() + async def read_resource(uri: AnyUrl) -> str: + assert str(uri) == _DOC + return "resource fixture body" + + return StreamableHTTPSessionManager(app=server, json_response=False, stateless=True) + + +def _tool_server() -> StreamableHTTPSessionManager: + server: Server[Any, Any] = Server("synthetic-mapped-tool") + + @server.list_tools() + async def list_tools() -> list[types.Tool]: + return [types.Tool(name="read", inputSchema=_INPUT, outputSchema=_OUTPUT)] + + @server.call_tool() + async def read_tool(name: str, arguments: dict[str, Any]) -> dict[str, str]: + assert name == "read" + assert arguments == {"id": _DOC} + return {"id": _DOC, "title": "Mapped", "uri": _DOC, "text": "tool fixture body"} + + return StreamableHTTPSessionManager(app=server, json_response=True, stateless=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["resource", "tool"]) +async def test_read_and_proof_with_two_accounts(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: + if mode == "resource": + manager = _resource_server() + config = MCPSourceConfig(endpoint=_ENDPOINT, bearer_audience=_ENDPOINT) + else: + manager = _tool_server() + config = MCPSourceConfig( + endpoint=_ENDPOINT, + bearer_audience=_ENDPOINT, + approved_tools=("read",), + read=MCPToolMapping( + name="read", input_schema=_INPUT, output_schema=_OUTPUT, argument_name="id" + ), + ) + allowed = {b"Bearer synthetic-alice"} + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + if dict(scope["headers"]).get(b"authorization") not in allowed: + await send({"type": "http.response.start", "status": 403, "headers": []}) + await send({"type": "http.response.body", "body": b""}) + return + await manager.handle_request(scope, receive, send) + + async def synthetic_pin(host: str) -> ipaddress.IPv6Address: + assert host == "source.example.test" + return ipaddress.IPv6Address("2600::10") + + def routed_client(config: Any, credential: Any, *, validate_access: Any) -> Any: + return mcp_client.MCPSourceClient( + config, + credential, + validate_access=validate_access, + _transport=httpx.ASGITransport(app=app), + ) + + monkeypatch.setattr(mcp_client, "resolve_public_address", synthetic_pin) + monkeypatch.setattr(direct_backend, "MCPSourceClient", routed_client) + profile = ApprovedProfile(config, ("org",)) + binding = ReadBinding( + worker_id=uuid4(), + org="org", + namespace="team", + source_id=uuid4(), + selection_generation=1, + requester="alice", + connection_id=uuid4(), + connection_generation=1, + profile_digest=profile.digest, + resource_id=_DOC, + ) + bob = binding.model_copy(update={"requester": "bob", "connection_id": uuid4()}) + accounts = _SyntheticAccounts(binding) + accounts.add(bob, "synthetic-bob") + key = Ed25519PrivateKey.generate() + service = ReadService( + worker_id=binding.worker_id, + issuer="loom", + verifier=key.public_key(), + backend=DirectBackend(accounts, (profile,)), + limits=ReadLimits( + concurrent=4, concurrent_per_org=2, timeout_seconds=5, content_bytes=2048 + ), + ) + + def grant(target: ReadBinding, operation: str) -> str: + request = ReadGrant.model_validate( + {"request_id": uuid4(), "operation": operation, "binding": target} + ) + return issue_read_grant(request, issuer="loom", key=key, lifetime_seconds=10) + + async with manager.run(): + result = await service.execute(grant(binding, "live"), "live") + assert result.document is not None + assert result.document.text == f"{mode} fixture body" + with pytest.raises(ReadFailure, match="^denied$"): + await service.execute(grant(bob, "check_access"), "check_access") + allowed.add(b"Bearer synthetic-bob") + proof = await service.execute(grant(bob, "check_access"), "check_access") + assert proof.document is None + assert proof.content_sha256 == result.content_sha256 diff --git a/source_worker/tests/test_read_service.py b/source_worker/tests/test_read_service.py new file mode 100644 index 0000000000..67419727d3 --- /dev/null +++ b/source_worker/tests/test_read_service.py @@ -0,0 +1,147 @@ +import asyncio +import hashlib +import unittest +from uuid import uuid4 + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from loom_source_worker.protocol import ( + ConnectionBinding, + ReadBinding, + ReadGrant, + issue_read_grant, +) +from loom_source_worker.read_service import ( + BoundReader, + CurrentAccess, + Document, + ReadFailure, + ReadLimits, + ReadService, +) + + +class _Backend: + def __init__(self, binding: ConnectionBinding) -> None: + self.binding = binding + self.started = asyncio.Event() + self.release = asyncio.Event() + self.release.set() + self.return_identity: str | None = None + self.payload = "actualité" + self.calls: list[str] = [] + + async def resolve(self, binding: ReadBinding) -> BoundReader: + return self + + async def current(self, binding: ReadBinding) -> ConnectionBinding: + return self.binding + + async def read_exact(self, resource_id: str, *, authorize: CurrentAccess) -> Document: + await authorize() + self.calls.append(resource_id) + self.started.set() + await self.release.wait() + return Document(self.return_identity or resource_id, "Title", self.payload) + + +class TestReadService(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.key = Ed25519PrivateKey.generate() + self.binding = ReadBinding( + worker_id=uuid4(), + org="org", + namespace="team", + source_id=uuid4(), + selection_generation=2, + requester="alice", + connection_id=uuid4(), + connection_generation=1, + profile_digest="d" * 64, + resource_id="urn:resource:exact", + ) + self.backend = _Backend( + ConnectionBinding( + worker_id=self.binding.worker_id, + org=self.binding.org, + owner=self.binding.requester, + connection_id=self.binding.connection_id, + generation=self.binding.connection_generation, + profile_digest=self.binding.profile_digest, + ) + ) + + def _service(self, *, timeout: float = 1) -> ReadService: + return ReadService( + worker_id=self.binding.worker_id, + issuer="loom", + verifier=self.key.public_key(), + backend=self.backend, + limits=ReadLimits( + concurrent=2, concurrent_per_org=1, timeout_seconds=timeout, content_bytes=128 + ), + ) + + def _token(self, grant: ReadGrant) -> str: + return issue_read_grant(grant, issuer="loom", key=self.key, lifetime_seconds=10) + + def _live(self) -> ReadGrant: + return ReadGrant(request_id=uuid4(), operation="live", binding=self.binding) + + async def test_live_and_access_check_are_separate(self) -> None: + service = self._service() + live = self._live() + proof = ReadGrant(request_id=uuid4(), operation="check_access", binding=self.binding) + result = await service.execute(self._token(live), "live") + checked = await service.execute(self._token(proof), "check_access") + self.assertEqual(result.request_id, live.request_id) + self.assertEqual(result.document, Document(self.binding.resource_id, "Title", "actualité")) + self.assertIsNone(checked.document) + self.assertEqual(checked.content_sha256, hashlib.sha256("actualité".encode()).hexdigest()) + with self.assertRaisesRegex(ReadFailure, "^denied$"): + await service.execute(self._token(proof), "live") + self.assertEqual(self.backend.calls, [self.binding.resource_id] * 2) + + async def test_other_account_cannot_reuse_a_team_connection(self) -> None: + bob = self.binding.model_copy(update={"requester": "bob"}) + grant = ReadGrant(request_id=uuid4(), operation="live", binding=bob) + with self.assertRaisesRegex(ReadFailure, "^denied$"): + await self._service().execute(self._token(grant), "live") + self.assertEqual(self.backend.calls, []) + + async def test_revocation_before_response_refuses_data(self) -> None: + self.backend.release.clear() + service = self._service() + read = asyncio.create_task(service.execute(self._token(self._live()), "live")) + await self.backend.started.wait() + self.backend.binding = self.backend.binding.model_copy(update={"generation": 2}) + self.backend.release.set() + with self.assertRaisesRegex(ReadFailure, "^denied$"): + await read + + async def test_wrong_resource_and_large_utf8_body_are_never_returned(self) -> None: + service = self._service() + self.backend.return_identity = "urn:another-document" + with self.assertRaisesRegex(ReadFailure, "^denied$"): + await service.execute(self._token(self._live()), "live") + self.backend.return_identity = None + self.backend.payload = "é" * 65 + with self.assertRaisesRegex(ReadFailure, "^unsupported$"): + await service.execute(self._token(self._live()), "live") + + async def test_saturation_and_cancellation_release_the_live_slot(self) -> None: + self.backend.release.clear() + service = self._service() + read = asyncio.create_task(service.execute(self._token(self._live()), "live")) + await self.backend.started.wait() + with self.assertRaisesRegex(ReadFailure, "^overloaded$"): + await service.execute(self._token(self._live()), "live") + read.cancel() + with self.assertRaises(asyncio.CancelledError): + await read + self.backend.release.set() + self.assertIsNotNone((await service.execute(self._token(self._live()), "live")).document) + + async def test_stalled_upstream_has_a_distinct_timeout(self) -> None: + self.backend.release.clear() + with self.assertRaisesRegex(ReadFailure, "^timeout$"): + await self._service(timeout=0.03).execute(self._token(self._live()), "live") From 993e7530d0cbbd8a9531d2531ee93a796d3fac5c Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 08:36:51 +0000 Subject: [PATCH 02/31] Document the private source worker boundary Signed-off-by: zlareb1 --- source_worker/README.md | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 source_worker/README.md diff --git a/source_worker/README.md b/source_worker/README.md new file mode 100644 index 0000000000..4745ab3341 --- /dev/null +++ b/source_worker/README.md @@ -0,0 +1,51 @@ +# MCP source worker + +The companion runs outside the Loom service. It executes approved reads through +remote Streamable HTTP MCP servers. It accepts anonymous connections and +preissued bearer tokens bound to an approved resource audience and origin. It +does not run local server commands, acquire OAuth grants, refresh tokens or +infer read operations from tool descriptions. Resources and operator-approved +tool mappings use the same size, request, schema and deadline bounds. + +The worker package contains no Loom server, database client or indexing code. +Loom integration, refresh and publication are separate from this package. + +## Running the companion + +Run `loom-source-worker` or build the image using this directory as its context. +The worker serves a private Unix socket. Put a TLS proxy in front of that socket +and limit it to the authorized Loom service. Disable proxy access, header, body +and trace logging and response caching. Forward only `POST /v1/live` and +`POST /v1/check-access`. Neither route accepts a query string or request body. +The worker verifies an issuer-pinned, short-lived Ed25519 grant in the +authorization header, scoped to the worker, operation, requester, connection, +tenant and selected resource. Do not forward this grant to an upstream server. + +| Path | Purpose | +| --------------------------------------------------- | ----------------------------------------------- | +| `/etc/loom-source-worker/config.json` | Worker identity, issuer, profiles and limits | +| `/etc/loom-source-worker/grant-verifier.pem` | Ed25519 public key used to verify Loom grants | +| `/etc/loom-source-worker/vault-ca.pem` | Optional CA roots for the credential service | +| `/run/loom-source-worker/credentials/vault-token` | Worker-only credential service token | +| `/run/loom-source-worker/socket/worker.sock` | Local socket mounted only by worker and proxy | + +The image runs as UID and GID `10001`. Give it a socket directory it owns with +mode `0700`. Share only the socket directory with the proxy. Keep the +credential mount out of the proxy and Loom containers. Give the worker token +read access only to its dedicated KV v2 connection prefix. Store each record +under the worker UUID and opaque connection UUID; the record binds the owner, +organization, profile and generation to that connection. The generation must +match the current secret version. Rotate or revoke at the credential backend; +do not copy the credential into a Loom registration or task. Limit egress to +the approved credential, DNS and upstream endpoints. + +The required configuration fields are `transport` (`tls_proxy_unix`), +`worker_id`, `issuer`, `vault`, `read_limits` and `profiles`. A profile names the +permitted organizations, optional HTTPS citation origins and the approved +client configuration. Keep the signer and worker profile digest in agreement. +Any account, profile, selection or authority change requires a current grant. +An access check returns a content digest and fetch time without the body. + +The hosted package test uses owned SDK resource and mapped-tool servers with +synthetic accounts. It does not qualify production credential infrastructure +or a particular external service. From ad87228292d2bb52a92ae10864bc10b914c7739e Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 08:44:19 +0000 Subject: [PATCH 03/31] Enforce current mapped read schemas and bounded credential checks Signed-off-by: zlareb1 --- source_worker/README.md | 29 ++++--- .../loom_source_worker/direct_backend.py | 2 + source_worker/loom_source_worker/main.py | 2 +- .../loom_source_worker/mcp_client.py | 27 +++--- .../loom_source_worker/read_service.py | 5 +- source_worker/tests/test_main.py | 20 ++++- source_worker/tests/test_mcp_client.py | 41 +++++++++ source_worker/tests/test_protocol_servers.py | 87 +++++++++++++++++-- 8 files changed, 180 insertions(+), 33 deletions(-) diff --git a/source_worker/README.md b/source_worker/README.md index 4745ab3341..62c280e8dc 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -21,16 +21,17 @@ The worker verifies an issuer-pinned, short-lived Ed25519 grant in the authorization header, scoped to the worker, operation, requester, connection, tenant and selected resource. Do not forward this grant to an upstream server. -| Path | Purpose | -| --------------------------------------------------- | ----------------------------------------------- | -| `/etc/loom-source-worker/config.json` | Worker identity, issuer, profiles and limits | -| `/etc/loom-source-worker/grant-verifier.pem` | Ed25519 public key used to verify Loom grants | -| `/etc/loom-source-worker/vault-ca.pem` | Optional CA roots for the credential service | -| `/run/loom-source-worker/credentials/vault-token` | Worker-only credential service token | -| `/run/loom-source-worker/socket/worker.sock` | Local socket mounted only by worker and proxy | - -The image runs as UID and GID `10001`. Give it a socket directory it owns with -mode `0700`. Share only the socket directory with the proxy. Keep the +Mount these files and directories in the worker: + +- `/etc/loom-source-worker/config.json`: identity, issuer, profiles and limits. +- `/etc/loom-source-worker/grant-verifier.pem`: public key used to verify grants. +- `/etc/loom-source-worker/vault-ca.pem`: optional credential service CA roots. +- `/run/loom-source-worker/credentials/vault-token`: credential service token. +- `/run/loom-source-worker/socket`: directory mounted by the worker and proxy. + +Run the proxy and worker under the same numeric UID, `10001` in the image. +The worker requires an owned `0700` directory and creates the socket with +mode `0600`. Share only the socket directory with the proxy. Keep the credential mount out of the proxy and Loom containers. Give the worker token read access only to its dedicated KV v2 connection prefix. Store each record under the worker UUID and opaque connection UUID; the record binds the owner, @@ -42,10 +43,16 @@ the approved credential, DNS and upstream endpoints. The required configuration fields are `transport` (`tls_proxy_unix`), `worker_id`, `issuer`, `vault`, `read_limits` and `profiles`. A profile names the permitted organizations, optional HTTPS citation origins and the approved -client configuration. Keep the signer and worker profile digest in agreement. +client configuration. A mapped read must return the exact selected identity. +Keep the signer and worker profile digest in agreement. Any account, profile, selection or authority change requires a current grant. An access check returns a content digest and fetch time without the body. +A grant is reusable until its expiry for the same read, within the worker's +capacity limits. It never authorizes a stored write. The issuer must check +selection and requester authority before issuing it and before delivering a +result. The worker rechecks its connection during the read and before reply. + The hosted package test uses owned SDK resource and mapped-tool servers with synthetic accounts. It does not qualify production credential infrastructure or a particular external service. diff --git a/source_worker/loom_source_worker/direct_backend.py b/source_worker/loom_source_worker/direct_backend.py index 0f3a3fb8f8..dfeddb9e7a 100644 --- a/source_worker/loom_source_worker/direct_backend.py +++ b/source_worker/loom_source_worker/direct_backend.py @@ -26,6 +26,8 @@ class ApprovedProfile: def __post_init__(self) -> None: if self.config.approved_resource_ids or not self.organizations: raise ValueError("profile must scope the tenant without selecting resources") + if self.config.read is not None and self.config.read.result_format == "text": + raise ValueError("mapped read must return its selected resource identity") if any(_link_origin(value) != value for value in self.link_origins): raise ValueError("invalid approved link origin") diff --git a/source_worker/loom_source_worker/main.py b/source_worker/loom_source_worker/main.py index 62e8248f76..cb7dec3e58 100644 --- a/source_worker/loom_source_worker/main.py +++ b/source_worker/loom_source_worker/main.py @@ -153,7 +153,7 @@ def _parse_settings(raw: bytes) -> _Settings: ): raise ValueError("invalid profile scope") audience = profile.config.bearer_audience - if audience is not None and not _https_origin(audience): + if audience is not None and not _visible_ascii(audience, 2048): raise ValueError("invalid profile audience") credential = MCPBearer("profile-validation", audience) if audience is not None else None client = MCPSourceClient( diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 1359165474..877c766b3d 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -546,12 +546,12 @@ def _tool_value( def _check_tool_schema(tool: types.Tool, mapping: MCPToolMapping, policy: MCPDataPolicy) -> None: _schema(tool.inputSchema, policy) - if tool.inputSchema != mapping.input_schema: + if _json(tool.inputSchema, 16_384) != _json(mapping.input_schema, 16_384): raise MCPSourceError("schema") if tool.outputSchema is not None: _schema(tool.outputSchema, policy) expected = mapping.output_schema if mapping.require_output_schema else None - if tool.outputSchema != expected: + if _json(tool.outputSchema, 16_384) != _json(expected, 16_384): raise MCPSourceError("schema") @@ -586,7 +586,7 @@ async def __aiter__(self) -> AsyncIterator[bytes]: self.owner.received += len(chunk) if self.owner.received > self.owner.limits.max_wire_bytes: raise MCPSourceError("limit") - await self.owner._authorize() + self.owner._check_state() yield chunk except Exception as error: # noqa: BLE001 — only fixed diagnostics cross the transport boundary self.owner.failure = self.owner.failure or _error_code(error) @@ -594,7 +594,7 @@ async def __aiter__(self) -> AsyncIterator[bytes]: async def aclose(self) -> None: # The SDK cancels its task group before joining HTTP stream finalizers. - with anyio.CancelScope(shield=True): + with anyio.move_on_after(1, shield=True): await self.stream.aclose() @@ -711,11 +711,12 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: finally: if response is not None and not handed_off: # Leave the deadline scope before joining an unclaimed response's finalizer. - with anyio.CancelScope(shield=True): + with anyio.move_on_after(1, shield=True): await response.aclose() async def aclose(self) -> None: - await self.inner.aclose() + with anyio.move_on_after(1, shield=True): + await self.inner.aclose() _T = TypeVar("_T") @@ -777,7 +778,8 @@ def __init__( self._operation_failure: ErrorCode | None = None self._deadline = 0.0 self._discovery: MCPDiscovery | None = None - self._schema_changed = False + self._tool_epoch = 0 + self._discovered_epoch = -1 self._pages, self._results = 0, 0 self._issued_cursors: set[tuple[tuple[str, str], str]] = set() self._used_cursors: set[tuple[tuple[str, str], str]] = set() @@ -969,7 +971,7 @@ async def _message_handler(self, message: Any) -> None: if isinstance(message, types.ServerNotification) and isinstance( message.root, types.ToolListChangedNotification ): - self._schema_changed = True + self._tool_epoch += 1 async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: with private_work(): @@ -1010,6 +1012,7 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T async def discover(self) -> MCPDiscovery: async def action(session: ClientSession) -> MCPDiscovery: approved = set(self._config.approved_tools) + epoch = self._tool_epoch found: set[str] = set() cursor: str | None = None seen: set[str] = set() @@ -1040,9 +1043,11 @@ async def action(session: ClientSession) -> MCPDiscovery: raise MCPSourceError("limit") if found != approved: raise MCPSourceError("unsupported") + if epoch != self._tool_epoch: + raise MCPSourceError("schema") assert self._discovery is not None self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) - self._schema_changed = False + self._discovered_epoch = epoch return self._discovery return await self._run(action) @@ -1095,7 +1100,7 @@ async def _tool( ) -> Any: await self.discover() if ( - self._schema_changed + self._tool_epoch != self._discovered_epoch or self._discovery is None or mapping.name not in self._discovery.tools ): @@ -1116,7 +1121,7 @@ async def _tool( ), types.CallToolResult, ) - if self._schema_changed: + if self._tool_epoch != self._discovered_epoch: raise MCPSourceError("schema") return _tool_value(result, mapping, self._config.limits, self._config.data_policy) diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index 27ac385c62..e5730686d4 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -126,7 +126,10 @@ async def require_current() -> None: if time.time() >= expires_at: raise ReadFailure("timeout") current = await self._backend.current(binding) - current.authorize(grant) + try: + current.authorize(grant) + except ReadGrantRefused: + raise ReadFailure("denied") from None if time.time() >= expires_at: raise ReadFailure("timeout") diff --git a/source_worker/tests/test_main.py b/source_worker/tests/test_main.py index 47261f82f0..e2c99c76ff 100644 --- a/source_worker/tests/test_main.py +++ b/source_worker/tests/test_main.py @@ -70,7 +70,7 @@ def test_resource_profile_and_transport_settings(config): def test_mapped_read_profile_is_validated_at_startup(config): source = config["profiles"][0]["config"] source.update( - bearer_audience="https://mcp.example", + bearer_audience="https://mcp.example/rpc", approved_tools=["read_document"], read={ "name": "read_document", @@ -93,6 +93,7 @@ def test_mapped_read_profile_is_validated_at_startup(config): }, ) settings = _parse_settings(json.dumps(config).encode()) + assert settings.profiles[0].config.bearer_audience == "https://mcp.example/rpc" assert settings.profiles[0].config.read.id_path == ("id",) assert len(settings.profiles[0].digest) == 64 source["read"]["argument_nam"] = "id" @@ -100,6 +101,23 @@ def test_mapped_read_profile_is_validated_at_startup(config): _parse_settings(json.dumps(config).encode()) +def test_plain_text_mapping_cannot_prove_selection_identity(config): + source = config["profiles"][0]["config"] + source.update( + approved_tools=["read"], + read={ + "name": "read", + "argument_name": "id", + "input_schema": {"type": "object"}, + "output_schema": {"type": "string"}, + "result_format": "text", + "require_output_schema": False, + }, + ) + with pytest.raises(StartupError, match="^invalid worker configuration$"): + _parse_settings(json.dumps(config).encode()) + + @pytest.mark.parametrize( ("path", "value"), [ diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 202e029bc8..ecb2217f34 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -67,6 +67,7 @@ def __init__(self) -> None: self.redirect = False self.content_encoding = "identity" self.resource_text = "synthetic text" + self.change_tools_during_discovery = False async def aclose(self) -> None: self.closed = True @@ -118,6 +119,20 @@ async def respond(self, request: httpx.Request) -> httpx.Response: }, ) elif method == "tools/list": + if self.change_tools_during_discovery: + if not body.get("params", {}).get("cursor"): + return _json_response(body["id"], {"tools": [self.tool], "nextCursor": "next"}) + notification = {"jsonrpc": "2.0", "method": "notifications/tools/list_changed"} + answer = {"jsonrpc": "2.0", "id": body["id"], "result": {"tools": []}} + frames = "".join( + f"event: message\ndata: {json.dumps(item)}\n\n" + for item in (notification, answer) + ) + return httpx.Response( + 200, + stream=_Body(frames.encode()), + headers={"content-type": "text/event-stream"}, + ) result = {"tools": [self.tool]} elif method == "tools/call": result = self.tool_result @@ -282,6 +297,32 @@ async def test_mapping_snapshots_approved_schemas_and_refuses_drift(pin: list[st assert sum(method == "tools/call" for _, method in source.calls) == 1 +@pytest.mark.asyncio +async def test_tool_list_notification_invalidates_an_inflight_discovery(pin: list[str]) -> None: + source, mapping = _mapped_source() + source.change_tools_during_discovery = True + async with _client(source, approved_tools=("read",), read=mapping) as client: + with pytest.raises(MCPSourceError, match="^MCP source schema$"): + await client.discover() + assert sum(method == "tools/list" for _, method in source.calls) == 2 + assert not any(method == "tools/call" for _, method in source.calls) + + +@pytest.mark.asyncio +async def test_advertised_schema_cannot_replace_a_boolean_with_a_number(pin: list[str]) -> None: + source, mapping = _mapped_source() + approved = {**mapping.input_schema, "properties": {"id": {"const": True}}} + changed = {**mapping.input_schema, "properties": {"id": {"const": 1}}} + assert source.tool is not None + source.tool["inputSchema"] = changed + async with _client( + source, approved_tools=("read",), read=replace(mapping, input_schema=approved) + ) as client: + with pytest.raises(MCPSourceError, match="^MCP source schema$"): + await client.discover() + assert not any(method == "tools/call" for _, method in source.calls) + + @pytest.mark.parametrize( ("policy", "value"), [ diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index 91d56ca3d2..2b39a59f08 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -3,7 +3,10 @@ from __future__ import annotations import ipaddress +import json import time +from collections.abc import AsyncIterator, Callable +from dataclasses import asdict from typing import Any from uuid import UUID, uuid4 @@ -12,7 +15,8 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from loom_source_worker import direct_backend, mcp_client from loom_source_worker.credential_store import CredentialRecord -from loom_source_worker.direct_backend import ApprovedProfile, DirectBackend +from loom_source_worker.direct_backend import DirectBackend +from loom_source_worker.main import _parse_settings from loom_source_worker.mcp_client import MCPSourceConfig, MCPToolMapping from loom_source_worker.protocol import ConnectionBinding, ReadBinding, ReadGrant, issue_read_grant from loom_source_worker.read_service import ReadFailure, ReadLimits, ReadService @@ -41,6 +45,7 @@ class _SyntheticAccounts: def __init__(self, binding: ReadBinding) -> None: self.records: dict[UUID, CredentialRecord] = {} + self.reads = 0 self.add(binding, "synthetic-alice") def add(self, binding: ReadBinding, token: str) -> None: @@ -61,10 +66,33 @@ def add(self, binding: ReadBinding, token: str) -> None: ) async def get(self, connection_id: UUID) -> CredentialRecord: + self.reads += 1 return self.records[connection_id] -def _resource_server() -> StreamableHTTPSessionManager: +class _Fragments(httpx.AsyncByteStream): + def __init__(self, stream: httpx.AsyncByteStream) -> None: + self._stream = stream + + async def __aiter__(self) -> AsyncIterator[bytes]: + async for body in self._stream: + for offset in range(0, len(body), 4): + yield body[offset : offset + 4] + + async def aclose(self) -> None: + await self._stream.aclose() + + +class _FragmentedASGI(httpx.ASGITransport): + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + response = await super().handle_async_request(request) + assert isinstance(response.stream, httpx.AsyncByteStream) + return httpx.Response( + response.status_code, headers=response.headers, stream=_Fragments(response.stream) + ) + + +def _resource_server(on_read: Callable[[], None]) -> StreamableHTTPSessionManager: server: Server[Any, Any] = Server("synthetic-resources") @server.list_resources() @@ -74,12 +102,13 @@ async def list_resources() -> list[types.Resource]: @server.read_resource() async def read_resource(uri: AnyUrl) -> str: assert str(uri) == _DOC + on_read() return "resource fixture body" return StreamableHTTPSessionManager(app=server, json_response=False, stateless=True) -def _tool_server() -> StreamableHTTPSessionManager: +def _tool_server(on_read: Callable[[], None]) -> StreamableHTTPSessionManager: server: Server[Any, Any] = Server("synthetic-mapped-tool") @server.list_tools() @@ -90,6 +119,7 @@ async def list_tools() -> list[types.Tool]: async def read_tool(name: str, arguments: dict[str, Any]) -> dict[str, str]: assert name == "read" assert arguments == {"id": _DOC} + on_read() return {"id": _DOC, "title": "Mapped", "uri": _DOC, "text": "tool fixture body"} return StreamableHTTPSessionManager(app=server, json_response=True, stateless=True) @@ -98,11 +128,20 @@ async def read_tool(name: str, arguments: dict[str, Any]) -> dict[str, str]: @pytest.mark.asyncio @pytest.mark.parametrize("mode", ["resource", "tool"]) async def test_read_and_proof_with_two_accounts(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: + revoke: UUID | None = None + + def on_read() -> None: + if revoke is not None: + record = accounts.records[revoke] + accounts.records[revoke] = record.model_copy( + update={"binding": record.binding.model_copy(update={"generation": 2})} + ) + if mode == "resource": - manager = _resource_server() + manager = _resource_server(on_read) config = MCPSourceConfig(endpoint=_ENDPOINT, bearer_audience=_ENDPOINT) else: - manager = _tool_server() + manager = _tool_server(on_read) config = MCPSourceConfig( endpoint=_ENDPOINT, bearer_audience=_ENDPOINT, @@ -118,6 +157,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None: await send({"type": "http.response.start", "status": 403, "headers": []}) await send({"type": "http.response.body", "body": b""}) return + await manager.handle_request(scope, receive, send) async def synthetic_pin(host: str) -> ipaddress.IPv6Address: @@ -129,14 +169,41 @@ def routed_client(config: Any, credential: Any, *, validate_access: Any) -> Any: config, credential, validate_access=validate_access, - _transport=httpx.ASGITransport(app=app), + _transport=_FragmentedASGI(app=app), ) monkeypatch.setattr(mcp_client, "resolve_public_address", synthetic_pin) monkeypatch.setattr(direct_backend, "MCPSourceClient", routed_client) - profile = ApprovedProfile(config, ("org",)) + worker_id = uuid4() + settings = _parse_settings( + json.dumps( + { + "transport": "tls_proxy_unix", + "worker_id": str(worker_id), + "issuer": "loom", + "vault": {"origin": "https://vault.example.test", "mount": "connections"}, + "read_limits": { + "concurrent": 4, + "concurrent_per_org": 2, + "timeout_seconds": 5, + "content_bytes": 2048, + }, + "profiles": [ + { + "config": { + key: value + for key, value in asdict(config).items() + if key != "approved_resource_ids" + }, + "organizations": ["org"], + } + ], + } + ).encode() + ) + [profile] = settings.profiles binding = ReadBinding( - worker_id=uuid4(), + worker_id=worker_id, org="org", namespace="team", source_id=uuid4(), @@ -171,9 +238,13 @@ def grant(target: ReadBinding, operation: str) -> str: result = await service.execute(grant(binding, "live"), "live") assert result.document is not None assert result.document.text == f"{mode} fixture body" + assert accounts.reads <= 32 with pytest.raises(ReadFailure, match="^denied$"): await service.execute(grant(bob, "check_access"), "check_access") allowed.add(b"Bearer synthetic-bob") proof = await service.execute(grant(bob, "check_access"), "check_access") assert proof.document is None assert proof.content_sha256 == result.content_sha256 + revoke = bob.connection_id + with pytest.raises(ReadFailure, match="^denied$"): + await service.execute(grant(bob, "live"), "live") From c3506a2ad1bc6bc94fdfe30b2e5497f0483beba1 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 08:47:07 +0000 Subject: [PATCH 04/31] Return an in-flight revocation as denial before result delivery Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 2 +- source_worker/pyproject.toml | 22 +++++++++---------- source_worker/tests/test_mcp_client.py | 20 +++++++++++++++++ 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 877c766b3d..ebaaabe5c5 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -695,7 +695,7 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: ) await self._authorize() response = await self.inner.handle_async_request(outgoing) - await self._authorize() + self._check_state() _check_response(request.method, response) # Reject compression so the wire budget bounds decoded protocol bytes. if response.headers.get("content-encoding", "identity") != "identity": diff --git a/source_worker/pyproject.toml b/source_worker/pyproject.toml index 7496b40115..f10031f99d 100644 --- a/source_worker/pyproject.toml +++ b/source_worker/pyproject.toml @@ -5,17 +5,17 @@ description = "External MCP source worker for Loom." requires-python = ">=3.12" license = { text = "Apache-2.0" } dependencies = [ - "anyio>=4", - "cryptography>=44", - "dnspython>=2.6", - "httpx>=0.27", - "jsonschema>=4.20", - "mcp>=1.30.0,<2", - "pydantic>=2.9", - "pyjwt>=2.10", - "referencing>=0.37.0", - "starlette>=0.52", - "uvicorn>=0.34,<1", + "anyio>=4", + "cryptography>=44", + "dnspython>=2.6", + "httpx>=0.27", + "jsonschema>=4.20", + "mcp>=1.30.0,<2", + "pydantic>=2.9", + "pyjwt>=2.10", + "referencing>=0.37.0", + "starlette>=0.52", + "uvicorn>=0.34,<1", ] [project.scripts] diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index ecb2217f34..6f17a016c5 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -409,6 +409,26 @@ async def validate_access() -> None: assert source.closed +@pytest.mark.asyncio +async def test_revocation_after_remote_read_is_reported_without_waiting_for_timeout( + pin: list[str], +) -> None: + source = _Source() + + async def validate_access() -> None: + if source.read_started.is_set(): + raise MCPSourceError("denied") + + config = MCPSourceConfig(_ENDPOINT, approved_resource_ids=(_DOCUMENT,)) + async with ( + asyncio.timeout(2), + MCPSourceClient(config, None, validate_access=validate_access, _transport=source) as client, + ): + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await client.read(_DOCUMENT) + assert source.closed + + @pytest.mark.asyncio async def test_session_deadline_cancels_stalled_read(pin: list[str]) -> None: source = _Source() From 51c7d1b97099b4154446501fca7822666df93941 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 08:56:28 +0000 Subject: [PATCH 05/31] Bound stateful MCP reads and session cleanup Signed-off-by: zlareb1 (cherry picked from commit 0d67d3c9c17f9918a127f4d96540ce20c6e2edc3) Signed-off-by: zlareb1 --- .../loom_source_worker/direct_backend.py | 9 +- .../loom_source_worker/mcp_client.py | 49 +++++++++-- .../loom_source_worker/read_service.py | 16 ++-- source_worker/tests/test_mcp_client.py | 86 ++++++++++++++++++- source_worker/tests/test_protocol_servers.py | 8 +- source_worker/tests/test_read_service.py | 4 +- 6 files changed, 153 insertions(+), 19 deletions(-) diff --git a/source_worker/loom_source_worker/direct_backend.py b/source_worker/loom_source_worker/direct_backend.py index dfeddb9e7a..c5f5c7da97 100644 --- a/source_worker/loom_source_worker/direct_backend.py +++ b/source_worker/loom_source_worker/direct_backend.py @@ -65,7 +65,9 @@ class _MCPReader: def binding(self) -> ConnectionBinding: return self.record.binding - async def read_exact(self, resource_id: str, *, authorize: CurrentAccess) -> Document: + async def read_exact( + self, resource_id: str, *, authorize: CurrentAccess, deadline: float + ) -> Document: if resource_id != self.resource_id: raise ReadFailure("denied") config = replace(self.profile.config, approved_resource_ids=(self.resource_id,)) @@ -83,8 +85,9 @@ async def require_current() -> None: raise MCPSourceError("denied") from None try: - async with MCPSourceClient(config, bearer, validate_access=require_current) as client: - await client.discover() + async with MCPSourceClient( + config, bearer, validate_access=require_current, deadline=deadline + ) as client: item = await client.read(self.resource_id) receipt = item.receipt if ( diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index ebaaabe5c5..d058e68561 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -24,7 +24,7 @@ from mcp import ClientSession, types from mcp.client.streamable_http import streamable_http_client from mcp.shared.exceptions import McpError -from pydantic import AnyUrl +from pydantic import AnyUrl, ValidationError from referencing import Registry from referencing.exceptions import Unresolvable @@ -259,6 +259,16 @@ def _string(value: Any, maximum: int = 2048, *, empty: bool = False) -> str: return value +def _resource_url(identity: str) -> AnyUrl: + try: + uri = AnyUrl(identity) + except ValidationError: + raise MCPSourceError("unsupported") from None + if str(uri) != identity: + raise MCPSourceError("unsupported") + return uri + + def _endpoint_url(url: str) -> httpx.URL: try: _string(url, 2048) @@ -683,13 +693,17 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: body = await request.aread() if len(body) > 32_768: raise MCPSourceError("limit") + timeouts = dict(request.extensions.get("timeout", {})) + if request.method == "GET": + # Notifications may be idle until the session deadline. + timeouts["read"] = None outgoing = httpx.Request( request.method, self.target, headers=headers, content=body, extensions={ - "timeout": request.extensions.get("timeout", {}), + "timeout": timeouts, "sni_hostname": self.endpoint.raw_host.decode("ascii"), }, ) @@ -697,6 +711,8 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: response = await self.inner.handle_async_request(outgoing) self._check_state() _check_response(request.method, response) + if request.method == "DELETE": + return httpx.Response(response.status_code, content=b"") # Reject compression so the wire budget bounds decoded protocol bytes. if response.headers.get("content-encoding", "identity") != "identity": raise MCPSourceError("protocol") @@ -736,6 +752,7 @@ def __init__( credential: MCPBearer | None, *, validate_access: Callable[[], Awaitable[None]], + deadline: float | None = None, _transport: httpx.AsyncBaseTransport | None = None, ) -> None: if type(config.limits) is not MCPLimits or type(config.data_policy) is not MCPDataPolicy: @@ -777,6 +794,7 @@ def __init__( self._transport: _PinnedTransport | None = None self._operation_failure: ErrorCode | None = None self._deadline = 0.0 + self._outer_deadline = deadline self._discovery: MCPDiscovery | None = None self._tool_epoch = 0 self._discovered_epoch = -1 @@ -788,6 +806,9 @@ def __init__( self._selected_ids = frozenset( _string(identity) for identity in config.approved_resource_ids ) + if config.read is None: + for identity in self._selected_ids: + _resource_url(identity) self._resource_titles: dict[str, str] = {} def __repr__(self) -> str: @@ -857,6 +878,8 @@ async def __aenter__(self) -> MCPSourceClient: self._privacy.enter_context(private_work()) loop = asyncio.get_running_loop() self._deadline = loop.time() + self._config.limits.timeout_seconds + if self._outer_deadline is not None: + self._deadline = min(self._deadline, self._outer_deadline) self._ready = loop.create_future() self._owner_task = asyncio.create_task(self._serve_session()) try: @@ -941,6 +964,10 @@ async def _close(self) -> None: return if not self._closing: self._closing = True + if self._transport is not None: + self._transport.deadline = min( + self._deadline, asyncio.get_running_loop().time() + 1 + ) owner.cancel() interrupted: asyncio.CancelledError | None = None while not owner.done(): @@ -984,7 +1011,11 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T await self._authorize() self._check_state(require_session=True) assert self._session is not None - result = await action(self._session) + try: + result = await action(self._session) + except Exception: # Check authority before reporting an upstream error. + await self._authorize() + raise await self._authorize() self._check_state(require_session=True) return result @@ -1184,8 +1215,11 @@ async def action(session: ClientSession) -> MCPEvidence: return await self._read_tool(session, identity) if self._discovery is None or not self._discovery.resources: raise MCPSourceError("unsupported") - result = await session.read_resource(AnyUrl(identity)) - if not result.contents or len(result.contents) > self._config.limits.max_results: + result = await session.read_resource(_resource_url(identity)) + policy = self._config.data_policy + if not result.contents or len(result.contents) > min( + self._config.limits.max_results, policy.max_items + ): raise MCPSourceError("limit") texts: list[str] = [] size = 0 @@ -1198,7 +1232,10 @@ async def action(session: ClientSession) -> MCPEvidence: raise MCPSourceError("unsupported") if (content.mimeType or "text/plain") != mime_type: raise MCPSourceError("unsupported") - size += len(content.text.encode()) + bool(texts) + part_bytes = len(content.text.encode()) + if part_bytes > policy.max_string_bytes: + raise MCPSourceError("limit") + size += part_bytes + bool(texts) if size > self._config.limits.max_content_bytes: raise MCPSourceError("limit") texts.append(content.text) diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index e5730686d4..e3ca3b45c9 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -40,7 +40,9 @@ class BoundReader(Protocol): @property def binding(self) -> ConnectionBinding: ... - async def read_exact(self, resource_id: str, *, authorize: CurrentAccess) -> Document: ... + async def read_exact( + self, resource_id: str, *, authorize: CurrentAccess, deadline: float + ) -> Document: ... class ReadBackend(Protocol): @@ -133,14 +135,16 @@ async def require_current() -> None: if time.time() >= expires_at: raise ReadFailure("timeout") - async with ( - self._slot(binding.org), - asyncio.timeout(min(self._limits.timeout_seconds, expires_at - time.time())), - ): + deadline = asyncio.get_running_loop().time() + min( + self._limits.timeout_seconds, expires_at - time.time() + ) + async with self._slot(binding.org), asyncio.timeout_at(deadline): reader = await self._backend.resolve(binding) reader.binding.authorize(grant) await require_current() - document = await reader.read_exact(binding.resource_id, authorize=require_current) + document = await reader.read_exact( + binding.resource_id, authorize=require_current, deadline=deadline + ) fetched_at = int(time.time()) content_sha256 = self._check_document(binding, document) await require_current() diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 6f17a016c5..2f6bbeebb0 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -67,6 +67,9 @@ def __init__(self) -> None: self.redirect = False self.content_encoding = "identity" self.resource_text = "synthetic text" + self.resource_parts = 1 + self.notifications: _IdleBody | None = None + self.termination: _IdleBody | None = None self.change_tools_during_discovery = False async def aclose(self) -> None: @@ -76,6 +79,13 @@ async def respond(self, request: httpx.Request) -> httpx.Response: logging.getLogger("mcp.fixture").warning("synthetic private diagnostic") if request.method != "POST": self.calls.append((request, request.method)) + if request.method == "GET" and self.notifications is not None: + assert request.extensions["timeout"]["read"] is None + return httpx.Response( + 200, stream=self.notifications, headers={"content-type": "text/event-stream"} + ) + if request.method == "DELETE" and self.termination is not None: + return httpx.Response(200, stream=self.termination) return httpx.Response(405 if request.method == "GET" else 204) body = json.loads(request.content) method = body["method"] @@ -108,7 +118,9 @@ async def respond(self, request: httpx.Request) -> httpx.Response: await asyncio.Future[None]() finally: self.read_cancelled.set() - result = {"contents": [{"uri": _DOCUMENT, "text": self.resource_text}]} + result = { + "contents": [{"uri": _DOCUMENT, "text": self.resource_text}] * self.resource_parts + } envelope = json.dumps({"jsonrpc": "2.0", "id": body["id"], "result": result}) return httpx.Response( 200, @@ -150,6 +162,19 @@ async def __aiter__(self) -> AsyncIterator[bytes]: yield self.content[64:] +class _IdleBody(httpx.AsyncByteStream): + def __init__(self) -> None: + self.started = asyncio.Event() + self.closed = False + + async def __aiter__(self) -> AsyncIterator[bytes]: + self.started.set() + yield await asyncio.Future[bytes]() + + async def aclose(self) -> None: + self.closed = True + + def _json_response(request_id: int, result: dict[str, Any], **headers: str) -> httpx.Response: content = json.dumps({"jsonrpc": "2.0", "id": request_id, "result": result}).encode() return httpx.Response( @@ -409,6 +434,65 @@ async def validate_access() -> None: assert source.closed +@pytest.mark.asyncio +async def test_stateful_read_accepts_idle_notifications_and_does_not_drain_termination( + pin: list[str], +) -> None: + source = _Source() + source.notifications, source.termination = _IdleBody(), _IdleBody() + async with ( + asyncio.timeout(2), + _client(source, approved_resource_ids=(_DOCUMENT,)) as client, + ): + await source.notifications.started.wait() + assert (await client.read(_DOCUMENT)).text == source.resource_text + assert source.notifications.closed + assert source.termination.closed and not source.termination.started.is_set() + + +@pytest.mark.parametrize("identity", ["https://source.example", "https://résumé.example/item"]) +def test_resource_selection_refuses_a_uri_the_sdk_would_rewrite(identity: str) -> None: + source = _Source() + with pytest.raises(MCPSourceError, match="^MCP source unsupported$"): + _client(source, approved_resource_ids=(identity,)) + assert not source.calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("parts", "text", "policy"), + [(2, "a", MCPDataPolicy(max_items=1)), (1, "é" * 9, MCPDataPolicy(max_string_bytes=16))], +) +async def test_resource_content_respects_tightened_data_caps( + pin: list[str], parts: int, text: str, policy: MCPDataPolicy +) -> None: + source = _Source() + source.resource_parts, source.resource_text = parts, text + async with _client(source, approved_resource_ids=(_DOCUMENT,), data_policy=policy) as client: + with pytest.raises(MCPSourceError, match="^MCP source limit$"): + await client.read(_DOCUMENT) + + +@pytest.mark.asyncio +async def test_revocation_is_checked_after_a_mapped_tool_error(pin: list[str]) -> None: + source, mapping = _mapped_source() + source.tool_result = {"isError": True, "content": [{"type": "text", "text": "private error"}]} + + async def validate_access() -> None: + if any(method == "tools/call" for _, method in source.calls): + raise MCPSourceError("denied") + + config = MCPSourceConfig( + _ENDPOINT, approved_tools=("read",), read=mapping, approved_resource_ids=(_DOCUMENT,) + ) + async with MCPSourceClient( + config, None, validate_access=validate_access, _transport=source + ) as client: + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await client.read(_DOCUMENT) + assert source.closed + + @pytest.mark.asyncio async def test_revocation_after_remote_read_is_reported_without_waiting_for_timeout( pin: list[str], diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index 2b39a59f08..14665b98e1 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -17,7 +17,7 @@ from loom_source_worker.credential_store import CredentialRecord from loom_source_worker.direct_backend import DirectBackend from loom_source_worker.main import _parse_settings -from loom_source_worker.mcp_client import MCPSourceConfig, MCPToolMapping +from loom_source_worker.mcp_client import MCPLimits, MCPSourceConfig, MCPToolMapping from loom_source_worker.protocol import ConnectionBinding, ReadBinding, ReadGrant, issue_read_grant from loom_source_worker.read_service import ReadFailure, ReadLimits, ReadService from mcp import types @@ -146,6 +146,7 @@ def on_read() -> None: endpoint=_ENDPOINT, bearer_audience=_ENDPOINT, approved_tools=("read",), + limits=MCPLimits(max_requests=4), read=MCPToolMapping( name="read", input_schema=_INPUT, output_schema=_OUTPUT, argument_name="id" ), @@ -164,11 +165,14 @@ async def synthetic_pin(host: str) -> ipaddress.IPv6Address: assert host == "source.example.test" return ipaddress.IPv6Address("2600::10") - def routed_client(config: Any, credential: Any, *, validate_access: Any) -> Any: + def routed_client( + config: Any, credential: Any, *, validate_access: Any, deadline: float + ) -> Any: return mcp_client.MCPSourceClient( config, credential, validate_access=validate_access, + deadline=deadline, _transport=_FragmentedASGI(app=app), ) diff --git a/source_worker/tests/test_read_service.py b/source_worker/tests/test_read_service.py index 67419727d3..203cfe1bb5 100644 --- a/source_worker/tests/test_read_service.py +++ b/source_worker/tests/test_read_service.py @@ -36,7 +36,9 @@ async def resolve(self, binding: ReadBinding) -> BoundReader: async def current(self, binding: ReadBinding) -> ConnectionBinding: return self.binding - async def read_exact(self, resource_id: str, *, authorize: CurrentAccess) -> Document: + async def read_exact( + self, resource_id: str, *, authorize: CurrentAccess, deadline: float + ) -> Document: await authorize() self.calls.append(resource_id) self.started.set() From 52a4f8489a7ed95490dbd41feb4c98d059bbfbc4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 09:11:04 +0000 Subject: [PATCH 06/31] Verify raw resource receipts and terminate cancelled sessions Signed-off-by: zlareb1 (cherry picked from commit 36ac2f0258998f1b2ad69fe7949d17ab9f29da7c) --- .../loom_source_worker/mcp_client.py | 84 ++++++++++++------- source_worker/tests/test_mcp_client.py | 73 +++++++++++++++- source_worker/tests/test_protocol_servers.py | 60 +++++++++++-- 3 files changed, 179 insertions(+), 38 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index d058e68561..d90ca330f5 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -554,6 +554,35 @@ def _tool_value( return value +def _resource_value( + result: types.Result, identity: str, limits: MCPLimits, policy: MCPDataPolicy +) -> tuple[str, str]: + data = result.model_dump(by_alias=True, exclude_unset=True) + _bounded_data(data, limits.max_wire_bytes, policy) + contents = data.get("contents") + if not isinstance(contents, list) or not contents or len(contents) > limits.max_results: + raise MCPSourceError("limit") + texts: list[str] = [] + mime_type = "text/plain" + size = 0 + for part in contents: + if not isinstance(part, dict) or part.get("uri") != identity or "blob" in part: + raise MCPSourceError("unsupported") + text = part.get("text") + mime = part.get("mimeType") + if not isinstance(text, str) or (mime is not None and not isinstance(mime, str)): + raise MCPSourceError("unsupported") + mime = mime or "text/plain" + if texts and mime != mime_type: + raise MCPSourceError("unsupported") + mime_type = mime + size += len(text.encode()) + bool(texts) + if size > limits.max_content_bytes: + raise MCPSourceError("limit") + texts.append(text) + return "\n".join(texts), _string(mime_type, 128) + + def _check_tool_schema(tool: types.Tool, mapping: MCPToolMapping, policy: MCPDataPolicy) -> None: _schema(tool.inputSchema, policy) if _json(tool.inputSchema, 16_384) != _json(mapping.input_schema, 16_384): @@ -630,6 +659,7 @@ def __init__( self.target: httpx.URL | None = None self.pin_lock = asyncio.Lock() self.failure: ErrorCode | None = None + self.terminate_only = False def _check_state(self) -> None: _guard_state(self.deadline, self.failure) @@ -652,6 +682,8 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: try: async with asyncio.timeout_at(self.deadline): self._check_state() + if self.terminate_only and request.method != "DELETE": + raise asyncio.CancelledError if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: raise MCPSourceError("denied") self.requests += 1 @@ -840,11 +872,14 @@ def _with_receipt( def _check_state(self, *, require_session: bool = False) -> None: owner = self._owner_task - failure = self._operation_failure or self._owner_failure + lifecycle = not require_session and asyncio.current_task() is owner + failure = self._operation_failure + # A cancelled read may still release its stateful session with current authority. + if lifecycle and self._closing and failure == "closed": + failure = None + failure = failure or self._owner_failure if failure is None and self._transport is not None: failure = self._transport.failure - # The lifecycle owner may perform SDK session termination during cleanup. - lifecycle = not require_session and asyncio.current_task() is owner active = ( owner is not None and not owner.done() @@ -965,6 +1000,7 @@ async def _close(self) -> None: if not self._closing: self._closing = True if self._transport is not None: + self._transport.terminate_only = True self._transport.deadline = min( self._deadline, asyncio.get_running_loop().time() + 1 ) @@ -1014,7 +1050,7 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T try: result = await action(self._session) except Exception: # Check authority before reporting an upstream error. - await self._authorize() + await self._validate_access() raise await self._authorize() self._check_state(require_session=True) @@ -1215,37 +1251,25 @@ async def action(session: ClientSession) -> MCPEvidence: return await self._read_tool(session, identity) if self._discovery is None or not self._discovery.resources: raise MCPSourceError("unsupported") - result = await session.read_resource(_resource_url(identity)) - policy = self._config.data_policy - if not result.contents or len(result.contents) > min( - self._config.limits.max_results, policy.max_items - ): - raise MCPSourceError("limit") - texts: list[str] = [] - size = 0 - mime_type = result.contents[0].mimeType or "text/plain" - for content in result.contents: - if ( - not isinstance(content, types.TextResourceContents) - or str(content.uri) != identity - ): - raise MCPSourceError("unsupported") - if (content.mimeType or "text/plain") != mime_type: - raise MCPSourceError("unsupported") - part_bytes = len(content.text.encode()) - if part_bytes > policy.max_string_bytes: - raise MCPSourceError("limit") - size += part_bytes + bool(texts) - if size > self._config.limits.max_content_bytes: - raise MCPSourceError("limit") - texts.append(content.text) + # Read the wire URI before AnyUrl can normalize its spelling. + result = await session.send_request( + types.ClientRequest( + types.ReadResourceRequest( + params=types.ReadResourceRequestParams(uri=_resource_url(identity)) + ) + ), + types.Result, + ) + text, mime_type = _resource_value( + result, identity, self._config.limits, self._config.data_policy + ) return self._with_receipt( MCPEvidence( identity, identity, self._resource_titles.get(identity, identity), - "\n".join(texts), - _string(mime_type, 128), + text, + mime_type, ), "resources/read", ) diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 2f6bbeebb0..d52629bf5b 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -67,7 +67,10 @@ def __init__(self) -> None: self.redirect = False self.content_encoding = "identity" self.resource_text = "synthetic text" + self.resource_uri = _DOCUMENT self.resource_parts = 1 + self.resource_error: int | None = None + self.resource_extensions: dict[str, Any] = {} self.notifications: _IdleBody | None = None self.termination: _IdleBody | None = None self.change_tools_during_discovery = False @@ -113,13 +116,17 @@ async def respond(self, request: httpx.Request) -> httpx.Response: ) elif method == "resources/read": self.read_started.set() + if self.resource_error is not None: + return httpx.Response(self.resource_error) if self.stall: try: await asyncio.Future[None]() finally: self.read_cancelled.set() result = { - "contents": [{"uri": _DOCUMENT, "text": self.resource_text}] * self.resource_parts + "contents": [{"uri": self.resource_uri, "text": self.resource_text}] + * self.resource_parts, + **self.resource_extensions, } envelope = json.dumps({"jsonrpc": "2.0", "id": body["id"], "result": result}) return httpx.Response( @@ -458,6 +465,17 @@ def test_resource_selection_refuses_a_uri_the_sdk_would_rewrite(identity: str) - assert not source.calls +@pytest.mark.asyncio +async def test_resource_receipt_requires_exact_wire_uri(pin: list[str]) -> None: + source = _Source() + source.resource_uri = "https://source.example" + identity = "https://source.example/" + async with _client(source, approved_resource_ids=(identity,)) as client: + with pytest.raises(MCPSourceError, match="^MCP source unsupported$"): + await client.read(identity) + assert source.read_started.is_set() + + @pytest.mark.asyncio @pytest.mark.parametrize( ("parts", "text", "policy"), @@ -473,6 +491,25 @@ async def test_resource_content_respects_tightened_data_caps( await client.read(_DOCUMENT) +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("extensions", "policy"), + [ + ({"_meta": {"nested": {"data": {"too": {"deep": True}}}}}, MCPDataPolicy(max_depth=4)), + ({"extension": "é" * 16}, MCPDataPolicy(max_string_bytes=30)), + ({"extension": list(range(12))}, MCPDataPolicy(max_nodes=13)), + ], +) +async def test_resource_parser_bounds_cover_metadata_and_extensions( + pin: list[str], extensions: dict[str, Any], policy: MCPDataPolicy +) -> None: + source = _Source() + source.resource_extensions = extensions + async with _client(source, approved_resource_ids=(_DOCUMENT,), data_policy=policy) as client: + with pytest.raises(MCPSourceError, match="^MCP source limit$"): + await client.read(_DOCUMENT) + + @pytest.mark.asyncio async def test_revocation_is_checked_after_a_mapped_tool_error(pin: list[str]) -> None: source, mapping = _mapped_source() @@ -493,6 +530,24 @@ async def validate_access() -> None: assert source.closed +@pytest.mark.asyncio +async def test_revocation_wins_over_upstream_reconnect(pin: list[str]) -> None: + source = _Source() + source.resource_error = 401 + + async def validate_access() -> None: + if source.read_started.is_set(): + raise MCPSourceError("denied") + + config = MCPSourceConfig(_ENDPOINT, approved_resource_ids=(_DOCUMENT,)) + async with MCPSourceClient( + config, None, validate_access=validate_access, _transport=source + ) as client: + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await client.read(_DOCUMENT) + assert source.closed + + @pytest.mark.asyncio async def test_revocation_after_remote_read_is_reported_without_waiting_for_timeout( pin: list[str], @@ -525,10 +580,21 @@ async def test_session_deadline_cancels_stalled_read(pin: list[str]) -> None: @pytest.mark.asyncio -async def test_cancel_drains_owned_sdk_request_before_return(pin: list[str]) -> None: +@pytest.mark.parametrize("revoked", [False, True]) +async def test_cancel_joins_sdk_and_only_terminates_current_session( + pin: list[str], revoked: bool +) -> None: source = _Source() source.stall = True - async with _client(source, approved_resource_ids=(_DOCUMENT,)) as client: + + async def validate_access() -> None: + if revoked and source.read_started.is_set(): + raise MCPSourceError("denied") + + config = MCPSourceConfig(_ENDPOINT, approved_resource_ids=(_DOCUMENT,)) + async with MCPSourceClient( + config, None, validate_access=validate_access, _transport=source + ) as client: read = asyncio.create_task(client.read(_DOCUMENT)) async with asyncio.timeout(3): await source.read_started.wait() @@ -536,5 +602,6 @@ async def test_cancel_drains_owned_sdk_request_before_return(pin: list[str]) -> with pytest.raises(asyncio.CancelledError): await read assert source.read_cancelled.is_set() and source.closed + assert sum(method == "DELETE" for _, method in source.calls) == int(not revoked) with pytest.raises(MCPSourceError, match="^MCP source closed$"): await client.read(_DOCUMENT) diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index 14665b98e1..b34d009425 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import ipaddress import json import time @@ -42,6 +43,11 @@ } +async def _synthetic_pin(host: str) -> ipaddress.IPv6Address: + assert host == "source.example.test" + return ipaddress.IPv6Address("2600::10") + + class _SyntheticAccounts: def __init__(self, binding: ReadBinding) -> None: self.records: dict[UUID, CredentialRecord] = {} @@ -161,10 +167,6 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None: await manager.handle_request(scope, receive, send) - async def synthetic_pin(host: str) -> ipaddress.IPv6Address: - assert host == "source.example.test" - return ipaddress.IPv6Address("2600::10") - def routed_client( config: Any, credential: Any, *, validate_access: Any, deadline: float ) -> Any: @@ -176,7 +178,7 @@ def routed_client( _transport=_FragmentedASGI(app=app), ) - monkeypatch.setattr(mcp_client, "resolve_public_address", synthetic_pin) + monkeypatch.setattr(mcp_client, "resolve_public_address", _synthetic_pin) monkeypatch.setattr(direct_backend, "MCPSourceClient", routed_client) worker_id = uuid4() settings = _parse_settings( @@ -252,3 +254,51 @@ def grant(target: ReadBinding, operation: str) -> str: revoke = bob.connection_id with pytest.raises(ReadFailure, match="^denied$"): await service.execute(grant(bob, "live"), "live") + + +@pytest.mark.asyncio +async def test_cancel_terminates_an_active_stateful_sdk_session( + monkeypatch: pytest.MonkeyPatch, +) -> None: + started = asyncio.Event() + terminations: list[tuple[bytes, int]] = [] + server: Server[Any, Any] = Server("synthetic-stateful-resources") + + @server.list_resources() + async def list_resources() -> list[types.Resource]: + return [types.Resource(uri=AnyUrl(_DOC), name="Resource")] + + @server.read_resource() + async def read_resource(uri: AnyUrl) -> str: + assert str(uri) == _DOC + started.set() + return await asyncio.Future[str]() + + manager = StreamableHTTPSessionManager(app=server, json_response=True, stateless=False) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + async def watch(message: Any) -> None: + if scope["method"] == "DELETE" and message["type"] == "http.response.start": + terminations.append((dict(scope["headers"])[b"mcp-session-id"], message["status"])) + await send(message) + + await manager.handle_request(scope, receive, watch) + + async def validate() -> None: + return None + + monkeypatch.setattr(mcp_client, "resolve_public_address", _synthetic_pin) + config = MCPSourceConfig(endpoint=_ENDPOINT, approved_resource_ids=(_DOC,)) + async with ( + asyncio.timeout(5), + manager.run(), + mcp_client.MCPSourceClient( + config, None, validate_access=validate, _transport=httpx.ASGITransport(app=app) + ) as client, + ): + read = asyncio.create_task(client.read(_DOC)) + await started.wait() + read.cancel() + with pytest.raises(asyncio.CancelledError): + await read + assert len(terminations) == 1 and terminations[0][0] and terminations[0][1] == 200 From 7d221892a1d057f5ed92a51b0163111c8c2f8d62 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 09:03:26 +0000 Subject: [PATCH 07/31] Package the source worker behind a private Compose proxy Signed-off-by: zlareb1 (cherry picked from commit 2042b82be31c3c8a4cde317427b10af3d70df4d9) --- .../mcp-source-worker-deployment.yml | 28 + source_worker/README.md | 22 +- source_worker/compose.yaml | 94 ++++ source_worker/proxy.conf | 83 +++ source_worker/qualification/compose_smoke.py | 281 ++++++++++ source_worker/qualification/fixture.py | 494 ++++++++++++++++++ 6 files changed, 1000 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/mcp-source-worker-deployment.yml create mode 100644 source_worker/compose.yaml create mode 100644 source_worker/proxy.conf create mode 100644 source_worker/qualification/compose_smoke.py create mode 100644 source_worker/qualification/fixture.py diff --git a/.github/workflows/mcp-source-worker-deployment.yml b/.github/workflows/mcp-source-worker-deployment.yml new file mode 100644 index 0000000000..b15f4a250a --- /dev/null +++ b/.github/workflows/mcp-source-worker-deployment.yml @@ -0,0 +1,28 @@ +name: MCP source worker deployment smoke + +on: + pull_request: + paths: + - .github/workflows/mcp-source-worker-deployment.yml + - source_worker/** + workflow_dispatch: + +permissions: + contents: read + +jobs: + compose: + name: External worker and mTLS proxy on Docker Compose + runs-on: ubuntu-24.04 + timeout-minutes: 15 + env: + QUALIFICATION_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ env.QUALIFICATION_SHA }} + persist-credentials: false + sparse-checkout: /source_worker/ + sparse-checkout-cone-mode: false + - name: Qualify the exact checkout with synthetic credentials + run: python3 -IBu source_worker/qualification/compose_smoke.py diff --git a/source_worker/README.md b/source_worker/README.md index 62c280e8dc..1ee68d8c5c 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -53,6 +53,24 @@ capacity limits. It never authorizes a stored write. The issuer must check selection and requester authority before issuing it and before delivering a result. The worker rechecks its connection during the read and before reply. +## Docker Compose + +`compose.yaml` starts the worker and its TLS proxy only when the `source-worker` +profile is selected. Place the worker configuration and public grant verifier +under `operator/worker/config`, the credential service token under +`operator/worker/credentials`, and the TLS server chain, private key and trusted +client CA under `operator/proxy`. Supply these files through deployment secret +management and keep them out of the image and repository. + +The proxy is reachable only from the internal `worker-ingress` network. Attach +the approved grant issuer to that network and configure it to verify the proxy +certificate by name and present its own client certificate. The manifest does +not publish a host port. Only the worker joins the egress network. Restrict that +network to approved MCP hosts, DNS and the credential backend through host or +infrastructure policy; Compose network membership alone does not allowlist +outbound destinations. + The hosted package test uses owned SDK resource and mapped-tool servers with -synthetic accounts. It does not qualify production credential infrastructure -or a particular external service. +synthetic accounts. The separate deployment smoke uses the Compose image and +proxy with synthetic certificates and a credential fixture. These tests do not +qualify production credential infrastructure or a particular external service. diff --git a/source_worker/compose.yaml b/source_worker/compose.yaml new file mode 100644 index 0000000000..1ecb893ae9 --- /dev/null +++ b/source_worker/compose.yaml @@ -0,0 +1,94 @@ +services: + source-worker: + profiles: [source-worker] + build: + context: . + user: "10001:10001" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + stop_grace_period: 35s + networks: [worker-egress] + volumes: + - type: bind + source: ./operator/worker/config + target: /etc/loom-source-worker + read_only: true + bind: + create_host_path: false + - type: bind + source: ./operator/worker/credentials + target: /run/loom-source-worker/credentials + read_only: true + bind: + create_host_path: false + - type: volume + source: worker-socket + target: /run/loom-source-worker/socket + volume: + nocopy: true + + source-worker-proxy: + profiles: [source-worker] + image: nginx:1.30.8-alpine@sha256:6437a63b5c529f0e06162b3f593c0154cff6fa2ea0f94fd7c27928cb399e022d + user: "10001:10001" + entrypoint: [nginx] + command: [-e, /dev/null, -g, "daemon off;", -c, /etc/nginx/nginx.conf] + depends_on: [source-worker] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + logging: + driver: "none" + networks: [worker-ingress] + tmpfs: + - /tmp:rw,nosuid,nodev,noexec,size=1m,mode=0700,uid=10001,gid=10001 + volumes: + - type: bind + source: ./proxy.conf + target: /etc/nginx/nginx.conf + read_only: true + bind: + create_host_path: false + - type: bind + source: ./operator/proxy/server-chain.pem + target: /etc/nginx/tls/server-chain.pem + read_only: true + bind: + create_host_path: false + - type: bind + source: ./operator/proxy/server-key.pem + target: /etc/nginx/tls/server-key.pem + read_only: true + bind: + create_host_path: false + - type: bind + source: ./operator/proxy/client-ca.pem + target: /etc/nginx/tls/client-ca.pem + read_only: true + bind: + create_host_path: false + - type: volume + source: worker-socket + target: /run/loom-source-worker/socket + read_only: true + volume: + nocopy: true + +networks: + worker-ingress: + driver: bridge + internal: true + enable_ipv6: false + driver_opts: + com.docker.network.bridge.gateway_mode_ipv4: isolated + worker-egress: + driver: bridge + +volumes: + worker-socket: + driver: local + driver_opts: + type: tmpfs + device: tmpfs + o: "uid=10001,gid=10001,mode=0700,size=64k,nosuid,nodev,noexec" diff --git a/source_worker/proxy.conf b/source_worker/proxy.conf new file mode 100644 index 0000000000..bd595f8dcf --- /dev/null +++ b/source_worker/proxy.conf @@ -0,0 +1,83 @@ +worker_processes 1; +pid /tmp/nginx.pid; +error_log /dev/null crit; + +events { + worker_connections 768; +} + +http { + access_log off; + server_tokens off; + + client_body_temp_path /tmp/client_body; + proxy_temp_path /tmp/proxy; + fastcgi_temp_path /tmp/fastcgi; + uwsgi_temp_path /tmp/uwsgi; + scgi_temp_path /tmp/scgi; + + client_header_buffer_size 1k; + large_client_header_buffers 1 31k; + max_headers 64; + client_header_timeout 5s; + client_body_timeout 5s; + client_max_body_size 1; + keepalive_timeout 0; + send_timeout 5s; + + server { + listen 8443 ssl; + server_name source-worker-proxy; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_certificate /etc/nginx/tls/server-chain.pem; + ssl_certificate_key /etc/nginx/tls/server-key.pem; + ssl_client_certificate /etc/nginx/tls/client-ca.pem; + ssl_verify_client on; + ssl_verify_depth 2; + ssl_early_data off; + ssl_session_cache off; + ssl_session_tickets off; + + error_page 497 = @drop_cleartext; + add_header Cache-Control no-store always; + + location @drop_cleartext { + return 444; + } + + location / { + if ($request !~ "^POST /v1/(live|check-access) HTTP/1[.]1$") { + return 404; + } + if ($content_length !~ "^0?$") { + return 400; + } + if ($http_transfer_encoding != "") { + return 400; + } + + proxy_pass http://unix:/run/loom-source-worker/socket/worker.sock; + proxy_http_version 1.1; + proxy_pass_request_headers off; + proxy_pass_request_body off; + proxy_set_header Host source-worker; + proxy_set_header Authorization $http_authorization; + proxy_set_header Content-Length ""; + proxy_set_header Transfer-Encoding ""; + + proxy_buffering off; + proxy_request_buffering off; + proxy_max_temp_file_size 0; + proxy_cache off; + proxy_store off; + proxy_ignore_headers X-Accel-Buffering X-Accel-Redirect; + proxy_hide_header Cache-Control; + proxy_redirect off; + proxy_next_upstream off; + proxy_connect_timeout 1s; + proxy_send_timeout 5s; + proxy_read_timeout 35s; + } + } +} diff --git a/source_worker/qualification/compose_smoke.py b/source_worker/qualification/compose_smoke.py new file mode 100644 index 0000000000..07d7ce510d --- /dev/null +++ b/source_worker/qualification/compose_smoke.py @@ -0,0 +1,281 @@ +"""Run the joined Compose deployment on an ephemeral GitHub-hosted Linux runner.""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import tempfile +from pathlib import Path + +SOURCE = Path(__file__).resolve().parents[1] +FIXTURE = Path(__file__).with_name("fixture.py").resolve() +WORKER = "source-worker" +PROXY = "source-worker-proxy" +SOCKET_DIR = "/run/loom-source-worker/socket" +CONFIG_DIR = "/etc/loom-source-worker" +CREDENTIAL_DIR = "/run/loom-source-worker/credentials" + + +def command(*args: str, capture: bool = False, check: bool = True) -> subprocess.CompletedProcess: + result = subprocess.run(args, check=False, text=True, capture_output=capture, timeout=360) + if check and result.returncode != 0: + raise RuntimeError(f"{args[:2]} exited with code {result.returncode}") + return result + + +def output(*args: str) -> str: + return command(*args, capture=True).stdout.strip() + + +def inspect(kind: str, name: str) -> dict: + return json.loads(output("docker", kind, "inspect", name))[0] + + +def assert_service( + container: dict, network: str, own_mounts: dict[str, Path], *, proxy: bool +) -> None: + config, host = container["Config"], container["HostConfig"] + assert container["State"]["Running"], "service is not running" + assert config["User"] == "10001:10001", "service UID/GID changed" + assert host["ReadonlyRootfs"] and host["CapDrop"] == ["ALL"] and not host["CapAdd"] + assert {"no-new-privileges", "no-new-privileges:true", "no-new-privileges=true"}.intersection( + host["SecurityOpt"] + ) + assert not host["PortBindings"] and not host["PublishAllPorts"], "published ports" + assert set(container["NetworkSettings"]["Networks"]) == {network} + mounts = {mount["Destination"]: mount for mount in container["Mounts"]} + if proxy: + assert set(host["Tmpfs"]) == {"/tmp"} + if "/tmp" in mounts: + assert mounts.pop("/tmp")["Type"] == "tmpfs" + assert set(mounts) == own_mounts.keys() | {SOCKET_DIR}, "unexpected service mounts" + for destination, source in own_mounts.items(): + mount = mounts[destination] + assert not mount["RW"] and mount["Type"] == "bind" and mount["Source"] == str(source) + assert mounts[SOCKET_DIR]["Type"] == "volume" and mounts[SOCKET_DIR]["RW"] != proxy + if proxy: + assert host["LogConfig"]["Type"] == "none", "proxy logging is enabled" + + +def qualify(root: Path) -> None: + project = root.name.replace("_", "-") + worker_image = f"{project}-{WORKER}" + kv_name = f"{project}-kv" + caller_name = f"{project}-caller" + setup_name = f"{project}-setup" + ingress, egress = f"{project}_worker-ingress", f"{project}_worker-egress" + volume = f"{project}_worker-socket" + source = root / "source_worker" + source.mkdir() + for name in ("Dockerfile", ".dockerignore", "pyproject.toml", "compose.yaml", "proxy.conf"): + shutil.copyfile(SOURCE / name, source / name) + shutil.copytree(SOURCE / "loom_source_worker", source / "loom_source_worker") + + compose = ( + "docker", + "compose", + "--env-file", + "/dev/null", + "-p", + project, + "-f", + str(source / "compose.yaml"), + ) + enabled = (*compose, "--profile", "source-worker") + operator = source / "operator" + helper = ( + "docker", + "run", + "--rm", + "--user", + f"{os.getuid()}:{os.getgid()}", + "--read-only", + "--cap-drop", + "ALL", + "--security-opt", + "no-new-privileges:true", + "--mount", + f"type=bind,src={FIXTURE},dst=/fixture.py,readonly", + "--entrypoint", + "python", + ) + + def start_caller(mode: str) -> None: + command( + *helper, + "--name", + caller_name, + "--network", + ingress, + "--mount", + f"type=bind,src={root / 'caller'},dst=/caller,readonly", + "--mount", + f"type=bind,src={root / 'signals'},dst=/signals,readonly", + worker_image, + "-IBu", + "/fixture.py", + mode, + ) + + try: + disabled = json.loads(output(*compose, "config", "--format", "json")) + active = json.loads(output(*enabled, "config", "--format", "json")) + assert not disabled.get("services"), "worker profile is enabled by default" + assert set(active["services"]) == {WORKER, PROXY}, "unexpected enabled services" + proxy_image = active["services"][PROXY]["image"] + assert re.fullmatch(r"nginx:[^@]+@sha256:[0-9a-f]{64}", proxy_image), "proxy is not pinned" + command(*enabled, "build", "--pull", WORKER) + command(*enabled, "pull", PROXY) + for image in (worker_image, proxy_image): + info = inspect("image", image) + print( + f"{image}: {info['Os']}/{info['Architecture']} {info['Id']} {info['RepoDigests']}" + ) + + command( + *helper, + "--name", + setup_name, + "--network", + "none", + "--mount", + f"type=bind,src={root},dst=/work", + worker_image, + "-IBu", + "/fixture.py", + "prepare", + ) + command( + "sudo", + "chown", + "root:10001", + str(operator / "worker/credentials/vault-token"), + str(operator / "proxy/server-key.pem"), + ) + command(*enabled, "up", "-d", "--no-build", "--pull", "never") + command( + *helper, + "-d", + "--name", + kv_name, + "--network", + egress, + "--network-alias", + "synthetic-kv", + "--mount", + f"type=bind,src={root / 'kv'},dst=/kv,readonly", + "--mount", + f"type=bind,src={root / 'signals'},dst=/signals", + worker_image, + "-IBu", + "/fixture.py", + "serve", + ) + + ingress_info = inspect("network", ingress) + assert ingress_info["Internal"] and not ingress_info["EnableIPv6"] + assert ingress_info["Options"]["com.docker.network.bridge.gateway_mode_ipv4"] == "isolated" + worker_id, proxy_id = (output(*enabled, "ps", "-q", service) for service in (WORKER, PROXY)) + worker, proxy = (inspect("container", name) for name in (worker_id, proxy_id)) + assert_service( + worker, + egress, + { + CONFIG_DIR: operator / "worker/config", + CREDENTIAL_DIR: operator / "worker/credentials", + }, + proxy=False, + ) + assert_service( + proxy, + ingress, + { + "/etc/nginx/nginx.conf": source / "proxy.conf", + **{ + f"/etc/nginx/tls/{name}": operator / "proxy" / name + for name in ("server-chain.pem", "server-key.pem", "client-ca.pem") + }, + }, + proxy=True, + ) + assert all( + next(mount for mount in service["Mounts"] if mount["Destination"] == SOCKET_DIR)["Name"] + == volume + for service in (worker, proxy) + ), "services do not share exactly the owned socket volume" + + start_caller("probe") + proxy_address = proxy["NetworkSettings"]["Networks"][ingress]["IPAddress"] + command( + "docker", "exec", kv_name, "python", "-IB", "/fixture.py", "isolated", proxy_address + ) + kv_inputs = json.loads((root / "kv/inputs.json").read_text()) + for name in ("vault_token", "upstream_token"): + assert all(kv_inputs[name] not in json.dumps(service) for service in (worker, proxy)) + listeners = "".join( + output("docker", "exec", worker_id, "cat", path) + "\n" + for path in ("/proc/net/tcp", "/proc/net/tcp6") + ) + assert not any( + fields[3] == "0A" and fields[1].split(":")[0] != "0B00007F" + for line in listeners.splitlines() + if (fields := line.split()) and fields[0] != "sl" + ), "worker has a TCP listener other than the Docker DNS stub" + assert ( + output("docker", "exec", proxy_id, "stat", "-c", "%a:%u:%g", SOCKET_DIR) + == "700:10001:10001" + ) + socket_path = f"{SOCKET_DIR}/worker.sock" + command("docker", "exec", proxy_id, "test", "-S", socket_path) + assert ( + output("docker", "exec", proxy_id, "stat", "-c", "%a:%u:%g", socket_path) + == "600:10001:10001" + ) + command(*enabled, "stop", WORKER) + command("docker", "exec", proxy_id, "test", "!", "-e", socket_path) + start_caller("stopped") + command(*enabled, "start", WORKER) + start_caller("ready") + print("PASS: profile, runtime isolation, socket ownership, stop and restart") + finally: + for name in (caller_name, kv_name, setup_name): + command("docker", "rm", "-f", name, capture=True, check=False) + command(*enabled, "down", "--volumes") + assert not output(*enabled, "ps", "--all", "--quiet"), "Compose project containers remain" + for kind, name in (("network", ingress), ("network", egress), ("volume", volume)): + assert ( + command("docker", kind, "inspect", name, capture=True, check=False).returncode != 0 + ) + for name in (caller_name, kv_name, setup_name): + assert ( + command( + "docker", "container", "inspect", name, capture=True, check=False + ).returncode + != 0 + ) + command("docker", "image", "rm", worker_image, capture=True, check=False) + + +def main() -> None: + assert ( + os.environ.get("GITHUB_ACTIONS") == "true" + and os.environ.get("RUNNER_ENVIRONMENT") == "github-hosted" + ) + sha = os.environ["QUALIFICATION_SHA"] + assert re.fullmatch(r"[0-9a-f]{40}", sha) and output("git", "rev-parse", "HEAD") == sha + assert not os.environ.get("COMPOSE_PROFILES"), "unexpected active profiles" + print( + f"Checkout {sha}; runner {os.environ['RUNNER_OS']}/{os.environ['RUNNER_ARCH']}; " + f"image {os.environ.get('ImageOS')}/{os.environ.get('ImageVersion')}" + ) + command("docker", "version", "--format", "{{.Server.Version}} {{.Server.Os}}/{{.Server.Arch}}") + command("docker", "compose", "version") + with tempfile.TemporaryDirectory(prefix="mcp-deploy-", dir=os.environ["RUNNER_TEMP"]) as work: + qualify(Path(work)) + + +if __name__ == "__main__": + main() diff --git a/source_worker/qualification/fixture.py b/source_worker/qualification/fixture.py new file mode 100644 index 0000000000..2d4b076933 --- /dev/null +++ b/source_worker/qualification/fixture.py @@ -0,0 +1,494 @@ +"""Synthetic inputs, HTTPS KV replies, and mTLS probes for the Compose smoke.""" + +from __future__ import annotations + +import errno +import http.client +import json +import secrets +import socket +import ssl +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from dataclasses import asdict +from datetime import UTC, datetime, timedelta +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib.metadata import version +from pathlib import Path +from uuid import uuid4 + +import jwt +from cryptography import x509 +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, ed25519 +from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, + load_pem_private_key, +) +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from loom_source_worker.direct_backend import ApprovedProfile +from loom_source_worker.mcp_client import MCPSourceConfig +from loom_source_worker.protocol import ReadBinding, ReadGrant, issue_read_grant + +PROXY = "source-worker-proxy" +KV = "synthetic-kv" +ISSUER = "urn:loom:qualification" +ORG = "smoke-org" +OWNER = "smoke-user" +PRIVATE_MCP = "https://127.0.0.1:9443" +SIGNALS = Path("/signals") +CALLER = Path("/caller") + + +def write(path: Path, data: bytes, mode: int = 0o644) -> None: + with path.open("xb") as stream: + stream.write(data) + path.chmod(mode) + + +def private_bytes(key: ec.EllipticCurvePrivateKey | ed25519.Ed25519PrivateKey) -> bytes: + return key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + + +def issue_certificate(name: str, ca=None, purpose=None, *, expired: bool = False): + key = ec.generate_private_key(ec.SECP256R1()) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]) + signing_key, issuer = ca if ca is not None else (key, None) + now = datetime.now(UTC) + end = now - timedelta(hours=1) if expired else now + timedelta(hours=2) + builder = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(issuer.subject if issuer is not None else subject) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(hours=2)) + .not_valid_after(end) + .add_extension(x509.BasicConstraints(ca=ca is None, path_length=None), critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) + .add_extension( + x509.AuthorityKeyIdentifier.from_issuer_public_key(signing_key.public_key()), + critical=False, + ) + .add_extension( + x509.KeyUsage( + digital_signature=ca is not None, + content_commitment=False, + key_encipherment=False, + data_encipherment=False, + key_agreement=False, + key_cert_sign=ca is None, + crl_sign=ca is None, + encipher_only=False, + decipher_only=False, + ), + critical=True, + ) + ) + if purpose is not None: + builder = builder.add_extension(x509.ExtendedKeyUsage([purpose]), critical=False) + if purpose == ExtendedKeyUsageOID.SERVER_AUTH: + builder = builder.add_extension( + x509.SubjectAlternativeName([x509.DNSName(name)]), critical=False + ) + return key, builder.sign(signing_key, hashes.SHA256()) + + +def prepare(root: Path) -> None: + operator = root / "source_worker/operator" + config, credentials, proxy = ( + operator / subdir for subdir in ("worker/config", "worker/credentials", "proxy") + ) + caller, kv, signals = (root / name for name in ("caller", "kv", "signals")) + for directory in (config, credentials, proxy, caller, kv, signals): + directory.mkdir(parents=True, mode=0o755) + caller.chmod(0o700) + kv.chmod(0o700) + + server_ca, client_ca, foreign_ca, vault_ca = ( + issue_certificate(name) + for name in ("smoke-server-ca", "smoke-client-ca", "foreign-ca", "smoke-kv-ca") + ) + write(caller / "server-ca.pem", server_ca[1].public_bytes(Encoding.PEM)) + write(caller / "foreign-ca.pem", foreign_ca[1].public_bytes(Encoding.PEM)) + write(proxy / "client-ca.pem", client_ca[1].public_bytes(Encoding.PEM)) + write(config / "vault-ca.pem", vault_ca[1].public_bytes(Encoding.PEM)) + for name, ca, directory, cert_name, secret_mode in ( + (PROXY, server_ca, proxy, "server-chain", 0o440), + (KV, vault_ca, kv, "server", 0o400), + ): + key, cert = issue_certificate(name, ca, ExtendedKeyUsageOID.SERVER_AUTH) + write(directory / f"{cert_name}.pem", cert.public_bytes(Encoding.PEM)) + write(directory / "server-key.pem", private_bytes(key), secret_mode) + for name, ca in (("valid", client_ca), ("untrusted", foreign_ca), ("expired", client_ca)): + key, cert = issue_certificate( + name, ca, ExtendedKeyUsageOID.CLIENT_AUTH, expired=name == "expired" + ) + write(caller / f"{name}.pem", cert.public_bytes(Encoding.PEM)) + write(caller / f"{name}-key.pem", private_bytes(key), 0o400) + + signer = ed25519.Ed25519PrivateKey.generate() + write(caller / "signer.pem", private_bytes(signer), 0o400) + write( + config / "grant-verifier.pem", + signer.public_key().public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo), + ) + worker_id, active, slow, missing = (str(uuid4()) for _ in range(4)) + profile = ApprovedProfile( + MCPSourceConfig(f"{PRIVATE_MCP}/mcp", bearer_audience=PRIVATE_MCP), (ORG,) + ) + settings = { + "transport": "tls_proxy_unix", + "worker_id": worker_id, + "issuer": ISSUER, + "vault": { + "origin": f"https://{KV}:9443", + "mount": "smoke", + "custom_ca": True, + "timeout_seconds": 10, + }, + "read_limits": { + "timeout_seconds": 6, + "concurrent": 1, + "concurrent_per_org": 1, + "content_bytes": 4096, + }, + "profiles": [asdict(profile)], + } + write(config / "config.json", json.dumps(settings).encode()) + bindings = { + "worker_id": worker_id, + "active": active, + "slow": slow, + "missing": missing, + "profile_digest": profile.digest, + } + write(caller / "bindings.json", json.dumps(bindings).encode()) + vault_token, upstream_token = (secrets.token_urlsafe(32) for _ in range(2)) + write(credentials / "vault-token", vault_token.encode(), 0o440) + write( + kv / "inputs.json", + json.dumps(dict(bindings, vault_token=vault_token, upstream_token=upstream_token)).encode(), + 0o400, + ) + + +def serve() -> None: + root = Path("/kv") + settings = json.loads((root / "inputs.json").read_text()) + target = f"/v1/smoke/data/{settings['worker_id']}/" + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args) -> None: + pass + + def do_GET(self) -> None: + status, body = self.reply() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def reply(self) -> tuple[int, bytes]: + connection = self.path.removeprefix(target) + kind = next( + (kind for kind in ("active", "slow", "missing") if settings[kind] == connection), + None, + ) + values = self.headers.get_all("X-Vault-Token", []) + authorized = ( + self.path.startswith(target) + and kind is not None + and len(values) == 1 + and secrets.compare_digest(values[0], settings["vault_token"]) + and "Authorization" not in self.headers + and "Forwarded" not in self.headers + and "X-Qualification-Canary" not in self.headers + ) + with (SIGNALS / "kv-events").open("ab") as events: + events.write(f"{kind if authorized else 'unexpected'}\n".encode()) + if not authorized: + return 403, b"{}" + if kind == "missing": + return 404, b"{}" + if kind == "slow": + time.sleep(15) + return 404, b"{}" + record = { + "binding": { + "worker_id": settings["worker_id"], + "org": ORG, + "owner": OWNER, + "connection_id": connection, + "generation": 1, + "profile_digest": settings["profile_digest"], + }, + "state": "active", + "auth": "bearer", + "audience": PRIVATE_MCP, + "token": settings["upstream_token"], + "expires_at": int(time.time()) + 3600, + } + return 200, json.dumps( + { + "data": { + "data": record, + "metadata": {"version": 1, "destroyed": False, "deletion_time": ""}, + } + } + ).encode() + + class QuietServer(ThreadingHTTPServer): + def handle_error(self, _request, _client_address) -> None: + if not isinstance( + sys.exception(), (BrokenPipeError, ConnectionResetError, ssl.SSLEOFError) + ): + (SIGNALS / "kv-error").touch() + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(root / "server.pem", root / "server-key.pem") + with QuietServer(("0.0.0.0", 9443), Handler) as server: + server.socket = context.wrap_socket(server.socket, server_side=True) + (SIGNALS / "kv-ready").touch() + server.serve_forever() + + +def client_context(cert: str | None = "valid", ca: str = "server-ca") -> ssl.SSLContext: + context = ssl.create_default_context(cafile=str(CALLER / f"{ca}.pem")) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + if cert is not None: + context.load_cert_chain(CALLER / f"{cert}.pem", CALLER / f"{cert}-key.pem") + return context + + +def request( + context: ssl.SSLContext, + token: str = "", + *, + start: str = "POST /v1/live HTTP/1.1", + extra: bytes = b"", + body: bytes = b"", + hostname: str = PROXY, +) -> tuple[int, list, bytes]: + authorization = f"Authorization: Bearer {token}\r\n" if token else "" + headers = f"{start}\r\nHost: {PROXY}\r\nConnection: close\r\n{authorization}".encode() + with socket.create_connection((PROXY, 8443), timeout=12) as connection: + with context.wrap_socket(connection, server_hostname=hostname) as channel: + channel.sendall(headers + extra + b"\r\n" + body) + with http.client.HTTPResponse(channel) as response: + response.begin() + payload = response.read(65_537) + assert len(payload) <= 65_536, "unexpected response size" + response_headers = response.getheaders() + if token: + assert token.encode() not in payload and all( + token not in val for _, val in response_headers + ) + return response.status, response_headers, payload + + +def assert_reply(response: tuple[int, list, bytes], status: int, code: str) -> None: + actual, headers, payload = response + assert actual == status, f"expected worker {status}, got {actual}" + assert [value for name, value in headers if name.lower() == "cache-control"] == ["no-store"] + assert json.loads(payload) == {"status": code}, f"unexpected response for {status}" + + +def wait_for(check, label: str, seconds: float = 20) -> None: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if check(): + return + time.sleep(0.1) + raise AssertionError(label) + + +def observed() -> list[str]: + assert not (SIGNALS / "kv-error").exists(), "unexpected synthetic KV I/O error" + path = SIGNALS / "kv-events" + return path.read_text().splitlines() if path.exists() else [] + + +def probe(mode: str) -> None: + bindings = json.loads((CALLER / "bindings.json").read_text()) + signer = load_pem_private_key((CALLER / "signer.pem").read_bytes(), password=None) + assert isinstance(signer, ed25519.Ed25519PrivateKey) + context = client_context() + + def grant(connection="missing", operation="live", *, key=signer, issuer=ISSUER, **changes): + binding = { + "worker_id": bindings["worker_id"], + "org": ORG, + "namespace": "smoke", + "source_id": str(uuid4()), + "selection_generation": 1, + "requester": OWNER, + "connection_id": bindings[connection], + "connection_generation": 1, + "profile_digest": bindings["profile_digest"], + "resource_id": "smoke://fixture/document", + } + binding.update(changes) + read = ReadGrant( + request_id=uuid4(), + operation=operation, + binding=ReadBinding.model_validate_json(json.dumps(binding)), + ) + return issue_read_grant(read, issuer=issuer, key=key, lifetime_seconds=30) + + if mode == "stopped": + before = observed() + assert request(context, grant())[0] == 502, "proxy did not fail closed without the worker" + assert observed() == before + return + + wait_for((SIGNALS / "kv-ready").is_file, "synthetic KV is not listening") + + def ready() -> bool: + try: + return request(context)[::2] == (403, b'{"status":"denied"}') + except ssl.SSLCertVerificationError: + raise + except (OSError, http.client.HTTPException): + return False + + wait_for(ready, "mTLS proxy or worker socket is not ready") + before = observed() + assert_reply(request(context, grant()), 409, "reconnect") + assert observed() == [*before, "missing"], "signed grant did not reach the KV fixture" + if mode == "ready": + return + print( + f"Installed worker {version('loom-source-worker')}; MCP SDK {version('mcp')}; " + f"{ssl.OPENSSL_VERSION}" + ) + + before = observed() + for cert in (None, "untrusted", "expired"): + invalid_context = client_context(cert) + try: + status, _, _ = request(invalid_context, grant()) + except ssl.SSLCertVerificationError: + raise + except ssl.SSLError as error: + assert error.reason in { + "TLSV13_ALERT_CERTIFICATE_REQUIRED", + "TLSV1_ALERT_UNKNOWN_CA", + "SSLV3_ALERT_BAD_CERTIFICATE", + "SSLV3_ALERT_CERTIFICATE_EXPIRED", + }, "unexpected client TLS alert" + continue + assert status == 400, "proxy did not reject an invalid client certificate" + for ca, hostname in (("foreign-ca", PROXY), ("server-ca", "wrong-name.invalid")): + try: + request(client_context(ca=ca), grant(), hostname=hostname) + except ssl.SSLCertVerificationError: + pass + else: + raise AssertionError("caller accepted untrusted server identity") + with socket.create_connection((PROXY, 8443), timeout=5) as connection: + connection.sendall(f"POST /v1/live HTTP/1.1\r\nHost: {PROXY}\r\n\r\n".encode()) + try: + assert connection.recv(1) == b"", "proxy returned bytes to a cleartext caller" + except ConnectionResetError: + pass + + first_grant = grant() + for start, extra, body, expected in ( + ("GET /v1/live HTTP/1.1", b"", b"", 404), + ("POST /v1/live? HTTP/1.1", b"", b"", 404), + ("POST /v1/%6cive HTTP/1.1", b"", b"", 404), + ("POST /v1/live HTTP/1.1", b"Content-Length: 1\r\n", b"x", 400), + ("POST /v1/live HTTP/1.1", b"Content-Length: 00\r\n", b"", 400), + ("POST /v1/live HTTP/1.1", b"Transfer-Encoding: chunked\r\n", b"0\r\n\r\n", 400), + ("POST /v1/live HTTP/1.1", b"Authorization: Bearer other\r\n", b"", 400), + ("POST /v1/live HTTP/1.1", b"X-Oversize: " + b"x" * 32_768 + b"\r\n", b"", 400), + ): + status, _, _ = request(context, first_grant, start=start, extra=extra, body=body) + assert status == expected, f"proxy framing refusal: expected {expected}, got {status}" + + expired = jwt.decode(grant(), options={"verify_signature": False}) + expired.update(iat=int(time.time()) - 20, exp=int(time.time()) - 5) + for token in ( + "", + "not-a-grant", + grant(key=ed25519.Ed25519PrivateKey.generate()), + grant(issuer="wrong-issuer"), + grant(worker_id=str(uuid4())), + grant(operation="check_access"), + jwt.encode(expired, signer, algorithm="EdDSA"), + ): + assert_reply(request(context, token), 403, "denied") + assert observed() == before, "a refused TLS, HTTP or grant request reached the KV fixture" + print("PASS: peer trust, cleartext and HTTP framing refused; invalid claims fail closed") + + canary = b"X-Qualification-Canary: synthetic-header\r\nForwarded: for=192.0.2.5\r\n" + for operation, path in (("live", "live"), ("check_access", "check-access")): + before = observed() + assert_reply( + request( + context, grant(operation=operation), start=f"POST /v1/{path} HTTP/1.1", extra=canary + ), + 409, + "reconnect", + ) + assert observed() == [*before, "missing"] + before = observed() + assert_reply(request(context, grant("active", connection_generation=2)), 403, "denied") + assert observed() == [*before, "active"], "stale generation must fail before re-authorization" + before = observed() + assert_reply(request(context, grant("active")), 403, "denied") + after = observed() + assert after[: len(before)] == before and len(after[len(before) :]) >= 2 + assert set(after[len(before) :]) == {"active"} + print( + "PASS: both signed routes reach TLS KV; live worker denies private MCP and stale bindings" + ) + + before = observed() + with ThreadPoolExecutor(max_workers=1) as pool: + started = time.monotonic() + pending = pool.submit(request, context, grant("slow")) + wait_for( + lambda: observed() == [*before, "slow"], "slow KV request was not admitted", seconds=4 + ) + assert_reply(request(context, grant()), 429, "overloaded") + assert observed() == [*before, "slow"], "overloaded request reached KV" + assert_reply(pending.result(timeout=10), 504, "timeout") + elapsed = time.monotonic() - started + assert 5 <= elapsed < 9.5, f"worker did not apply the 6s deadline: {elapsed:.2f}s" + assert_reply(request(context, grant()), 409, "reconnect") + assert observed() == [*before, "slow", "missing"], "timeout did not release the worker slot" + print( + f"PASS: stalled KV read returned at {elapsed:.2f}s; " + "overloaded request shed and slot recovered" + ) + + +def assert_isolated(address: str) -> None: + try: + with socket.create_connection((address, 8443), timeout=2): + raise AssertionError("proxy port reachable from worker egress") + except TimeoutError: + pass + except OSError as error: + assert error.errno in {errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ENETUNREACH} + + +if __name__ == "__main__": + mode = sys.argv[1] + if mode == "prepare": + prepare(Path("/work")) + elif mode == "serve": + serve() + elif mode == "isolated": + assert_isolated(sys.argv[2]) + else: + assert mode in {"probe", "ready", "stopped"} + probe(mode) From 59ebf049da0749380282cd8656c1d466ccea3131 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 09:11:04 +0000 Subject: [PATCH 08/31] Render the standalone worker with Kubernetes restrictions Signed-off-by: zlareb1 (cherry picked from commit 76ba2150c3fc5ced9e62f10629b71215532bb164) --- .../mcp-source-worker-deployment.yml | 38 ++++ source_worker/chart/Chart.yaml | 6 + source_worker/chart/README.md | 131 +++++++++++++ .../chart/examples/qualification-values.yaml | 27 +++ source_worker/chart/files/proxy.conf | 83 ++++++++ source_worker/chart/templates/_helpers.tpl | 29 +++ .../chart/templates/networkpolicy.yaml | 50 +++++ source_worker/chart/templates/service.yaml | 16 ++ .../chart/templates/serviceaccount.yaml | 8 + source_worker/chart/templates/workload.yaml | 181 ++++++++++++++++++ source_worker/chart/values.schema.json | 106 ++++++++++ source_worker/chart/values.yaml | 1 + 12 files changed, 676 insertions(+) create mode 100644 source_worker/chart/Chart.yaml create mode 100644 source_worker/chart/README.md create mode 100644 source_worker/chart/examples/qualification-values.yaml create mode 100644 source_worker/chart/files/proxy.conf create mode 100644 source_worker/chart/templates/_helpers.tpl create mode 100644 source_worker/chart/templates/networkpolicy.yaml create mode 100644 source_worker/chart/templates/service.yaml create mode 100644 source_worker/chart/templates/serviceaccount.yaml create mode 100644 source_worker/chart/templates/workload.yaml create mode 100644 source_worker/chart/values.schema.json create mode 100644 source_worker/chart/values.yaml diff --git a/.github/workflows/mcp-source-worker-deployment.yml b/.github/workflows/mcp-source-worker-deployment.yml index b15f4a250a..2e6d5c3869 100644 --- a/.github/workflows/mcp-source-worker-deployment.yml +++ b/.github/workflows/mcp-source-worker-deployment.yml @@ -26,3 +26,41 @@ jobs: sparse-checkout-cone-mode: false - name: Qualify the exact checkout with synthetic credentials run: python3 -IBu source_worker/qualification/compose_smoke.py + + kubernetes: + name: Standalone worker chart lint and schema + runs-on: ubuntu-24.04 + timeout-minutes: 10 + env: + QUALIFICATION_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ env.QUALIFICATION_SHA }} + persist-credentials: false + sparse-checkout: /source_worker/ + sparse-checkout-cone-mode: false + - name: Install the pinned render and schema tools + run: | + tools=$(mktemp -d) + cd "$tools" + curl -sSfL -o helm.tgz https://get.helm.sh/helm-v3.16.2-linux-amd64.tar.gz + echo '9318379b847e333460d33d291d4c088156299a26cd93d570a7f5d0c36e50b5bb helm.tgz' | sha256sum -c - + tar -xzf helm.tgz + curl -sSfL -o kubeconform.tgz https://github.com/yannh/kubeconform/releases/download/v0.6.7/kubeconform-linux-amd64.tar.gz + echo '95f14e87aa28c09d5941f11bd024c1d02fdc0303ccaa23f61cef67bc92619d73 kubeconform.tgz' | sha256sum -c - + tar -xzf kubeconform.tgz kubeconform + echo "$tools/linux-amd64" >> "$GITHUB_PATH" + echo "$tools" >> "$GITHUB_PATH" + - name: Validate the exact checkout, default and enabled charts + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$QUALIFICATION_SHA" + chart=source_worker/chart + cmp source_worker/proxy.conf "$chart/files/proxy.conf" + helm lint --strict "$chart" + disabled=$(helm template source-worker "$chart") + test -z "$disabled" + values="$chart/examples/qualification-values.yaml" + helm lint --strict "$chart" -f "$values" + helm template source-worker "$chart" -f "$values" | kubeconform -strict -summary -kubernetes-version 1.30.0 diff --git a/source_worker/chart/Chart.yaml b/source_worker/chart/Chart.yaml new file mode 100644 index 0000000000..29374561a0 --- /dev/null +++ b/source_worker/chart/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: loom-source-worker +description: Private mTLS companion for Loom document source reads +type: application +version: 0.1.0 +kubeVersion: ">=1.30.0-0" diff --git a/source_worker/chart/README.md b/source_worker/chart/README.md new file mode 100644 index 0000000000..6bdcd8bda0 --- /dev/null +++ b/source_worker/chart/README.md @@ -0,0 +1,131 @@ +# Kubernetes source worker + +The standalone chart runs a source worker and its mTLS proxy in one Linux Pod, +separate from Loom. `enabled: false` renders no objects. With `enabled: true`, +the release creates one Deployment, a ClusterIP Service on TCP 8443, a +NetworkPolicy, a ServiceAccount with no RBAC grants or token mount, and an +immutable ConfigMap for the proxy. It creates no Ingress or credential objects. + +Use Helm 3.16.2 or later and Kubernetes 1.30 or later. Run the chart in a +dedicated namespace with the Restricted Pod Security Standard enforced and a +CNI that enforces ingress and egress NetworkPolicy. Both container images are +operator-supplied `@sha256:` references. Build the worker from the same reviewed +revision as the chart. The proxy baseline is the digest in +[`../compose.yaml`](../compose.yaml); an alternate build must pass the same +proxy qualification with the unchanged configuration. Configure image pulls at +the node if the worker image is private. + +## Inputs + +Create these objects in the companion namespace before opting in. Values name +the objects; they do not contain config or credentials. Every listed key is +required. A missing object or key prevents volume setup. Invalid configuration +or credential syntax stops the worker; invalid proxy TLS files stop nginx. + +| Value | Object and required keys | Mount | +| --- | --- | --- | +| `inputs.workerConfigMap` | ConfigMap: `config.json`, `grant-verifier.pem`, `vault-ca.pem` | Worker only, read-only at `/etc/loom-source-worker`. | +| `inputs.vaultTokenSecret` | Secret: `vault-token` | Worker only, read-only at `/run/loom-source-worker/credentials/vault-token`, mode `0440`, group `10001`. | +| `inputs.proxyTlsSecret` | Separate Secret: `server-chain.pem`, `server-key.pem`, `client-ca.pem` | Proxy only, read-only at `/etc/nginx/tls`. | + +Use the [worker config and grant contract](../README.md). Set +`transport: tls_proxy_unix` in the worker config. Mount the Vault CA bundle and +set `vault.custom_ca` when the worker must trust that bundle instead of the +system roots. The chart requires the `vault-ca.pem` key even when the worker +uses system roots. Give the Vault token only read authority on the worker's +dedicated KV v2 connection prefix. The worker reads the token from the mounted +file, not an environment variable. Neither Loom nor nginx gets this token or +the upstream credentials. + +Provision Secrets from the operator's encrypted secret backend. Configure +encryption at rest for Kubernetes Secrets, restrict API and node access, and +restrict who can create Pods or attach debug containers in the namespace. This +chart does not configure Vault, Kubernetes encryption, or Secret delivery. Use +versioned ConfigMap and TLS Secret names and update the references to reload +worker settings, verifier keys, or TLS assets. The worker rereads the token +file, so same-name token updates follow kubelet projection latency; revoke at +Vault rather than relying on projection as the revocation boundary. The single +Pod is replaced on changes to its specification; expect a readiness gap. + +The worker and proxy run as UID/GID `10001`, with no Linux capabilities, no +privilege escalation, and read-only root filesystems. A non-root init container +creates a `0700` directory on a bounded memory volume. The worker creates the +`0600` Unix socket there; nginx sees only the read-only directory mount. nginx +has a separate 1 MiB memory volume at `/tmp`. Readiness checks the local socket +and proxy TCP listener; neither probe uses credentials or checks Vault or the +upstream service. A client still needs mTLS and a signed grant for each read. + +## Network boundary + +- `network.callers` selects approved caller Pods by exact namespace and + nonempty `matchLabels`. The caller config uses the + `sw-..svc.` Service DNS name on 8443, a + server CA and a client certificate. Put the Service DNS name in the server + certificate SAN. Keep the client private key in the caller, not this chart. +- `network.dns.nameservers` sets the Pod's literal resolver IPs. The policy + permits UDP and TCP 53 only to those addresses and any configured + `network.dns.pods` peers. Use fully qualified endpoint names. Include resolver + Pod peers where the CNI evaluates DNS traffic after Service translation. +- `network.httpsPods` and `network.httpsCidrs` allow explicit destinations and + one TCP port per peer for Vault and approved MCP endpoints. For Pods use the + target port the CNI sees. Use the smallest external CIDRs and keep them in sync + with endpoint DNS. These rules match IPs and ports, not TLS names or HTTP + paths. The worker's approved profile and certificate checks are separate. + +All other Pod ingress and egress is isolated by the policy, subject to cluster +behavior: policies are additive, node traffic is special, and Service address +translation can affect matches. Prestage a namespace default-deny policy, +control label assignment, allow the companion on the caller's egress policy if +needed, and check both successful and denied traffic on the actual CNI. Use +infrastructure controls for node-local and metadata paths the CNI cannot +isolate. Do not permit broad policies or service-mesh injection in this +namespace. NetworkPolicy applies to the whole Pod, not individual containers; +nginx shares its egress policy but has no Vault token or worker config mount. + +## Hosted qualification + +Run on the exact reviewed revision, using synthetic credentials and endpoints. +The [static fixture](examples/qualification-values.yaml) is for lint and render +only. Do not deploy its placeholder worker image or network addresses. + +```sh +set -eu +chart=source_worker/chart +values="$chart/examples/qualification-values.yaml" +cmp source_worker/proxy.conf "$chart/files/proxy.conf" +helm lint --strict "$chart" --kube-version 1.30.0 +helm lint --strict "$chart" --kube-version 1.30.0 -f "$values" +helm template source-worker "$chart" --kube-version 1.30.0 > disabled.yaml +test ! -s disabled.yaml || ! grep -q '^kind:' disabled.yaml +helm template source-worker "$chart" --namespace companion-test \ + --kube-version 1.30.0 -f "$values" > worker.yaml +kubeconform -strict -summary -kubernetes-version 1.30.0 worker.yaml +``` + +Decode the rendered ConfigMap's `binaryData.nginx.conf` and compare it with +`source_worker/proxy.conf`. The chart holds a byte-for-byte copy because Helm +cannot load a file outside the packaged chart. Run the same render from an +isolated chart copy. Assert that opt-in fails without images or input names, +without approved callers, DNS or egress destinations, with a tag-only image, +with the same Secret for Vault and TLS, and without the packaged proxy file. + +On a disposable, policy-enforcing hosted cluster, repeat strict validation for +the target Kubernetes version. Configure Restricted admission, default deny, +real hosted image digests and test-specific allowlists. Use an ephemeral KV v2 +backend, independent issuer keys, synthetic PKI and controlled HTTPS MCP +endpoints. Run server-side dry-run and wait for Pod admission and readiness. +Record the exact chart revision, tool versions, CNI, image digests and checks. + +| Check | Expected result | +| --- | --- | +| Missing input object, missing key, bad token permissions or invalid proxy TLS | No ready endpoints. No fallback listener or credentials. | +| Runtime mounts | Worker socket directory `10001:10001` mode `0700`, socket `0600`, Vault file mode `0440`; no token in proxy or Loom and no service-account token in either container. | +| Approved caller, trusted client certificate and valid signed grant | Bodyless HTTP/1.1 `POST /v1/live` and `POST /v1/check-access` work; only the live response has content. Responses carry `Cache-Control: no-store`. | +| No or untrusted client certificate; wrong server name or CA; plaintext; forged or missing grant | No protected result; no caller TLS bypass or plaintext route. | +| Extra headers, nonempty body, transfer encoding or unlisted method/path | Proxy forwards only the grant and fixed upstream Host; rejects disallowed requests without an upstream read. | +| Same labels in a different namespace, wrong caller labels, unapproved TCP destination/port, and unauthorized DNS | Policy blocks them. The approved DNS, Vault and MCP destinations still work. | +| Log, volume and restart inspection | Synthetic body and token markers absent from proxy and worker logs, termination messages and proxy temp files. No stale socket route after worker restart; readiness and mTLS recover after restart and reviewed rotation. | + +Remove the hosted synthetic resources after recording results. Rendering and +schema checks do not qualify mTLS, file ownership, DNS translation or CNI +enforcement. diff --git a/source_worker/chart/examples/qualification-values.yaml b/source_worker/chart/examples/qualification-values.yaml new file mode 100644 index 0000000000..bc21eb5d19 --- /dev/null +++ b/source_worker/chart/examples/qualification-values.yaml @@ -0,0 +1,27 @@ +enabled: true +images: + worker: registry.example/loom/source-worker@sha256:0000000000000000000000000000000000000000000000000000000000000000 + proxy: nginx:1.30.8-alpine@sha256:6437a63b5c529f0e06162b3f593c0154cff6fa2ea0f94fd7c27928cb399e022d +inputs: + workerConfigMap: source-worker-config-v1 + vaultTokenSecret: source-worker-vault-token + proxyTlsSecret: source-worker-proxy-tls-v1 +network: + callers: + - namespace: issuer-test + matchLabels: + app.kubernetes.io/name: approved-issuer + dns: + nameservers: [192.0.2.53] + pods: + - namespace: kube-system + matchLabels: + k8s-app: kube-dns + httpsPods: + - namespace: credentials-test + matchLabels: + app.kubernetes.io/name: test-vault + port: 8200 + httpsCidrs: + - cidr: 192.0.2.44/32 + port: 443 diff --git a/source_worker/chart/files/proxy.conf b/source_worker/chart/files/proxy.conf new file mode 100644 index 0000000000..bd595f8dcf --- /dev/null +++ b/source_worker/chart/files/proxy.conf @@ -0,0 +1,83 @@ +worker_processes 1; +pid /tmp/nginx.pid; +error_log /dev/null crit; + +events { + worker_connections 768; +} + +http { + access_log off; + server_tokens off; + + client_body_temp_path /tmp/client_body; + proxy_temp_path /tmp/proxy; + fastcgi_temp_path /tmp/fastcgi; + uwsgi_temp_path /tmp/uwsgi; + scgi_temp_path /tmp/scgi; + + client_header_buffer_size 1k; + large_client_header_buffers 1 31k; + max_headers 64; + client_header_timeout 5s; + client_body_timeout 5s; + client_max_body_size 1; + keepalive_timeout 0; + send_timeout 5s; + + server { + listen 8443 ssl; + server_name source-worker-proxy; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_certificate /etc/nginx/tls/server-chain.pem; + ssl_certificate_key /etc/nginx/tls/server-key.pem; + ssl_client_certificate /etc/nginx/tls/client-ca.pem; + ssl_verify_client on; + ssl_verify_depth 2; + ssl_early_data off; + ssl_session_cache off; + ssl_session_tickets off; + + error_page 497 = @drop_cleartext; + add_header Cache-Control no-store always; + + location @drop_cleartext { + return 444; + } + + location / { + if ($request !~ "^POST /v1/(live|check-access) HTTP/1[.]1$") { + return 404; + } + if ($content_length !~ "^0?$") { + return 400; + } + if ($http_transfer_encoding != "") { + return 400; + } + + proxy_pass http://unix:/run/loom-source-worker/socket/worker.sock; + proxy_http_version 1.1; + proxy_pass_request_headers off; + proxy_pass_request_body off; + proxy_set_header Host source-worker; + proxy_set_header Authorization $http_authorization; + proxy_set_header Content-Length ""; + proxy_set_header Transfer-Encoding ""; + + proxy_buffering off; + proxy_request_buffering off; + proxy_max_temp_file_size 0; + proxy_cache off; + proxy_store off; + proxy_ignore_headers X-Accel-Buffering X-Accel-Redirect; + proxy_hide_header Cache-Control; + proxy_redirect off; + proxy_next_upstream off; + proxy_connect_timeout 1s; + proxy_send_timeout 5s; + proxy_read_timeout 35s; + } + } +} diff --git a/source_worker/chart/templates/_helpers.tpl b/source_worker/chart/templates/_helpers.tpl new file mode 100644 index 0000000000..0add3349a5 --- /dev/null +++ b/source_worker/chart/templates/_helpers.tpl @@ -0,0 +1,29 @@ +{{- define "loom-source-worker.name" -}} +{{- if not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" .Release.Name) -}} +{{- fail "source worker release name must be a DNS label" -}} +{{- end -}} +{{- printf "sw-%s" .Release.Name -}} +{{- end -}} + +{{- define "loom-source-worker.selector" -}} +app.kubernetes.io/name: loom-source-worker +app.kubernetes.io/instance: {{ .Release.Name | quote }} +{{- end -}} + +{{- define "loom-source-worker.containerSecurity" -}} +allowPrivilegeEscalation: false +readOnlyRootFilesystem: true +capabilities: + drop: [ALL] +{{- end -}} + +{{- define "loom-source-worker.podPeer" -}} +namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ .namespace | quote }} +podSelector: + matchLabels: + {{- range $label, $value := .matchLabels }} + {{ $label | quote }}: {{ $value | quote }} + {{- end }} +{{- end -}} diff --git a/source_worker/chart/templates/networkpolicy.yaml b/source_worker/chart/templates/networkpolicy.yaml new file mode 100644 index 0000000000..a79be4dc9f --- /dev/null +++ b/source_worker/chart/templates/networkpolicy.yaml @@ -0,0 +1,50 @@ +{{- if .Values.enabled }} +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "loom-source-worker.name" . }} + namespace: {{ .Release.Namespace | quote }} +spec: + podSelector: + matchLabels: + {{- include "loom-source-worker.selector" . | nindent 6 }} + policyTypes: [Ingress, Egress] + ingress: + - from: + {{- range .Values.network.callers }} + - {{ include "loom-source-worker.podPeer" . | nindent 10 | trim }} + {{- end }} + ports: + - port: 8443 + protocol: TCP + egress: + - to: + {{- range .Values.network.dns.nameservers }} + {{- $prefix := ternary 128 32 (contains ":" .) }} + - ipBlock: + cidr: {{ printf "%s/%d" . $prefix | quote }} + {{- end }} + {{- range .Values.network.dns.pods }} + - {{ include "loom-source-worker.podPeer" . | nindent 10 | trim }} + {{- end }} + ports: + - port: 53 + protocol: UDP + - port: 53 + protocol: TCP + {{- range .Values.network.httpsPods }} + - to: + - {{ include "loom-source-worker.podPeer" . | nindent 10 | trim }} + ports: + - port: {{ .port }} + protocol: TCP + {{- end }} + {{- range .Values.network.httpsCidrs }} + - to: + - ipBlock: + cidr: {{ .cidr | quote }} + ports: + - port: {{ .port }} + protocol: TCP + {{- end }} +{{- end }} diff --git a/source_worker/chart/templates/service.yaml b/source_worker/chart/templates/service.yaml new file mode 100644 index 0000000000..c011165b4f --- /dev/null +++ b/source_worker/chart/templates/service.yaml @@ -0,0 +1,16 @@ +{{- if .Values.enabled }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "loom-source-worker.name" . }} + namespace: {{ .Release.Namespace | quote }} +spec: + type: ClusterIP + selector: + {{- include "loom-source-worker.selector" . | nindent 4 }} + ports: + - name: https + port: 8443 + targetPort: https + protocol: TCP +{{- end }} diff --git a/source_worker/chart/templates/serviceaccount.yaml b/source_worker/chart/templates/serviceaccount.yaml new file mode 100644 index 0000000000..c8c029bb41 --- /dev/null +++ b/source_worker/chart/templates/serviceaccount.yaml @@ -0,0 +1,8 @@ +{{- if .Values.enabled }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "loom-source-worker.name" . }} + namespace: {{ .Release.Namespace | quote }} +automountServiceAccountToken: false +{{- end }} diff --git a/source_worker/chart/templates/workload.yaml b/source_worker/chart/templates/workload.yaml new file mode 100644 index 0000000000..3855e7568f --- /dev/null +++ b/source_worker/chart/templates/workload.yaml @@ -0,0 +1,181 @@ +{{- if .Values.enabled }} +{{- $name := include "loom-source-worker.name" . }} +{{- $proxy := .Files.Get "files/proxy.conf" }} +{{- if not $proxy }} +{{- fail "source worker chart is missing files/proxy.conf" }} +{{- end }} +{{- if eq .Values.inputs.vaultTokenSecret .Values.inputs.proxyTlsSecret }} +{{- fail "vaultTokenSecret and proxyTlsSecret must name separate Secrets" }} +{{- end }} +{{- $proxyName := printf "%s-proxy-%s" $name ($proxy | sha256sum | trunc 16) }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ $proxyName }} + namespace: {{ .Release.Namespace | quote }} +immutable: true +binaryData: + nginx.conf: {{ $proxy | b64enc | quote }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ $name }} + namespace: {{ .Release.Namespace | quote }} +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + {{- include "loom-source-worker.selector" . | nindent 6 }} + template: + metadata: + labels: + {{- include "loom-source-worker.selector" . | nindent 8 }} + spec: + os: + name: linux + nodeSelector: + kubernetes.io/os: linux + serviceAccountName: {{ $name }} + automountServiceAccountToken: false + enableServiceLinks: false + terminationGracePeriodSeconds: 35 + dnsPolicy: None + dnsConfig: + nameservers: + {{- range .Values.network.dns.nameservers }} + - {{ . | quote }} + {{- end }} + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: + type: RuntimeDefault + initContainers: + - name: private-directories + image: {{ .Values.images.worker | quote }} + command: [python, -IB, -c] + args: + - | + import os + import stat + from pathlib import Path + + for directory in (Path('/socket-volume/socket'), Path('/proxy-volume/tmp')): + directory.mkdir(mode=0o700, exist_ok=True) + info = directory.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid(): + raise SystemExit('invalid private volume directory') + directory.chmod(0o700) + securityContext: + {{- include "loom-source-worker.containerSecurity" . | nindent 12 }} + resources: + requests: {cpu: 25m, memory: 16Mi, ephemeral-storage: 8Mi} + limits: {cpu: 100m, memory: 32Mi, ephemeral-storage: 16Mi} + volumeMounts: + - {name: socket, mountPath: /socket-volume} + - {name: proxy-tmp, mountPath: /proxy-volume} + containers: + - name: source-worker + image: {{ .Values.images.worker | quote }} + command: [python, -IBu, -m, loom_source_worker.main] + securityContext: + {{- include "loom-source-worker.containerSecurity" . | nindent 12 }} + readinessProbe: + exec: + command: + - python + - -IB + - -c + - | + import socket + with socket.socket(socket.AF_UNIX) as probe: + probe.settimeout(1) + probe.connect('/run/loom-source-worker/socket/worker.sock') + timeoutSeconds: 2 + periodSeconds: 5 + resources: + requests: {cpu: 100m, memory: 256Mi, ephemeral-storage: 8Mi} + limits: {cpu: "1", memory: 512Mi, ephemeral-storage: 16Mi} + volumeMounts: + - name: worker-config + mountPath: /etc/loom-source-worker + readOnly: true + - name: vault-token + mountPath: /run/loom-source-worker/credentials + readOnly: true + - name: socket + mountPath: /run/loom-source-worker/socket + subPath: socket + - name: source-worker-proxy + image: {{ .Values.images.proxy | quote }} + command: [nginx, -e, /dev/null, -g, "daemon off;", -c, /etc/nginx/nginx.conf] + ports: + - {name: https, containerPort: 8443, protocol: TCP} + securityContext: + {{- include "loom-source-worker.containerSecurity" . | nindent 12 }} + readinessProbe: + tcpSocket: + port: https + timeoutSeconds: 2 + periodSeconds: 5 + resources: + requests: {cpu: 50m, memory: 64Mi, ephemeral-storage: 8Mi} + limits: {cpu: 500m, memory: 128Mi, ephemeral-storage: 16Mi} + volumeMounts: + - name: proxy-config + mountPath: /etc/nginx/nginx.conf + subPath: nginx.conf + readOnly: true + - name: proxy-tls + mountPath: /etc/nginx/tls + readOnly: true + - name: socket + mountPath: /run/loom-source-worker/socket + subPath: socket + readOnly: true + - name: proxy-tmp + mountPath: /tmp + subPath: tmp + volumes: + - name: worker-config + configMap: + name: {{ .Values.inputs.workerConfigMap | quote }} + optional: false + defaultMode: 288 + items: + - {key: config.json, path: config.json} + - {key: grant-verifier.pem, path: grant-verifier.pem} + - {key: vault-ca.pem, path: vault-ca.pem} + - name: vault-token + secret: + secretName: {{ .Values.inputs.vaultTokenSecret | quote }} + optional: false + defaultMode: 288 + items: + - {key: vault-token, path: vault-token} + - name: proxy-config + configMap: + name: {{ $proxyName }} + optional: false + defaultMode: 288 + items: + - {key: nginx.conf, path: nginx.conf} + - name: proxy-tls + secret: + secretName: {{ .Values.inputs.proxyTlsSecret | quote }} + optional: false + defaultMode: 288 + items: + - {key: server-chain.pem, path: server-chain.pem} + - {key: server-key.pem, path: server-key.pem} + - {key: client-ca.pem, path: client-ca.pem} + - name: socket + emptyDir: {medium: Memory, sizeLimit: 64Ki} + - name: proxy-tmp + emptyDir: {medium: Memory, sizeLimit: 1Mi} +{{- end }} diff --git a/source_worker/chart/values.schema.json b/source_worker/chart/values.schema.json new file mode 100644 index 0000000000..25951abfe3 --- /dev/null +++ b/source_worker/chart/values.schema.json @@ -0,0 +1,106 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "additionalProperties": false, + "required": ["enabled"], + "properties": { + "enabled": {"type": "boolean"}, + "images": { + "type": "object", + "additionalProperties": false, + "required": ["worker", "proxy"], + "properties": { + "worker": {"$ref": "#/definitions/digestImage"}, + "proxy": {"$ref": "#/definitions/digestImage"} + } + }, + "inputs": { + "type": "object", + "additionalProperties": false, + "required": ["workerConfigMap", "vaultTokenSecret", "proxyTlsSecret"], + "properties": { + "workerConfigMap": {"$ref": "#/definitions/objectName"}, + "vaultTokenSecret": {"$ref": "#/definitions/objectName"}, + "proxyTlsSecret": {"$ref": "#/definitions/objectName"} + } + }, + "network": { + "type": "object", + "additionalProperties": false, + "required": ["callers", "dns"], + "properties": { + "callers": { + "type": "array", "minItems": 1, "maxItems": 32, + "items": {"$ref": "#/definitions/podPeer"} + }, + "dns": { + "type": "object", + "additionalProperties": false, + "required": ["nameservers"], + "properties": { + "nameservers": { + "type": "array", "minItems": 1, "maxItems": 3, "uniqueItems": true, + "items": {"anyOf": [{"format": "ipv4", "type": "string"}, {"format": "ipv6", "type": "string"}]} + }, + "pods": {"type": "array", "maxItems": 16, "items": {"$ref": "#/definitions/podPeer"}} + } + }, + "httpsPods": { + "type": "array", "maxItems": 64, + "items": {"$ref": "#/definitions/httpsPodPeer"} + }, + "httpsCidrs": { + "type": "array", "maxItems": 128, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["cidr", "port"], + "properties": { + "cidr": {"type": "string", "pattern": "^[0-9A-Fa-f:.]+/[1-9][0-9]{0,2}$", "maxLength": 43}, + "port": {"$ref": "#/definitions/port"} + } + } + } + }, + "anyOf": [ + {"required": ["httpsPods"], "properties": {"httpsPods": {"minItems": 1}}}, + {"required": ["httpsCidrs"], "properties": {"httpsCidrs": {"minItems": 1}}} + ] + } + }, + "if": {"properties": {"enabled": {"const": true}}}, + "then": {"required": ["images", "inputs", "network"]}, + "definitions": { + "digestImage": { + "type": "string", + "pattern": "^([a-z0-9][a-z0-9._-]*(:[0-9]+)?/)*[a-z0-9][a-z0-9._-]*(:[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?@sha256:[a-f0-9]{64}$" + }, + "objectName": {"type": "string", "maxLength": 253, "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$"}, + "namespace": {"type": "string", "maxLength": 63, "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"}, + "matchLabels": { + "type": "object", "minProperties": 1, "maxProperties": 16, + "propertyNames": {"pattern": "^([a-z0-9][-.a-z0-9]*[a-z0-9]/|[a-z0-9]/)?[A-Za-z0-9]([-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?$"}, + "additionalProperties": {"type": "string", "pattern": "^[A-Za-z0-9]([-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?$"} + }, + "port": {"type": "integer", "minimum": 1, "maximum": 65535}, + "podPeer": { + "type": "object", + "additionalProperties": false, + "required": ["namespace", "matchLabels"], + "properties": { + "namespace": {"$ref": "#/definitions/namespace"}, + "matchLabels": {"$ref": "#/definitions/matchLabels"} + } + }, + "httpsPodPeer": { + "type": "object", + "additionalProperties": false, + "required": ["namespace", "matchLabels", "port"], + "properties": { + "namespace": {"$ref": "#/definitions/namespace"}, + "matchLabels": {"$ref": "#/definitions/matchLabels"}, + "port": {"$ref": "#/definitions/port"} + } + } + } +} diff --git a/source_worker/chart/values.yaml b/source_worker/chart/values.yaml new file mode 100644 index 0000000000..bc114417c7 --- /dev/null +++ b/source_worker/chart/values.yaml @@ -0,0 +1 @@ +enabled: false From 576c095c6866e6916998b562b46d19a203c18323 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 09:23:07 +0000 Subject: [PATCH 09/31] Validate Compose fixture profiles before container startup Signed-off-by: zlareb1 (cherry picked from commit 95841c2437a5952ab507f1c54666d5c53c3b01d9) --- source_worker/chart/values.schema.json | 159 ++++++++++++++++++++----- source_worker/qualification/fixture.py | 26 +++- 2 files changed, 148 insertions(+), 37 deletions(-) diff --git a/source_worker/chart/values.schema.json b/source_worker/chart/values.schema.json index 25951abfe3..d725ec677f 100644 --- a/source_worker/chart/values.schema.json +++ b/source_worker/chart/values.schema.json @@ -4,14 +4,20 @@ "additionalProperties": false, "required": ["enabled"], "properties": { - "enabled": {"type": "boolean"}, + "enabled": { + "type": "boolean" + }, "images": { "type": "object", "additionalProperties": false, "required": ["worker", "proxy"], "properties": { - "worker": {"$ref": "#/definitions/digestImage"}, - "proxy": {"$ref": "#/definitions/digestImage"} + "worker": { + "$ref": "#/definitions/digestImage" + }, + "proxy": { + "$ref": "#/definitions/digestImage" + } } }, "inputs": { @@ -19,9 +25,15 @@ "additionalProperties": false, "required": ["workerConfigMap", "vaultTokenSecret", "proxyTlsSecret"], "properties": { - "workerConfigMap": {"$ref": "#/definitions/objectName"}, - "vaultTokenSecret": {"$ref": "#/definitions/objectName"}, - "proxyTlsSecret": {"$ref": "#/definitions/objectName"} + "workerConfigMap": { + "$ref": "#/definitions/objectName" + }, + "vaultTokenSecret": { + "$ref": "#/definitions/objectName" + }, + "proxyTlsSecret": { + "$ref": "#/definitions/objectName" + } } }, "network": { @@ -30,8 +42,12 @@ "required": ["callers", "dns"], "properties": { "callers": { - "type": "array", "minItems": 1, "maxItems": 32, - "items": {"$ref": "#/definitions/podPeer"} + "type": "array", + "minItems": 1, + "maxItems": 32, + "items": { + "$ref": "#/definitions/podPeer" + } }, "dns": { "type": "object", @@ -39,57 +55,132 @@ "required": ["nameservers"], "properties": { "nameservers": { - "type": "array", "minItems": 1, "maxItems": 3, "uniqueItems": true, - "items": {"anyOf": [{"format": "ipv4", "type": "string"}, {"format": "ipv6", "type": "string"}]} + "type": "array", + "minItems": 1, + "maxItems": 3, + "uniqueItems": true, + "items": { + "anyOf": [ + { + "format": "ipv4", + "type": "string" + }, + { + "format": "ipv6", + "type": "string" + } + ] + } }, - "pods": {"type": "array", "maxItems": 16, "items": {"$ref": "#/definitions/podPeer"}} + "pods": { + "type": "array", + "maxItems": 16, + "items": { + "$ref": "#/definitions/podPeer" + } + } } }, "httpsPods": { - "type": "array", "maxItems": 64, - "items": {"$ref": "#/definitions/httpsPodPeer"} + "type": "array", + "maxItems": 64, + "items": { + "$ref": "#/definitions/httpsPodPeer" + } }, "httpsCidrs": { - "type": "array", "maxItems": 128, + "type": "array", + "maxItems": 128, "items": { "type": "object", "additionalProperties": false, "required": ["cidr", "port"], "properties": { - "cidr": {"type": "string", "pattern": "^[0-9A-Fa-f:.]+/[1-9][0-9]{0,2}$", "maxLength": 43}, - "port": {"$ref": "#/definitions/port"} + "cidr": { + "type": "string", + "pattern": "^[0-9A-Fa-f:.]+/[1-9][0-9]{0,2}$", + "maxLength": 43 + }, + "port": { + "$ref": "#/definitions/port" + } } } } }, "anyOf": [ - {"required": ["httpsPods"], "properties": {"httpsPods": {"minItems": 1}}}, - {"required": ["httpsCidrs"], "properties": {"httpsCidrs": {"minItems": 1}}} + { + "required": ["httpsPods"], + "properties": { + "httpsPods": { + "minItems": 1 + } + } + }, + { + "required": ["httpsCidrs"], + "properties": { + "httpsCidrs": { + "minItems": 1 + } + } + } ] } }, - "if": {"properties": {"enabled": {"const": true}}}, - "then": {"required": ["images", "inputs", "network"]}, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "required": ["images", "inputs", "network"] + }, "definitions": { "digestImage": { "type": "string", "pattern": "^([a-z0-9][a-z0-9._-]*(:[0-9]+)?/)*[a-z0-9][a-z0-9._-]*(:[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?@sha256:[a-f0-9]{64}$" }, - "objectName": {"type": "string", "maxLength": 253, "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$"}, - "namespace": {"type": "string", "maxLength": 63, "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$"}, + "objectName": { + "type": "string", + "maxLength": 253, + "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" + }, + "namespace": { + "type": "string", + "maxLength": 63, + "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" + }, "matchLabels": { - "type": "object", "minProperties": 1, "maxProperties": 16, - "propertyNames": {"pattern": "^([a-z0-9][-.a-z0-9]*[a-z0-9]/|[a-z0-9]/)?[A-Za-z0-9]([-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?$"}, - "additionalProperties": {"type": "string", "pattern": "^[A-Za-z0-9]([-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?$"} + "type": "object", + "minProperties": 1, + "maxProperties": 16, + "propertyNames": { + "pattern": "^([a-z0-9][-.a-z0-9]*[a-z0-9]/|[a-z0-9]/)?[A-Za-z0-9]([-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?$" + }, + "additionalProperties": { + "type": "string", + "pattern": "^[A-Za-z0-9]([-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?$" + } + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 }, - "port": {"type": "integer", "minimum": 1, "maximum": 65535}, "podPeer": { "type": "object", "additionalProperties": false, "required": ["namespace", "matchLabels"], "properties": { - "namespace": {"$ref": "#/definitions/namespace"}, - "matchLabels": {"$ref": "#/definitions/matchLabels"} + "namespace": { + "$ref": "#/definitions/namespace" + }, + "matchLabels": { + "$ref": "#/definitions/matchLabels" + } } }, "httpsPodPeer": { @@ -97,9 +188,15 @@ "additionalProperties": false, "required": ["namespace", "matchLabels", "port"], "properties": { - "namespace": {"$ref": "#/definitions/namespace"}, - "matchLabels": {"$ref": "#/definitions/matchLabels"}, - "port": {"$ref": "#/definitions/port"} + "namespace": { + "$ref": "#/definitions/namespace" + }, + "matchLabels": { + "$ref": "#/definitions/matchLabels" + }, + "port": { + "$ref": "#/definitions/port" + } } } } diff --git a/source_worker/qualification/fixture.py b/source_worker/qualification/fixture.py index 2d4b076933..8f89f33603 100644 --- a/source_worker/qualification/fixture.py +++ b/source_worker/qualification/fixture.py @@ -31,6 +31,7 @@ ) from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID from loom_source_worker.direct_backend import ApprovedProfile +from loom_source_worker.main import _parse_settings from loom_source_worker.mcp_client import MCPSourceConfig from loom_source_worker.protocol import ReadBinding, ReadGrant, issue_read_grant @@ -141,6 +142,8 @@ def prepare(root: Path) -> None: profile = ApprovedProfile( MCPSourceConfig(f"{PRIVATE_MCP}/mcp", bearer_audience=PRIVATE_MCP), (ORG,) ) + profile_config = asdict(profile) + del profile_config["config"]["approved_resource_ids"] settings = { "transport": "tls_proxy_unix", "worker_id": worker_id, @@ -157,15 +160,17 @@ def prepare(root: Path) -> None: "concurrent_per_org": 1, "content_bytes": 4096, }, - "profiles": [asdict(profile)], + "profiles": [profile_config], } - write(config / "config.json", json.dumps(settings).encode()) + raw_settings = json.dumps(settings).encode() + [parsed_profile] = _parse_settings(raw_settings).profiles + write(config / "config.json", raw_settings) bindings = { "worker_id": worker_id, "active": active, "slow": slow, "missing": missing, - "profile_digest": profile.digest, + "profile_digest": parsed_profile.digest, } write(caller / "bindings.json", json.dumps(bindings).encode()) vault_token, upstream_token = (secrets.token_urlsafe(32) for _ in range(2)) @@ -350,15 +355,24 @@ def grant(connection="missing", operation="live", *, key=signer, issuer=ISSUER, wait_for((SIGNALS / "kv-ready").is_file, "synthetic KV is not listening") + last_probe = "no response" + def ready() -> bool: + nonlocal last_probe try: - return request(context)[::2] == (403, b'{"status":"denied"}') + status, _, payload = request(context) + last_probe = f"HTTP {status}" + return status == 403 and payload == b'{"status":"denied"}' except ssl.SSLCertVerificationError: raise - except (OSError, http.client.HTTPException): + except (OSError, http.client.HTTPException) as error: + last_probe = type(error).__name__ return False - wait_for(ready, "mTLS proxy or worker socket is not ready") + try: + wait_for(ready, "mTLS proxy or worker socket is not ready") + except AssertionError as error: + raise AssertionError(f"{error}; last probe: {last_probe}") from None before = observed() assert_reply(request(context, grant()), 409, "reconnect") assert observed() == [*before, "missing"], "signed grant did not reach the KV fixture" From e31e2791b0c61884bb3c4f5effccc405588c7de7 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 09:42:42 +0000 Subject: [PATCH 10/31] Recheck initialization failure and normalize approval deadlines Signed-off-by: zlareb1 (cherry picked from commit 577fbfad075db8be87376fff989092556f3cf485) --- .../loom_source_worker/mcp_client.py | 23 +++++++-- source_worker/tests/test_mcp_client.py | 51 +++++++++++++++++++ 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index d90ca330f5..7c840219d7 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -122,8 +122,8 @@ def _check_response(method: str, response: httpx.Response) -> None: @dataclass(frozen=True) class MCPLimits: - timeout_seconds: float = 30 - request_seconds: float = 10 + timeout_seconds: float = 30.0 + request_seconds: float = 10.0 max_pages: int = 8 max_results: int = 100 max_content_bytes: int = 1_000_000 @@ -138,6 +138,9 @@ def __post_init__(self) -> None: or not 0 < value <= ceiling ): raise MCPSourceError("config") + # Profile digests use one representation for equal effective deadlines. + object.__setattr__(self, "timeout_seconds", float(self.timeout_seconds)) + object.__setattr__(self, "request_seconds", float(self.request_seconds)) for value, ceiling in ( (self.max_pages, 32), (self.max_results, 1000), @@ -932,9 +935,23 @@ async def __aenter__(self) -> MCPSourceClient: except Exception as error: # noqa: BLE001 — only fixed initialization failures reach callers try: await self._close() + code = await self._initialization_failure(error) finally: self._leave_private() - raise MCPSourceError(self._owner_failure or _error_code(error)) from None + raise MCPSourceError(code) from None + + async def _initialization_failure(self, error: Exception) -> ErrorCode: + code = self._owner_failure or _error_code(error) + if self._transport is None or code in {"denied", "closed", "timeout"}: + return code + if asyncio.get_running_loop().time() >= self._deadline: + return code + try: + async with asyncio.timeout_at(self._deadline): + await self._validate_access() + except Exception as current: # noqa: BLE001 — expose only the current fixed refusal + return _error_code(current) + return code async def _serve_session(self) -> None: # SDK AnyIO scopes are entered and exited by this one lifecycle owner. diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index d52629bf5b..2c2e18ac53 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -14,6 +14,8 @@ import pytest from loom_source_worker import mcp_client from loom_source_worker._mcp_transport import resolve_public_address +from loom_source_worker.direct_backend import ApprovedProfile +from loom_source_worker.main import _parse_settings from loom_source_worker.mcp_client import ( MCPBearer, MCPDataPolicy, @@ -34,6 +36,33 @@ async def _authorized() -> None: return None +def test_equivalent_effective_deadlines_share_one_approved_profile_digest() -> None: + raw: dict[str, Any] = { + "transport": "tls_proxy_unix", + "worker_id": "83d061b4-2542-4db7-adc0-4b81b3280c08", + "issuer": "synthetic-grants", + "vault": {"origin": "https://vault.example", "mount": "connections"}, + "read_limits": { + "concurrent": 8, + "concurrent_per_org": 2, + "timeout_seconds": 5, + "content_bytes": 4096, + }, + "profiles": [{"organizations": ["tenant"], "config": {"endpoint": _ENDPOINT}}], + } + omitted = _parse_settings(json.dumps(raw).encode()).profiles[0] + raw["profiles"][0]["config"]["limits"] = { + "timeout_seconds": 30.0, + "request_seconds": 10.0, + } + explicit = _parse_settings(json.dumps(raw).encode()).profiles[0] + direct = ApprovedProfile( + MCPSourceConfig(_ENDPOINT, limits=MCPLimits(timeout_seconds=30, request_seconds=10)), + ("tenant",), + ) + assert omitted.digest == explicit.digest == direct.digest + + @pytest.fixture(autouse=True) def _no_dns(monkeypatch: pytest.MonkeyPatch) -> None: def refuse_resolver() -> None: @@ -69,6 +98,7 @@ def __init__(self) -> None: self.resource_text = "synthetic text" self.resource_uri = _DOCUMENT self.resource_parts = 1 + self.initialize_error: int | None = None self.resource_error: int | None = None self.resource_extensions: dict[str, Any] = {} self.notifications: _IdleBody | None = None @@ -94,6 +124,8 @@ async def respond(self, request: httpx.Request) -> httpx.Response: method = body["method"] self.calls.append((request, method)) if method == "initialize": + if self.initialize_error is not None: + return httpx.Response(self.initialize_error) if self.redirect: return httpx.Response(307, headers={"location": "https://other.example/mcp"}) capabilities = {"resources": {}} if self.tool is None else {"tools": {}} @@ -530,6 +562,25 @@ async def validate_access() -> None: assert source.closed +@pytest.mark.asyncio +async def test_revocation_wins_over_initialization_reconnect(pin: list[str]) -> None: + source = _Source() + source.initialize_error = 401 + + async def validate_access() -> None: + if any(method == "initialize" for _, method in source.calls): + raise MCPSourceError("denied") + + config = MCPSourceConfig(_ENDPOINT, approved_resource_ids=(_DOCUMENT,)) + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + async with MCPSourceClient( + config, None, validate_access=validate_access, _transport=source + ): + pytest.fail("read became available after revocation") + assert [method for _, method in source.calls] == ["initialize"] + assert source.closed + + @pytest.mark.asyncio async def test_revocation_wins_over_upstream_reconnect(pin: list[str]) -> None: source = _Source() From bd663a402ea2502d5ea4a19b0f85a25b536cbed8 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 09:44:56 +0000 Subject: [PATCH 11/31] Declare the chart worker IPv4 boundary Signed-off-by: zlareb1 --- .../workflows/mcp-source-worker-deployment.yml | 9 ++++++++- source_worker/chart/README.md | 5 ++++- source_worker/chart/templates/networkpolicy.yaml | 3 +-- source_worker/chart/templates/service.yaml | 2 ++ source_worker/chart/values.schema.json | 16 ++++------------ 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/.github/workflows/mcp-source-worker-deployment.yml b/.github/workflows/mcp-source-worker-deployment.yml index 2e6d5c3869..4f2fc8d33b 100644 --- a/.github/workflows/mcp-source-worker-deployment.yml +++ b/.github/workflows/mcp-source-worker-deployment.yml @@ -63,4 +63,11 @@ jobs: test -z "$disabled" values="$chart/examples/qualification-values.yaml" helm lint --strict "$chart" -f "$values" - helm template source-worker "$chart" -f "$values" | kubeconform -strict -summary -kubernetes-version 1.30.0 + rendered=$(helm template source-worker "$chart" -f "$values") + printf '%s\n' "$rendered" | kubeconform -strict -summary -kubernetes-version 1.30.0 + grep -Fq 'ipFamilies: [IPv4]' <<< "$rendered" + if helm template source-worker "$chart" -f "$values" \ + --set-string 'network.dns.nameservers[0]=2001:db8::53'; then + echo 'IPv6-only nameserver was accepted' >&2 + exit 1 + fi diff --git a/source_worker/chart/README.md b/source_worker/chart/README.md index 6bdcd8bda0..26bfccc878 100644 --- a/source_worker/chart/README.md +++ b/source_worker/chart/README.md @@ -13,7 +13,10 @@ operator-supplied `@sha256:` references. Build the worker from the same reviewed revision as the chart. The proxy baseline is the digest in [`../compose.yaml`](../compose.yaml); an alternate build must pass the same proxy qualification with the unchanged configuration. Configure image pulls at -the node if the worker image is private. +the node if the worker image is private. The proxy supports IPv4 Pod and Service +addresses only. The chart requests an IPv4 ClusterIP and requires IPv4 DNS and +CIDR values. Deploy it only where the Pod, Service and credential backend have +IPv4 connectivity. ## Inputs diff --git a/source_worker/chart/templates/networkpolicy.yaml b/source_worker/chart/templates/networkpolicy.yaml index a79be4dc9f..bd62476b11 100644 --- a/source_worker/chart/templates/networkpolicy.yaml +++ b/source_worker/chart/templates/networkpolicy.yaml @@ -20,9 +20,8 @@ spec: egress: - to: {{- range .Values.network.dns.nameservers }} - {{- $prefix := ternary 128 32 (contains ":" .) }} - ipBlock: - cidr: {{ printf "%s/%d" . $prefix | quote }} + cidr: {{ printf "%s/32" . | quote }} {{- end }} {{- range .Values.network.dns.pods }} - {{ include "loom-source-worker.podPeer" . | nindent 10 | trim }} diff --git a/source_worker/chart/templates/service.yaml b/source_worker/chart/templates/service.yaml index c011165b4f..dd6f63cd12 100644 --- a/source_worker/chart/templates/service.yaml +++ b/source_worker/chart/templates/service.yaml @@ -6,6 +6,8 @@ metadata: namespace: {{ .Release.Namespace | quote }} spec: type: ClusterIP + ipFamilyPolicy: SingleStack + ipFamilies: [IPv4] selector: {{- include "loom-source-worker.selector" . | nindent 4 }} ports: diff --git a/source_worker/chart/values.schema.json b/source_worker/chart/values.schema.json index d725ec677f..c260f90c16 100644 --- a/source_worker/chart/values.schema.json +++ b/source_worker/chart/values.schema.json @@ -60,16 +60,8 @@ "maxItems": 3, "uniqueItems": true, "items": { - "anyOf": [ - { - "format": "ipv4", - "type": "string" - }, - { - "format": "ipv6", - "type": "string" - } - ] + "format": "ipv4", + "type": "string" } }, "pods": { @@ -98,8 +90,8 @@ "properties": { "cidr": { "type": "string", - "pattern": "^[0-9A-Fa-f:.]+/[1-9][0-9]{0,2}$", - "maxLength": 43 + "pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}/([1-9]|[12][0-9]|3[0-2])$", + "maxLength": 18 }, "port": { "$ref": "#/definitions/port" From 7438e8c83b510932d76b701f1631fde34ba08c93 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 10:03:22 +0000 Subject: [PATCH 12/31] Keep Helm source templates distinct from rendered YAML Signed-off-by: zlareb1 --- source_worker/chart/README.md | 11 ++++++----- .../{networkpolicy.yaml => networkpolicy.yaml.tpl} | 0 .../templates/{service.yaml => service.yaml.tpl} | 0 .../{serviceaccount.yaml => serviceaccount.yaml.tpl} | 0 .../templates/{workload.yaml => workload.yaml.tpl} | 0 5 files changed, 6 insertions(+), 5 deletions(-) rename source_worker/chart/templates/{networkpolicy.yaml => networkpolicy.yaml.tpl} (100%) rename source_worker/chart/templates/{service.yaml => service.yaml.tpl} (100%) rename source_worker/chart/templates/{serviceaccount.yaml => serviceaccount.yaml.tpl} (100%) rename source_worker/chart/templates/{workload.yaml => workload.yaml.tpl} (100%) diff --git a/source_worker/chart/README.md b/source_worker/chart/README.md index 26bfccc878..af961f766f 100644 --- a/source_worker/chart/README.md +++ b/source_worker/chart/README.md @@ -25,11 +25,12 @@ the objects; they do not contain config or credentials. Every listed key is required. A missing object or key prevents volume setup. Invalid configuration or credential syntax stops the worker; invalid proxy TLS files stop nginx. -| Value | Object and required keys | Mount | -| --- | --- | --- | -| `inputs.workerConfigMap` | ConfigMap: `config.json`, `grant-verifier.pem`, `vault-ca.pem` | Worker only, read-only at `/etc/loom-source-worker`. | -| `inputs.vaultTokenSecret` | Secret: `vault-token` | Worker only, read-only at `/run/loom-source-worker/credentials/vault-token`, mode `0440`, group `10001`. | -| `inputs.proxyTlsSecret` | Separate Secret: `server-chain.pem`, `server-key.pem`, `client-ca.pem` | Proxy only, read-only at `/etc/nginx/tls`. | +- `inputs.workerConfigMap`: `config.json`, `grant-verifier.pem` and + `vault-ca.pem`. Worker only, read-only at `/etc/loom-source-worker`. +- `inputs.vaultTokenSecret`: `vault-token`. Worker only, read-only at + `/run/loom-source-worker/credentials/vault-token`, mode `0440`, group `10001`. +- `inputs.proxyTlsSecret`: a separate Secret with `server-chain.pem`, + `server-key.pem` and `client-ca.pem`. Proxy only, read-only at `/etc/nginx/tls`. Use the [worker config and grant contract](../README.md). Set `transport: tls_proxy_unix` in the worker config. Mount the Vault CA bundle and diff --git a/source_worker/chart/templates/networkpolicy.yaml b/source_worker/chart/templates/networkpolicy.yaml.tpl similarity index 100% rename from source_worker/chart/templates/networkpolicy.yaml rename to source_worker/chart/templates/networkpolicy.yaml.tpl diff --git a/source_worker/chart/templates/service.yaml b/source_worker/chart/templates/service.yaml.tpl similarity index 100% rename from source_worker/chart/templates/service.yaml rename to source_worker/chart/templates/service.yaml.tpl diff --git a/source_worker/chart/templates/serviceaccount.yaml b/source_worker/chart/templates/serviceaccount.yaml.tpl similarity index 100% rename from source_worker/chart/templates/serviceaccount.yaml rename to source_worker/chart/templates/serviceaccount.yaml.tpl diff --git a/source_worker/chart/templates/workload.yaml b/source_worker/chart/templates/workload.yaml.tpl similarity index 100% rename from source_worker/chart/templates/workload.yaml rename to source_worker/chart/templates/workload.yaml.tpl From 78ea5e513bb64e50555375ac9c445a2e216b9078 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 09:55:13 +0000 Subject: [PATCH 13/31] Keep listed resource identities exact before selection Signed-off-by: zlareb1 (cherry picked from commit 6724d19604a995f93f4a4b75f94a0cd362fb73a0) --- .../loom_source_worker/mcp_client.py | 31 ++++++++++++++----- source_worker/tests/test_mcp_client.py | 12 ++++++- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 7c840219d7..4a57fbd2ff 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -1165,17 +1165,34 @@ async def list_resources(self, cursor: str | None = None) -> MCPPage: async def action(session: ClientSession) -> MCPPage: if self._discovery is None or not self._discovery.resources: raise MCPSourceError("unsupported") - self._page_start(cursor, ("resources", "")) - result = await session.list_resources( - params=types.PaginatedRequestParams(cursor=cursor) + scope = ("resources", "") + self._page_start(cursor, scope) + result = await session.send_request( + types.ClientRequest( + types.ListResourcesRequest(params=types.PaginatedRequestParams(cursor=cursor)) + ), + types.Result, ) + data = result.model_dump(by_alias=True, exclude_unset=True) + limits, policy = self._config.limits, self._config.data_policy + _bounded_data(data, limits.max_wire_bytes, policy) + resources = data.get("resources") + if not isinstance(resources, list) or len(resources) > limits.max_results: + raise MCPSourceError("limit") items = [] - for resource in result.resources: - identity = _string(str(resource.uri)) - title = _string(resource.title or resource.name) + for resource in resources: + if not isinstance(resource, dict): + raise MCPSourceError("schema") + identity = _string(resource.get("uri")) + # Keep the selected identity tied to the exact URI the server exposed. + _resource_url(identity) + title = _string(resource.get("title") or resource.get("name")) items.append(MCPEvidence(identity, identity, title)) self._resource_titles[identity] = title - return self._page(items, result.nextCursor, ("resources", "")) + next_cursor = data.get("nextCursor") + if next_cursor is not None: + next_cursor = _string(next_cursor) + return self._page(items, next_cursor, scope) return await self._run(action) diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 2c2e18ac53..fd53402ae6 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -97,6 +97,7 @@ def __init__(self) -> None: self.content_encoding = "identity" self.resource_text = "synthetic text" self.resource_uri = _DOCUMENT + self.listed_uri = _DOCUMENT self.resource_parts = 1 self.initialize_error: int | None = None self.resource_error: int | None = None @@ -142,7 +143,7 @@ async def respond(self, request: httpx.Request) -> httpx.Response: {"resources": []} if body.get("params", {}).get("cursor") == "next" else { - "resources": [{"uri": _DOCUMENT, "name": "Synthetic document"}], + "resources": [{"uri": self.listed_uri, "name": "Synthetic document"}], "nextCursor": "next", } ) @@ -542,6 +543,15 @@ async def test_resource_parser_bounds_cover_metadata_and_extensions( await client.read(_DOCUMENT) +@pytest.mark.asyncio +async def test_list_does_not_offer_a_normalized_replacement_identity(pin: list[str]) -> None: + source = _Source() + source.listed_uri = "https://UPSTREAM.example/path" + async with _client(source) as client: + with pytest.raises(MCPSourceError, match="^MCP source unsupported$"): + await client.list_resources() + + @pytest.mark.asyncio async def test_revocation_is_checked_after_a_mapped_tool_error(pin: list[str]) -> None: source, mapping = _mapped_source() From 2d952071917d59a96c5c2c43817519ea0f0af275 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 10:06:49 +0000 Subject: [PATCH 14/31] List chart qualification checks in plain Markdown Signed-off-by: zlareb1 --- source_worker/chart/README.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/source_worker/chart/README.md b/source_worker/chart/README.md index af961f766f..0e0abcbf15 100644 --- a/source_worker/chart/README.md +++ b/source_worker/chart/README.md @@ -120,15 +120,13 @@ backend, independent issuer keys, synthetic PKI and controlled HTTPS MCP endpoints. Run server-side dry-run and wait for Pod admission and readiness. Record the exact chart revision, tool versions, CNI, image digests and checks. -| Check | Expected result | -| --- | --- | -| Missing input object, missing key, bad token permissions or invalid proxy TLS | No ready endpoints. No fallback listener or credentials. | -| Runtime mounts | Worker socket directory `10001:10001` mode `0700`, socket `0600`, Vault file mode `0440`; no token in proxy or Loom and no service-account token in either container. | -| Approved caller, trusted client certificate and valid signed grant | Bodyless HTTP/1.1 `POST /v1/live` and `POST /v1/check-access` work; only the live response has content. Responses carry `Cache-Control: no-store`. | -| No or untrusted client certificate; wrong server name or CA; plaintext; forged or missing grant | No protected result; no caller TLS bypass or plaintext route. | -| Extra headers, nonempty body, transfer encoding or unlisted method/path | Proxy forwards only the grant and fixed upstream Host; rejects disallowed requests without an upstream read. | -| Same labels in a different namespace, wrong caller labels, unapproved TCP destination/port, and unauthorized DNS | Policy blocks them. The approved DNS, Vault and MCP destinations still work. | -| Log, volume and restart inspection | Synthetic body and token markers absent from proxy and worker logs, termination messages and proxy temp files. No stale socket route after worker restart; readiness and mTLS recover after restart and reviewed rotation. | +- **Missing input object, missing key, bad token permissions or invalid proxy TLS.** No ready endpoints. No fallback listener or credentials. +- **Runtime mounts.** Worker socket directory `10001:10001` mode `0700`, socket `0600`, Vault file mode `0440`; no token in proxy or Loom and no service-account token in either container. +- **Approved caller, trusted client certificate and valid signed grant.** Bodyless HTTP/1.1 `POST /v1/live` and `POST /v1/check-access` work; only the live response has content. Responses carry `Cache-Control: no-store`. +- **No or untrusted client certificate; wrong server name or CA; plaintext; forged or missing grant.** No protected result; no caller TLS bypass or plaintext route. +- **Extra headers, nonempty body, transfer encoding or unlisted method/path.** Proxy forwards only the grant and fixed upstream Host; rejects disallowed requests without an upstream read. +- **Same labels in a different namespace, wrong caller labels, unapproved TCP destination/port, and unauthorized DNS.** Policy blocks them. The approved DNS, Vault and MCP destinations still work. +- **Log, volume and restart inspection.** Synthetic body and token markers absent from proxy and worker logs, termination messages and proxy temp files. No stale socket route after worker restart; readiness and mTLS recover after restart and reviewed rotation. Remove the hosted synthetic resources after recording results. Rendering and schema checks do not qualify mTLS, file ownership, DNS translation or CNI From 2669d764ec3bcc84ba701963d2e98d27718114d0 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 10:28:23 +0000 Subject: [PATCH 15/31] Validate MCP catalog rows and worker chart egress Signed-off-by: zlareb1 --- .../workflows/mcp-source-worker-deployment.yml | 8 ++++++++ source_worker/chart/README.md | 4 +++- source_worker/chart/templates/_helpers.tpl | 16 ++++++++++++++++ .../chart/templates/networkpolicy.yaml.tpl | 2 +- source_worker/chart/templates/workload.yaml.tpl | 7 ++----- source_worker/chart/values.schema.json | 2 +- source_worker/loom_source_worker/mcp_client.py | 6 +++++- source_worker/tests/test_mcp_client.py | 12 +++++++++++- 8 files changed, 47 insertions(+), 10 deletions(-) diff --git a/.github/workflows/mcp-source-worker-deployment.yml b/.github/workflows/mcp-source-worker-deployment.yml index 4f2fc8d33b..bd6f3bc752 100644 --- a/.github/workflows/mcp-source-worker-deployment.yml +++ b/.github/workflows/mcp-source-worker-deployment.yml @@ -71,3 +71,11 @@ jobs: echo 'IPv6-only nameserver was accepted' >&2 exit 1 fi + grep -Fq "socket.create_connection(('127.0.0.1', 8443)" <<< "$rendered" + for cidr in 999.0.2.44/32 192.0.2.44/24; do + if helm template source-worker "$chart" -f "$values" \ + --set-string "network.httpsCidrs[0].cidr=$cidr"; then + echo 'Invalid IPv4 network was accepted' >&2 + exit 1 + fi + done diff --git a/source_worker/chart/README.md b/source_worker/chart/README.md index 0e0abcbf15..2942c9862e 100644 --- a/source_worker/chart/README.md +++ b/source_worker/chart/README.md @@ -16,7 +16,9 @@ proxy qualification with the unchanged configuration. Configure image pulls at the node if the worker image is private. The proxy supports IPv4 Pod and Service addresses only. The chart requests an IPv4 ClusterIP and requires IPv4 DNS and CIDR values. Deploy it only where the Pod, Service and credential backend have -IPv4 connectivity. +IPv4 connectivity. The readiness probe checks the worker socket and the proxy's +IPv4 loopback listener from inside the Pod, independent of its primary address. +Use canonical IPv4 networks for HTTPS egress, with host bits set to zero. ## Inputs diff --git a/source_worker/chart/templates/_helpers.tpl b/source_worker/chart/templates/_helpers.tpl index 0add3349a5..505d77f225 100644 --- a/source_worker/chart/templates/_helpers.tpl +++ b/source_worker/chart/templates/_helpers.tpl @@ -27,3 +27,19 @@ podSelector: {{ $label | quote }}: {{ $value | quote }} {{- end }} {{- end -}} + +{{- define "loom-source-worker.ipv4Network" -}} +{{- $parts := splitList "/" . -}} +{{- $address := 0 -}} +{{- range (splitList "." (index $parts 0)) -}} +{{- $address = add (mul $address 256) (int .) -}} +{{- end -}} +{{- $hostBlock := 1 -}} +{{- range (until (int (sub 32 (int (index $parts 1))))) -}} +{{- $hostBlock = mul $hostBlock 2 -}} +{{- end -}} +{{- if ne (mod $address $hostBlock) 0 -}} +{{- fail "source worker HTTPS egress CIDR has host bits set" -}} +{{- end -}} +{{- . -}} +{{- end -}} diff --git a/source_worker/chart/templates/networkpolicy.yaml.tpl b/source_worker/chart/templates/networkpolicy.yaml.tpl index bd62476b11..d8840d184e 100644 --- a/source_worker/chart/templates/networkpolicy.yaml.tpl +++ b/source_worker/chart/templates/networkpolicy.yaml.tpl @@ -41,7 +41,7 @@ spec: {{- range .Values.network.httpsCidrs }} - to: - ipBlock: - cidr: {{ .cidr | quote }} + cidr: {{ include "loom-source-worker.ipv4Network" .cidr | quote }} ports: - port: {{ .port }} protocol: TCP diff --git a/source_worker/chart/templates/workload.yaml.tpl b/source_worker/chart/templates/workload.yaml.tpl index 3855e7568f..b64b4d1253 100644 --- a/source_worker/chart/templates/workload.yaml.tpl +++ b/source_worker/chart/templates/workload.yaml.tpl @@ -96,6 +96,8 @@ spec: with socket.socket(socket.AF_UNIX) as probe: probe.settimeout(1) probe.connect('/run/loom-source-worker/socket/worker.sock') + with socket.create_connection(('127.0.0.1', 8443), timeout=0.5): + pass timeoutSeconds: 2 periodSeconds: 5 resources: @@ -118,11 +120,6 @@ spec: - {name: https, containerPort: 8443, protocol: TCP} securityContext: {{- include "loom-source-worker.containerSecurity" . | nindent 12 }} - readinessProbe: - tcpSocket: - port: https - timeoutSeconds: 2 - periodSeconds: 5 resources: requests: {cpu: 50m, memory: 64Mi, ephemeral-storage: 8Mi} limits: {cpu: 500m, memory: 128Mi, ephemeral-storage: 16Mi} diff --git a/source_worker/chart/values.schema.json b/source_worker/chart/values.schema.json index c260f90c16..5456bd2158 100644 --- a/source_worker/chart/values.schema.json +++ b/source_worker/chart/values.schema.json @@ -90,7 +90,7 @@ "properties": { "cidr": { "type": "string", - "pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}/([1-9]|[12][0-9]|3[0-2])$", + "pattern": "^((0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5])/([1-9]|[12][0-9]|3[0-2])$", "maxLength": 18 }, "port": { diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 4a57fbd2ff..2adff9733d 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -1183,10 +1183,14 @@ async def action(session: ClientSession) -> MCPPage: for resource in resources: if not isinstance(resource, dict): raise MCPSourceError("schema") + try: + provider_resource = types.Resource.model_validate(resource) + except ValidationError: + raise MCPSourceError("schema") from None identity = _string(resource.get("uri")) # Keep the selected identity tied to the exact URI the server exposed. _resource_url(identity) - title = _string(resource.get("title") or resource.get("name")) + title = _string(provider_resource.title or provider_resource.name) items.append(MCPEvidence(identity, identity, title)) self._resource_titles[identity] = title next_cursor = data.get("nextCursor") diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index fd53402ae6..1ed0e5c1f7 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -98,6 +98,7 @@ def __init__(self) -> None: self.resource_text = "synthetic text" self.resource_uri = _DOCUMENT self.listed_uri = _DOCUMENT + self.listed_metadata: dict[str, Any] = {"name": "Synthetic document"} self.resource_parts = 1 self.initialize_error: int | None = None self.resource_error: int | None = None @@ -143,7 +144,7 @@ async def respond(self, request: httpx.Request) -> httpx.Response: {"resources": []} if body.get("params", {}).get("cursor") == "next" else { - "resources": [{"uri": self.listed_uri, "name": "Synthetic document"}], + "resources": [{"uri": self.listed_uri, **self.listed_metadata}], "nextCursor": "next", } ) @@ -552,6 +553,15 @@ async def test_list_does_not_offer_a_normalized_replacement_identity(pin: list[s await client.list_resources() +@pytest.mark.asyncio +async def test_catalog_rejects_a_resource_without_its_required_name(pin: list[str]) -> None: + source = _Source() + source.listed_metadata = {"title": "Synthetic title"} + async with _client(source) as client: + with pytest.raises(MCPSourceError, match="^MCP source schema$"): + await client.list_resources() + + @pytest.mark.asyncio async def test_revocation_is_checked_after_a_mapped_tool_error(pin: list[str]) -> None: source, mapping = _mapped_source() From b5dcde08955297681393b848d6eed6196cd0130d Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 10:44:36 +0000 Subject: [PATCH 16/31] Recheck source access after failed session cleanup Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 8 ++-- source_worker/tests/test_mcp_client.py | 45 +++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 2adff9733d..7a08a10737 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -935,13 +935,13 @@ async def __aenter__(self) -> MCPSourceClient: except Exception as error: # noqa: BLE001 — only fixed initialization failures reach callers try: await self._close() - code = await self._initialization_failure(error) + code = await self._recheck_after_close(self._owner_failure or _error_code(error)) finally: self._leave_private() raise MCPSourceError(code) from None - async def _initialization_failure(self, error: Exception) -> ErrorCode: - code = self._owner_failure or _error_code(error) + async def _recheck_after_close(self, code: ErrorCode) -> ErrorCode: + """Report current authority after the SDK owner drains, without another upstream call.""" if self._transport is None or code in {"denied", "closed", "timeout"}: return code if asyncio.get_running_loop().time() >= self._deadline: @@ -1091,6 +1091,8 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T raise if isinstance(error, asyncio.CancelledError): raise + code = await self._recheck_after_close(self._operation_failure or code) + self._operation_failure = code raise MCPSourceError(code) from None async def discover(self) -> MCPDiscovery: diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 1ed0e5c1f7..7052ccd88e 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -92,6 +92,8 @@ def __init__(self) -> None: self.read_started = asyncio.Event() self.read_cancelled = asyncio.Event() self.closed = False + self.close_started = asyncio.Event() + self.release_close: asyncio.Event | None = None self.stall = False self.redirect = False self.content_encoding = "identity" @@ -102,12 +104,16 @@ def __init__(self) -> None: self.resource_parts = 1 self.initialize_error: int | None = None self.resource_error: int | None = None + self.resource_rpc_error = False self.resource_extensions: dict[str, Any] = {} self.notifications: _IdleBody | None = None self.termination: _IdleBody | None = None self.change_tools_during_discovery = False async def aclose(self) -> None: + self.close_started.set() + if self.release_close is not None: + await self.release_close.wait() self.closed = True async def respond(self, request: httpx.Request) -> httpx.Response: @@ -152,6 +158,15 @@ async def respond(self, request: httpx.Request) -> httpx.Response: self.read_started.set() if self.resource_error is not None: return httpx.Response(self.resource_error) + if self.resource_rpc_error: + return httpx.Response( + 200, + json={ + "jsonrpc": "2.0", + "id": body["id"], + "error": {"code": -32603, "message": "synthetic source error"}, + }, + ) if self.stall: try: await asyncio.Future[None]() @@ -676,3 +691,33 @@ async def validate_access() -> None: assert sum(method == "DELETE" for _, method in source.calls) == int(not revoked) with pytest.raises(MCPSourceError, match="^MCP source closed$"): await client.read(_DOCUMENT) + + +@pytest.mark.asyncio +async def test_established_failure_rechecks_authority_after_sdk_cleanup(pin: list[str]) -> None: + source = _Source() + source.resource_rpc_error = True + source.release_close = asyncio.Event() + revoked = False + after_drain = False + + async def current_authority() -> None: + nonlocal after_drain + if revoked: + after_drain = source.closed + raise MCPSourceError("denied") + + config = MCPSourceConfig(_ENDPOINT, approved_resource_ids=(_DOCUMENT,)) + async with MCPSourceClient( + config, None, validate_access=current_authority, _transport=source + ) as client: + read = asyncio.create_task(client.read(_DOCUMENT)) + try: + await asyncio.wait_for(source.close_started.wait(), timeout=2) + revoked = True + finally: + source.release_close.set() + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await read + assert after_drain + assert [method for _, method in source.calls].count("resources/read") == 1 From 741c63322d5cd0f4f0afbe5976c5faad526b7d3b Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 10:57:12 +0000 Subject: [PATCH 17/31] Recheck revoked source access after session teardown Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 2 +- source_worker/tests/test_mcp_client.py | 48 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 7a08a10737..fc3d7ffde9 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -1043,7 +1043,7 @@ async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: await self._close() failure = self._owner_failure if error is None and failure is not None and self._operation_failure is None: - raise MCPSourceError(failure) + raise MCPSourceError(await self._recheck_after_close(failure)) finally: self._leave_private() diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 7052ccd88e..eacadc683a 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -6,6 +6,7 @@ import json import logging from collections.abc import AsyncIterator +from contextlib import AsyncExitStack from dataclasses import FrozenInstanceError, replace from typing import Any @@ -721,3 +722,50 @@ async def current_authority() -> None: await read assert after_drain assert [method for _, method in source.calls].count("resources/read") == 1 + + +@pytest.mark.asyncio +async def test_failed_session_delete_rechecks_authority_after_close(pin: list[str]) -> None: + revoked = False + + class FailingTermination(_Source): + async def respond(self, request: httpx.Request) -> httpx.Response: + if request.method == "DELETE": + self.calls.append((request, request.method)) + return httpx.Response(500) + return await super().respond(request) + + async def aclose(self) -> None: + nonlocal revoked + revoked = True + await super().aclose() + + source = FailingTermination() + after_drain = False + + async def current_authority() -> None: + nonlocal after_drain + if revoked: + after_drain = source.closed + raise MCPSourceError("denied") + + config = MCPSourceConfig(_ENDPOINT, _AUDIENCE, approved_resource_ids=(_DOCUMENT,)) + async with AsyncExitStack() as stack: + client = await stack.enter_async_context( + MCPSourceClient( + config, + MCPBearer("synthetic", _AUDIENCE), + validate_access=current_authority, + _transport=source, + ) + ) + assert (await client.read(_DOCUMENT)).text == source.resource_text + with pytest.raises(MCPSourceError, match="^MCP source denied$"): + await stack.aclose() + + assert after_drain + assert [ + (method, request.headers.get("mcp-session-id")) + for request, method in source.calls + if method in {"resources/read", "DELETE"} + ] == [("resources/read", "synthetic-session"), ("DELETE", "synthetic-session")] From fc47d5c9721c9f24c51a131009f64c636f9802b0 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Tue, 24 Nov 2026 11:09:53 +0000 Subject: [PATCH 18/31] Report revoked access before unsupported source output Signed-off-by: zlareb1 --- .../loom_source_worker/read_service.py | 15 ++++++++++----- source_worker/tests/test_read_service.py | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index e3ca3b45c9..1c2d5987d3 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -142,11 +142,16 @@ async def require_current() -> None: reader = await self._backend.resolve(binding) reader.binding.authorize(grant) await require_current() - document = await reader.read_exact( - binding.resource_id, authorize=require_current, deadline=deadline - ) - fetched_at = int(time.time()) - content_sha256 = self._check_document(binding, document) + try: + document = await reader.read_exact( + binding.resource_id, authorize=require_current, deadline=deadline + ) + fetched_at = int(time.time()) + content_sha256 = self._check_document(binding, document) + except ReadFailure as failure: + if failure.code == "unsupported": + await require_current() + raise await require_current() return ReadResult( grant.request_id, diff --git a/source_worker/tests/test_read_service.py b/source_worker/tests/test_read_service.py index 203cfe1bb5..a2d1a78f2c 100644 --- a/source_worker/tests/test_read_service.py +++ b/source_worker/tests/test_read_service.py @@ -120,6 +120,24 @@ async def test_revocation_before_response_refuses_data(self) -> None: with self.assertRaisesRegex(ReadFailure, "^denied$"): await read + async def test_revocation_precedes_output_limit_refusal(self) -> None: + self.backend.payload = "é" * 65 + service = self._service() + with self.assertRaisesRegex(ReadFailure, "^unsupported$"): + await service.execute(self._token(self._live()), "live") + + self.backend.release.clear() + self.backend.started.clear() + read = asyncio.create_task(service.execute(self._token(self._live()), "live")) + try: + await self.backend.started.wait() + self.backend.binding = self.backend.binding.model_copy(update={"generation": 2}) + finally: + self.backend.release.set() + with self.assertRaisesRegex(ReadFailure, "^denied$"): + await read + self.assertEqual(self.backend.calls, [self.binding.resource_id] * 2) + async def test_wrong_resource_and_large_utf8_body_are_never_returned(self) -> None: service = self._service() self.backend.return_identity = "urn:another-document" From 008ac245253142281ac0760264debb5c29905800 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 09:53:44 +0000 Subject: [PATCH 19/31] Return upstream MCP refusals before the SDK deadline Wake the current RPC when its transport records a terminal failure. Drain the SDK session before returning the fixed status. Cover initial and subsequent HTTP refusals against official resource and mapped tool servers. Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 38 ++++-- source_worker/tests/test_protocol_servers.py | 114 +++++++++++++++++- 2 files changed, 141 insertions(+), 11 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index fc3d7ffde9..d4a7b7a9e2 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -631,8 +631,7 @@ async def __aiter__(self) -> AsyncIterator[bytes]: self.owner._check_state() yield chunk except Exception as error: # noqa: BLE001 — only fixed diagnostics cross the transport boundary - self.owner.failure = self.owner.failure or _error_code(error) - raise MCPSourceError(self.owner.failure) from None + raise MCPSourceError(self.owner.record_failure(error)) from None async def aclose(self) -> None: # The SDK cancels its task group before joining HTTP stream finalizers. @@ -661,9 +660,18 @@ def __init__( self.received, self.requests = 0, 0 self.target: httpx.URL | None = None self.pin_lock = asyncio.Lock() - self.failure: ErrorCode | None = None + self.failed: asyncio.Future[ErrorCode] = asyncio.get_running_loop().create_future() self.terminate_only = False + @property + def failure(self) -> ErrorCode | None: + return self.failed.result() if self.failed.done() else None + + def record_failure(self, error: BaseException) -> ErrorCode: + if not self.failed.done(): + self.failed.set_result(_error_code(error)) + return self.failed.result() + def _check_state(self) -> None: _guard_state(self.deadline, self.failure) @@ -676,8 +684,7 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: try: return await self._handle(request) except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials - self.failure = self.failure or _error_code(error) - raise MCPSourceError(self.failure) from None + raise MCPSourceError(self.record_failure(error)) from None async def _handle(self, request: httpx.Request) -> httpx.Response: response: httpx.Response | None = None @@ -757,8 +764,7 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: handed_off = True return response except Exception as error: # noqa: BLE001 — poison the session before awaiting private failure cleanup - self.failure = self.failure or _error_code(error) - raise MCPSourceError(self.failure) from None + raise MCPSourceError(self.record_failure(error)) from None finally: if response is not None and not handed_off: # Leave the deadline scope before joining an unclaimed response's finalizer. @@ -1057,15 +1063,29 @@ async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: with private_work(): return await self._execute(action) + async def _request(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + # The SDK RPC can keep waiting after its HTTP task has refused the request. + assert self._session is not None and self._transport is not None + failed = self._transport.failed + request = asyncio.ensure_future(action(self._session)) + try: + done, _ = await asyncio.wait((request, failed), return_when=asyncio.FIRST_COMPLETED) + if failed in done: + raise MCPSourceError(failed.result()) + return request.result() + finally: + if not request.done(): + request.cancel() + await asyncio.gather(request, return_exceptions=True) + async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: try: self._check_state(require_session=True) async with asyncio.timeout_at(self._deadline): await self._authorize() self._check_state(require_session=True) - assert self._session is not None try: - result = await action(self._session) + result = await self._request(action) except Exception: # Check authority before reporting an upstream error. await self._validate_access() raise diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index b34d009425..c0cfad53dd 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -7,7 +7,7 @@ import json import time from collections.abc import AsyncIterator, Callable -from dataclasses import asdict +from dataclasses import asdict, replace from typing import Any from uuid import UUID, uuid4 @@ -25,7 +25,8 @@ from mcp.server import Server from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from pydantic import AnyUrl, SecretStr -from starlette.types import Receive, Scope, Send +from starlette.requests import Request +from starlette.types import Message, Receive, Scope, Send _ENDPOINT = "https://source.example.test/mcp" _DOC = "urn:fixture:doc" @@ -256,6 +257,115 @@ def grant(target: ReadBinding, operation: str) -> str: await service.execute(grant(bob, "live"), "live") +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["resource", "tool"]) +@pytest.mark.parametrize("phase", ["initialize", "read"]) +@pytest.mark.parametrize(("status", "code"), [(401, "reconnect"), (403, "denied")]) +async def test_upstream_http_refusal_at_sdk_boundary( + mode: str, phase: str, status: int, code: mcp_client.ErrorCode, monkeypatch: pytest.MonkeyPatch +) -> None: + reads = 0 + + def on_read() -> None: + nonlocal reads + reads += 1 + + mapped = mode == "tool" + manager = _tool_server(on_read) if mapped else _resource_server(on_read) + config = MCPSourceConfig( + endpoint=_ENDPOINT, + bearer_audience=_ENDPOINT, + approved_tools=("read",) if mapped else (), + read=MCPToolMapping("read", _INPUT, _OUTPUT, "id") if mapped else None, + limits=MCPLimits(timeout_seconds=12, request_seconds=8), + ) + read_method = "tools/call" if mapped else "resources/read" + refusal_method = "initialize" if phase == "initialize" else read_method + alice_header = b"Bearer synthetic-alice" + armed = phase == "initialize" + posts: list[tuple[bytes | None, str]] = [] + refusals: list[int] = [] + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + if scope["method"] != "POST": + await manager.handle_request(scope, receive, send) + return + + body = await Request(scope, receive).body() + method = json.loads(body)["method"] + bearer = dict(scope["headers"]).get(b"authorization") + posts.append((bearer, method)) + if armed and bearer == alice_header and method == refusal_method: + await send({"type": "http.response.start", "status": status, "headers": []}) + await send({"type": "http.response.body", "body": b"synthetic private refusal"}) + refusals.append(status) + return + + replay_body: bytes | None = body + + async def replay() -> Message: + nonlocal replay_body + if replay_body is None: + return await receive() + payload, replay_body = replay_body, None + return {"type": "http.request", "body": payload} + + await manager.handle_request(scope, replay, send) + + async def validate() -> None: + return None + + def client_for(token: str, selected: str) -> mcp_client.MCPSourceClient: + return mcp_client.MCPSourceClient( + replace(config, approved_resource_ids=(selected,)), + mcp_client.MCPBearer(token, _ENDPOINT), + validate_access=validate, + _transport=_FragmentedASGI(app=app), + ) + + monkeypatch.setattr(mcp_client, "resolve_public_address", _synthetic_pin) + alice = client_for("synthetic-alice", _DOC) + async with manager.run(): + if phase == "initialize": + with pytest.raises(mcp_client.MCPSourceError, match=f"^MCP source {code}$") as refusal: + async with alice: + pytest.fail("upstream refusal opened a client session") + assert refusal.value.code == code + assert posts == [(alice_header, "initialize")] + assert reads == 0 + else: + async with client_for("synthetic-bob", "urn:fixture:peer") as peer: + async with alice: + evidence = await alice.read(_DOC) + assert evidence.resource_id == _DOC + assert evidence.text == f"{mode} fixture body" + assert evidence.receipt is not None + assert evidence.receipt.operation == read_method + assert evidence.receipt.requested_id == _DOC + assert evidence.receipt.identity_verified + armed = True + # A received refusal must finish before the SDK request deadline. + async with asyncio.timeout(2): + with pytest.raises( + mcp_client.MCPSourceError, match=f"^MCP source {code}$" + ) as refusal: + await alice.read(_DOC) + assert refusal.value.code == code + + if mapped: + assert (await peer.discover()).tools == ("read",) + else: + [listed] = (await peer.list_resources()).items + assert listed.resource_id == _DOC + with pytest.raises(mcp_client.MCPSourceError, match="^MCP source denied$"): + await peer.read(_DOC) + + read_bearers = [bearer for bearer, method in posts if method == read_method] + assert read_bearers == [alice_header, alice_header] + assert reads == 1 + assert refusals == [status] + + @pytest.mark.asyncio async def test_cancel_terminates_an_active_stateful_sdk_session( monkeypatch: pytest.MonkeyPatch, From 69f7d6bf422458301df53ad15a15eca8c6b1eaef Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:04:17 +0000 Subject: [PATCH 20/31] Keep mapped discovery refusals in the read operation Signed-off-by: zlareb1 --- source_worker/README.md | 114 +++++++++++++++++- .../loom_source_worker/mcp_client.py | 83 ++++++------- source_worker/tests/test_protocol_servers.py | 22 +++- 3 files changed, 172 insertions(+), 47 deletions(-) diff --git a/source_worker/README.md b/source_worker/README.md index 1ee68d8c5c..ce152f4190 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -32,8 +32,10 @@ Mount these files and directories in the worker: Run the proxy and worker under the same numeric UID, `10001` in the image. The worker requires an owned `0700` directory and creates the socket with mode `0600`. Share only the socket directory with the proxy. Keep the -credential mount out of the proxy and Loom containers. Give the worker token -read access only to its dedicated KV v2 connection prefix. Store each record +credential mount out of the proxy and Loom containers. The Vault token file +must be a regular file owned by root or the worker UID, with mode `0400` or +`0440` and readable by the worker. Give that token read access only to its +dedicated KV v2 connection prefix. Store each record under the worker UUID and opaque connection UUID; the record binds the owner, organization, profile and generation to that connection. The generation must match the current secret version. Rotate or revoke at the credential backend; @@ -53,6 +55,114 @@ capacity limits. It never authorizes a stored write. The issuer must check selection and requester authority before issuing it and before delivering a result. The worker rechecks its connection during the read and before reply. +## Resource profile and credential example + +The names and IDs below are synthetic. Use the service's approved HTTPS +endpoint and the audience for which its token was issued. The stored audience +must exactly match `bearer_audience`, including any path. The configured +audience and endpoint must have the same HTTPS origin. For an anonymous profile, +omit `bearer_audience` and use an `anonymous` record without a token, audience +or expiration. Do not set `approved_resource_ids` in either profile; the issuer +selects one exact resource in each grant. + +Save the worker configuration as `config.json`: + +```json +{ + "transport": "tls_proxy_unix", + "worker_id": "83d061b4-2542-4db7-adc0-4b81b3280c08", + "issuer": "source-grants", + "vault": {"origin": "https://vault.example:8200", "mount": "worker-connections"}, + "read_limits": { + "concurrent": 8, + "concurrent_per_org": 2, + "timeout_seconds": 20, + "content_bytes": 100000 + }, + "profiles": [{ + "organizations": ["tenant"], + "link_origins": ["https://docs.example"], + "config": { + "endpoint": "https://mcp.example/rpc", + "bearer_audience": "https://mcp.example/rpc" + } + }] +} +``` + +Use the parser from the installed worker version to compute the profile digest. +It includes parsed defaults as well as the profile's tenant and link settings. +Run this offline with the intended configuration; it does not read the token. + +```sh +python - <<'PYTHON' +from pathlib import Path +from loom_source_worker.main import _parse_settings + +settings = _parse_settings(Path("config.json").read_bytes()) +print(settings.profiles[0].digest) +PYTHON +``` + +For a first secret version, write this record under +`83d061b4-2542-4db7-adc0-4b81b3280c08/507d2572-b7e0-4a8c-8b87-195dd473ca29` +in the `worker-connections` KV v2 mount. Replace the two uppercase placeholders +and set `expires_at` to the issued token's actual Unix expiration in seconds. +When writing through the KV v2 API, send this record as its `data` object. +Production tokens belong in the secret store; keep them out of commands, +configuration and logs. The record's generation must match Vault's version. + +```json +{ + "binding": { + "worker_id": "83d061b4-2542-4db7-adc0-4b81b3280c08", + "org": "tenant", + "owner": "alice", + "connection_id": "507d2572-b7e0-4a8c-8b87-195dd473ca29", + "generation": 1, + "profile_digest": "PROFILE_DIGEST" + }, + "state": "active", + "auth": "bearer", + "audience": "https://mcp.example/rpc", + "token": "UPSTREAM_TOKEN", + "expires_at": 2000000000 +} +``` + +Use the same profile digest in this grant payload. The issuer must derive each +field from current authority and selection, and use a fresh request UUID. + +```json +{ + "version": 1, + "request_id": "63f8514d-7bcd-4144-b43e-78785d04b08b", + "operation": "live", + "binding": { + "worker_id": "83d061b4-2542-4db7-adc0-4b81b3280c08", + "org": "tenant", + "namespace": "collection", + "source_id": "d07561a2-791b-4fef-a5f2-8bdaf903000a", + "selection_generation": 1, + "requester": "alice", + "connection_id": "507d2572-b7e0-4a8c-8b87-195dd473ca29", + "connection_generation": 1, + "profile_digest": "PROFILE_DIGEST", + "resource_id": "urn:example:document:one" + } +} +``` + +Load the payload with `loom_source_worker.protocol.ReadGrant.model_validate_json` +and sign it with `issue_read_grant(grant, issuer="source-grants", key=signing_key, +lifetime_seconds=10)` on the issuer. Mount only the corresponding public key +in the worker. Send the resulting grant as the authorization bearer on the +matching route. For `/v1/check-access`, use operation `check_access`. + +Both routes return `200` with `ok` on success, `403` for `denied`, `409` for +`reconnect`, `422` for `unsupported`, `429` for `overloaded`, `503` for +`unavailable`, and `504` for `timeout`. A body or query is rejected with `400`. + ## Docker Compose `compose.yaml` starts the worker and its TLS proxy only when the `source-worker` diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index d4a7b7a9e2..d1afb57ec9 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -1116,47 +1116,47 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T raise MCPSourceError(code) from None async def discover(self) -> MCPDiscovery: - async def action(session: ClientSession) -> MCPDiscovery: - approved = set(self._config.approved_tools) - epoch = self._tool_epoch - found: set[str] = set() - cursor: str | None = None - seen: set[str] = set() - if approved: - for _ in range(self._config.limits.max_pages): - result = await session.list_tools( - params=types.PaginatedRequestParams(cursor=cursor) - ) - if len(result.tools) > self._config.limits.max_results: - raise MCPSourceError("limit") - for tool in result.tools: - if tool.name in seen: - raise MCPSourceError("schema") - seen.add(tool.name) - if tool.name not in approved: - continue - for mapping in (self._config.search, self._config.read): - if mapping is not None and mapping.name == tool.name: - _check_tool_schema(tool, mapping, self._config.data_policy) - found.add(tool.name) - if len(seen) > self._config.limits.max_results: - raise MCPSourceError("limit") - cursor = result.nextCursor - if cursor is None: - break - _string(cursor) - else: + return await self._run(self._discover) + + async def _discover(self, session: ClientSession) -> MCPDiscovery: + approved = set(self._config.approved_tools) + epoch = self._tool_epoch + found: set[str] = set() + cursor: str | None = None + seen: set[str] = set() + if approved: + for _ in range(self._config.limits.max_pages): + result = await session.list_tools( + params=types.PaginatedRequestParams(cursor=cursor) + ) + if len(result.tools) > self._config.limits.max_results: raise MCPSourceError("limit") - if found != approved: - raise MCPSourceError("unsupported") - if epoch != self._tool_epoch: - raise MCPSourceError("schema") - assert self._discovery is not None - self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) - self._discovered_epoch = epoch - return self._discovery - - return await self._run(action) + for tool in result.tools: + if tool.name in seen: + raise MCPSourceError("schema") + seen.add(tool.name) + if tool.name not in approved: + continue + for mapping in (self._config.search, self._config.read): + if mapping is not None and mapping.name == tool.name: + _check_tool_schema(tool, mapping, self._config.data_policy) + found.add(tool.name) + if len(seen) > self._config.limits.max_results: + raise MCPSourceError("limit") + cursor = result.nextCursor + if cursor is None: + break + _string(cursor) + else: + raise MCPSourceError("limit") + if found != approved: + raise MCPSourceError("unsupported") + if epoch != self._tool_epoch: + raise MCPSourceError("schema") + assert self._discovery is not None + self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) + self._discovered_epoch = epoch + return self._discovery def _page_start(self, cursor: str | None, scope: tuple[str, str]) -> None: if cursor is not None: @@ -1225,7 +1225,8 @@ async def action(session: ClientSession) -> MCPPage: async def _tool( self, session: ClientSession, mapping: MCPToolMapping, value: str, cursor: str | None = None ) -> Any: - await self.discover() + # Discovery and the mapped call share one terminal transport result. + await self._discover(session) if ( self._tool_epoch != self._discovered_epoch or self._discovery is None diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index c0cfad53dd..727b9d10e9 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -258,8 +258,16 @@ def grant(target: ReadBinding, operation: str) -> str: @pytest.mark.asyncio -@pytest.mark.parametrize("mode", ["resource", "tool"]) -@pytest.mark.parametrize("phase", ["initialize", "read"]) +@pytest.mark.parametrize( + ("mode", "phase"), + [ + ("resource", "initialize"), + ("resource", "read"), + ("tool", "initialize"), + ("tool", "read"), + ("tool", "discover"), + ], +) @pytest.mark.parametrize(("status", "code"), [(401, "reconnect"), (403, "denied")]) async def test_upstream_http_refusal_at_sdk_boundary( mode: str, phase: str, status: int, code: mcp_client.ErrorCode, monkeypatch: pytest.MonkeyPatch @@ -280,7 +288,9 @@ def on_read() -> None: limits=MCPLimits(timeout_seconds=12, request_seconds=8), ) read_method = "tools/call" if mapped else "resources/read" - refusal_method = "initialize" if phase == "initialize" else read_method + refusal_method = {"initialize": "initialize", "read": read_method, "discover": "tools/list"}[ + phase + ] alice_header = b"Bearer synthetic-alice" armed = phase == "initialize" posts: list[tuple[bytes | None, str]] = [] @@ -361,7 +371,11 @@ def client_for(token: str, selected: str) -> mcp_client.MCPSourceClient: await peer.read(_DOC) read_bearers = [bearer for bearer, method in posts if method == read_method] - assert read_bearers == [alice_header, alice_header] + assert read_bearers == [alice_header] * (1 if phase == "discover" else 2) + if phase == "discover": + assert [method for bearer, method in posts if bearer == alice_header][-1] == ( + "tools/list" + ) assert reads == 1 assert refusals == [status] From 34ed8cbabb90f5e67be2ea302abe5ebc8ec0396b Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:14:00 +0000 Subject: [PATCH 21/31] Report upstream MCP outages as temporary unavailability Signed-off-by: zlareb1 --- source_worker/README.md | 27 ++-- .../loom_source_worker/direct_backend.py | 2 + .../loom_source_worker/mcp_client.py | 18 ++- source_worker/tests/test_protocol_servers.py | 138 +++++++++++++++++- 4 files changed, 169 insertions(+), 16 deletions(-) diff --git a/source_worker/README.md b/source_worker/README.md index ce152f4190..535c560324 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -72,21 +72,23 @@ Save the worker configuration as `config.json`: "transport": "tls_proxy_unix", "worker_id": "83d061b4-2542-4db7-adc0-4b81b3280c08", "issuer": "source-grants", - "vault": {"origin": "https://vault.example:8200", "mount": "worker-connections"}, + "vault": { "origin": "https://vault.example:8200", "mount": "worker-connections" }, "read_limits": { "concurrent": 8, "concurrent_per_org": 2, "timeout_seconds": 20, "content_bytes": 100000 }, - "profiles": [{ - "organizations": ["tenant"], - "link_origins": ["https://docs.example"], - "config": { - "endpoint": "https://mcp.example/rpc", - "bearer_audience": "https://mcp.example/rpc" + "profiles": [ + { + "organizations": ["tenant"], + "link_origins": ["https://docs.example"], + "config": { + "endpoint": "https://mcp.example/rpc", + "bearer_audience": "https://mcp.example/rpc" + } } - }] + ] } ``` @@ -159,9 +161,14 @@ lifetime_seconds=10)` on the issuer. Mount only the corresponding public key in the worker. Send the resulting grant as the authorization bearer on the matching route. For `/v1/check-access`, use operation `check_access`. -Both routes return `200` with `ok` on success, `403` for `denied`, `409` for +The worker returns `200` with `ok` on success, `403` for `denied`, `409` for `reconnect`, `422` for `unsupported`, `429` for `overloaded`, `503` for -`unavailable`, and `504` for `timeout`. A body or query is rejected with `400`. +`unavailable`, and `504` for `timeout`. Connection errors, upstream 5xx and an +expired stateful MCP session return `unavailable`. Any retry needs current +authority and a new session; the worker does not retry inside the failed read. +The worker handler refuses a body or query with `400`. The TLS proxy rejects +query strings and other request targets outside the two routes with `404`, and +may return `413` when a body exceeds the proxy's limit. ## Docker Compose diff --git a/source_worker/loom_source_worker/direct_backend.py b/source_worker/loom_source_worker/direct_backend.py index c5f5c7da97..7e66b248ac 100644 --- a/source_worker/loom_source_worker/direct_backend.py +++ b/source_worker/loom_source_worker/direct_backend.py @@ -103,6 +103,8 @@ async def require_current() -> None: mapped: dict[str, FailureCode] = { "denied": "denied", "reconnect": "reconnect", + "session_ended": "unavailable", + "unavailable": "unavailable", "timeout": "timeout", } raise ReadFailure(mapped.get(error.code, "unsupported")) from None diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index d1afb57ec9..114ce443c4 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -35,6 +35,8 @@ "unsupported", "denied", "reconnect", + "session_ended", + "unavailable", "protocol", "schema", "limit", @@ -52,6 +54,8 @@ def __init__(self, code: ErrorCode) -> None: "unsupported", "denied", "reconnect", + "session_ended", + "unavailable", "protocol", "schema", "limit", @@ -68,6 +72,8 @@ def _error_code(error: BaseException) -> ErrorCode: return error.code if isinstance(error, (TimeoutError, httpx.TimeoutException)): return "timeout" + if isinstance(error, httpx.NetworkError): + return "unavailable" if isinstance(error, McpError) and error.error.code == httpx.codes.REQUEST_TIMEOUT: return "timeout" if isinstance(error, BaseExceptionGroup): @@ -77,6 +83,8 @@ def _error_code(error: BaseException) -> ErrorCode: "reconnect", "limit", "timeout", + "session_ended", + "unavailable", "schema", "unsupported", "closed", @@ -96,12 +104,18 @@ def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = T raise MCPSourceError("timeout") -def _check_response(method: str, response: httpx.Response) -> None: +def _check_response(method: str, response: httpx.Response, *, has_session: bool) -> None: status = response.status_code if status == 401: raise MCPSourceError("reconnect") if response.is_redirect or status == 403: raise MCPSourceError("denied") + if 500 <= status < 600: + raise MCPSourceError("unavailable") + if status == 404 and has_session: + if method == "DELETE": + return + raise MCPSourceError("session_ended") if status == 405 and method in {"GET", "DELETE"}: return if method == "DELETE": @@ -752,7 +766,7 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: await self._authorize() response = await self.inner.handle_async_request(outgoing) self._check_state() - _check_response(request.method, response) + _check_response(request.method, response, has_session="mcp-session-id" in headers) if request.method == "DELETE": return httpx.Response(response.status_code, content=b"") # Reject compression so the wire budget bounds decoded protocol bytes. diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index 727b9d10e9..cfdca2936f 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -16,7 +16,8 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from loom_source_worker import direct_backend, mcp_client from loom_source_worker.credential_store import CredentialRecord -from loom_source_worker.direct_backend import DirectBackend +from loom_source_worker.direct_backend import ApprovedProfile, DirectBackend +from loom_source_worker.http_service import create_app from loom_source_worker.main import _parse_settings from loom_source_worker.mcp_client import MCPLimits, MCPSourceConfig, MCPToolMapping from loom_source_worker.protocol import ConnectionBinding, ReadBinding, ReadGrant, issue_read_grant @@ -99,7 +100,9 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: ) -def _resource_server(on_read: Callable[[], None]) -> StreamableHTTPSessionManager: +def _resource_server( + on_read: Callable[[], None], *, stateless: bool = True +) -> StreamableHTTPSessionManager: server: Server[Any, Any] = Server("synthetic-resources") @server.list_resources() @@ -112,7 +115,9 @@ async def read_resource(uri: AnyUrl) -> str: on_read() return "resource fixture body" - return StreamableHTTPSessionManager(app=server, json_response=False, stateless=True) + return StreamableHTTPSessionManager( + app=server, json_response=not stateless, stateless=stateless + ) def _tool_server(on_read: Callable[[], None]) -> StreamableHTTPSessionManager: @@ -381,7 +386,126 @@ def client_for(token: str, selected: str) -> mcp_client.MCPSourceClient: @pytest.mark.asyncio +@pytest.mark.parametrize( + ("route", "operation"), [("live", "live"), ("check-access", "check_access")] +) +@pytest.mark.parametrize( + ("fault", "status"), + [("network", 503), ("upstream-503", 503), ("expired-session", 503), ("missing-endpoint", 422)], +) +async def test_signed_route_distinguishes_transport_failure_from_unsupported( + route: str, operation: str, fault: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + faulted = True + stale_session: bytes | None = None + successful_sessions: list[bytes] = [] + manager = _resource_server(lambda: None, stateless=False) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + nonlocal stale_session + if scope["method"] != "POST": + await manager.handle_request(scope, receive, send) + return + body = await Request(scope, receive).body() + method = json.loads(body)["method"] + session = dict(scope["headers"]).get(b"mcp-session-id") + if method == "initialize" and faulted and fault == "network": + raise httpx.ConnectError("synthetic private network detail") + refused = None + if method == "initialize" and faulted and fault in {"upstream-503", "missing-endpoint"}: + assert session is None + refused = 503 if fault == "upstream-503" else 404 + elif method == "resources/read": + assert session + if faulted and fault == "expired-session": + stale_session = session + refused = 404 + else: + successful_sessions.append(session) + if refused is not None: + await send({"type": "http.response.start", "status": refused, "headers": []}) + await send({"type": "http.response.body", "body": b"synthetic private HTTP detail"}) + return + + replay_body: bytes | None = body + + async def replay() -> Message: + nonlocal replay_body + if replay_body is None: + return await receive() + payload, replay_body = replay_body, None + return {"type": "http.request", "body": payload} + + await manager.handle_request(scope, replay, send) + + def routed_client(config, credential, *, validate_access, deadline): + return mcp_client.MCPSourceClient( + config, + credential, + validate_access=validate_access, + deadline=deadline, + _transport=httpx.ASGITransport(app=app), + ) + + monkeypatch.setattr(direct_backend, "MCPSourceClient", routed_client) + monkeypatch.setattr(mcp_client, "resolve_public_address", _synthetic_pin) + profile = ApprovedProfile( + MCPSourceConfig(endpoint=_ENDPOINT, bearer_audience=_ENDPOINT), ("org",) + ) + binding = ReadBinding( + worker_id=uuid4(), + org="org", + namespace="team", + source_id=uuid4(), + selection_generation=1, + requester="alice", + connection_id=uuid4(), + connection_generation=1, + profile_digest=profile.digest, + resource_id=_DOC, + ) + key = Ed25519PrivateKey.generate() + service = ReadService( + worker_id=binding.worker_id, + issuer="loom", + verifier=key.public_key(), + backend=DirectBackend(_SyntheticAccounts(binding), (profile,)), + limits=ReadLimits( + concurrent=4, concurrent_per_org=2, timeout_seconds=4, content_bytes=2048 + ), + ) + + def headers() -> dict[str, str]: + grant = ReadGrant.model_validate( + {"request_id": uuid4(), "operation": operation, "binding": binding} + ) + return { + "Authorization": "Bearer " + + issue_read_grant(grant, issuer="loom", key=key, lifetime_seconds=10) + } + + async with ( + manager.run(), + httpx.AsyncClient( + base_url="http://worker.test", transport=httpx.ASGITransport(app=create_app(service)) + ) as worker, + ): + failed = await worker.post(f"/v1/{route}", headers=headers()) + assert failed.status_code == status + assert failed.json() == {"status": "unavailable" if status == 503 else "unsupported"} + assert failed.headers["Cache-Control"] == "no-store" + assert not successful_sessions + faulted = False + succeeded = await worker.post(f"/v1/{route}", headers=headers()) + assert succeeded.status_code == 200 + assert (succeeded.json()["document"] is not None) == (route == "live") + assert len(successful_sessions) == 1 and successful_sessions[0] != stale_session + + +@pytest.mark.asyncio +@pytest.mark.parametrize("delete_status", [200, 404]) async def test_cancel_terminates_an_active_stateful_sdk_session( + delete_status: int, monkeypatch: pytest.MonkeyPatch, ) -> None: started = asyncio.Event() @@ -401,6 +525,12 @@ async def read_resource(uri: AnyUrl) -> str: manager = StreamableHTTPSessionManager(app=server, json_response=True, stateless=False) async def app(scope: Scope, receive: Receive, send: Send) -> None: + if scope["method"] == "DELETE" and delete_status == 404: + terminations.append((dict(scope["headers"])[b"mcp-session-id"], 404)) + await send({"type": "http.response.start", "status": 404, "headers": []}) + await send({"type": "http.response.body", "body": b""}) + return + async def watch(message: Any) -> None: if scope["method"] == "DELETE" and message["type"] == "http.response.start": terminations.append((dict(scope["headers"])[b"mcp-session-id"], message["status"])) @@ -425,4 +555,4 @@ async def validate() -> None: read.cancel() with pytest.raises(asyncio.CancelledError): await read - assert len(terminations) == 1 and terminations[0][0] and terminations[0][1] == 200 + assert len(terminations) == 1 and terminations[0][0] and terminations[0][1] == delete_status From 5aa230fc0a1e2472fde61ddb23f126a2b07e2d52 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:16:32 +0000 Subject: [PATCH 22/31] Hold worker capacity until the response drains Signed-off-by: zlareb1 --- .../loom_source_worker/http_service.py | 82 +++++++++++------- .../loom_source_worker/read_service.py | 10 ++- source_worker/tests/test_read_service.py | 84 +++++++++++++++++++ 3 files changed, 146 insertions(+), 30 deletions(-) diff --git a/source_worker/loom_source_worker/http_service.py b/source_worker/loom_source_worker/http_service.py index 6fcad13563..4ef0c0ec6e 100644 --- a/source_worker/loom_source_worker/http_service.py +++ b/source_worker/loom_source_worker/http_service.py @@ -8,8 +8,9 @@ from starlette.applications import Starlette from starlette.requests import Request -from starlette.responses import JSONResponse, Response +from starlette.responses import JSONResponse from starlette.routing import Route +from starlette.types import Message, Receive, Scope, Send from .read_service import ReadFailure, ReadService @@ -29,53 +30,76 @@ async def _disconnect(request: Request) -> None: pass -def create_app(service: ReadService) -> Starlette: - async def invoke(request: Request, operation: Literal["live", "check_access"]) -> Response: +def _error(code: str, status: int) -> JSONResponse: + return JSONResponse({"status": code}, status, headers=_CACHE_HEADERS) + + +class _ReadRoute: + def __init__(self, service: ReadService, operation: Literal["live", "check_access"]) -> None: + self.service = service + self.operation = operation + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + request = Request(scope, receive) if ( request.url.query or request.headers.get("content-length", "0") != "0" or "transfer-encoding" in request.headers ): - return JSONResponse({"status": "denied"}, 400, headers=_CACHE_HEADERS) + await _error("denied", 400)(scope, receive, send) + return auth = request.headers.getlist("authorization") if len(auth) != 1 or not auth[0].startswith("Bearer "): - return JSONResponse({"status": "denied"}, 403, headers=_CACHE_HEADERS) - result = asyncio.create_task(service.execute(auth[0][7:], operation)) + await _error("denied", 403)(scope, receive, send) + return + result = asyncio.create_task(self._deliver(auth[0][7:], scope, receive, send)) disconnect = asyncio.create_task(_disconnect(request)) try: await asyncio.wait((result, disconnect), return_when=asyncio.FIRST_COMPLETED) - if disconnect.done(): - return Response(status_code=499, headers=_CACHE_HEADERS) - reading = result.result() - response = { - "status": "ok", - "request_id": str(reading.request_id), - "fetched_at": reading.fetched_at, - "content_sha256": reading.content_sha256, - "document": asdict(reading.document) if reading.document else None, - } - return JSONResponse(response, headers=_CACHE_HEADERS) - except ReadFailure as error: - return JSONResponse( - {"status": error.code}, _STATUSES[error.code], headers=_CACHE_HEADERS - ) - except Exception: # noqa: BLE001 — adapter failure text can expose credential or document data - return JSONResponse({"status": "unavailable"}, 503, headers=_CACHE_HEADERS) + if result.done(): + result.result() finally: for task in (result, disconnect): if not task.done(): task.cancel() await asyncio.gather(result, disconnect, return_exceptions=True) - async def live(request: Request) -> Response: - return await invoke(request, "live") + async def _deliver(self, token: str, scope: Scope, receive: Receive, send: Send) -> None: + started = False - async def check_access(request: Request) -> Response: - return await invoke(request, "check_access") + async def emit(message: Message) -> None: + nonlocal started + if message["type"] == "http.response.start": + started = True + await send(message) + try: + async with self.service.admitted_read(token, self.operation) as reading: + body = { + "status": "ok", + "request_id": str(reading.request_id), + "fetched_at": reading.fetched_at, + "content_sha256": reading.content_sha256, + "document": asdict(reading.document) if reading.document else None, + } + await JSONResponse(body, headers=_CACHE_HEADERS)(scope, receive, emit) + except ReadFailure as error: + if not started: + await _error(error.code, _STATUSES[error.code])(scope, receive, send) + except Exception: # noqa: BLE001 — adapter failure text can expose credential or document data + if not started: + await _error("unavailable", 503)(scope, receive, send) + + +def create_app(service: ReadService) -> Starlette: return Starlette( routes=[ - Route("/v1/live", live, methods=["POST"]), - Route("/v1/check-access", check_access, methods=["POST"]), + Route("/v1/live", _ReadRoute(service, "live"), methods=["POST"], name="live"), + Route( + "/v1/check-access", + _ReadRoute(service, "check_access"), + methods=["POST"], + name="check_access", + ), ] ) diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index 1c2d5987d3..ac997e0e0e 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -116,6 +116,14 @@ async def _slot(self, org: str) -> AsyncIterator[None]: del self._by_org[org] async def execute(self, token: str, operation: Literal["live", "check_access"]) -> ReadResult: + async with self.admitted_read(token, operation) as result: + return result + + @asynccontextmanager + async def admitted_read( + self, token: str, operation: Literal["live", "check_access"] + ) -> AsyncIterator[ReadResult]: + """Keep capacity and the deadline until the consumer finishes sending.""" try: grant, expires_at = verify_read_grant( token, issuer=self._issuer, worker_id=self._worker_id, key=self._verifier @@ -153,7 +161,7 @@ async def require_current() -> None: await require_current() raise await require_current() - return ReadResult( + yield ReadResult( grant.request_id, fetched_at, content_sha256, diff --git a/source_worker/tests/test_read_service.py b/source_worker/tests/test_read_service.py index a2d1a78f2c..6bce932202 100644 --- a/source_worker/tests/test_read_service.py +++ b/source_worker/tests/test_read_service.py @@ -3,7 +3,9 @@ import unittest from uuid import uuid4 +import httpx from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from loom_source_worker.http_service import create_app from loom_source_worker.protocol import ( ConnectionBinding, ReadBinding, @@ -161,6 +163,88 @@ async def test_saturation_and_cancellation_release_the_live_slot(self) -> None: self.backend.release.set() self.assertIsNotNone((await service.execute(self._token(self._live()), "live")).document) + async def test_http_body_backpressure_holds_the_org_slot(self) -> None: + app = create_app(self._service(timeout=3)) + sending = asyncio.Event() + drain = asyncio.Event() + + async def blocked_app(scope, receive, send): + async def send_when_ready(message): + if message["type"] == "http.response.body": + sending.set() + await drain.wait() + await send(message) + + await app(scope, receive, send_when_ready) + + def headers(): + return {"Authorization": "Bearer " + self._token(self._live())} + + async with ( + asyncio.timeout(2), + httpx.AsyncClient( + transport=httpx.ASGITransport(app=blocked_app), base_url="http://worker.test" + ) as slow, + httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://worker.test" + ) as peer, + ): + first = asyncio.create_task(slow.post("/v1/live", headers=headers())) + try: + await sending.wait() + refused = await peer.post("/v1/live", headers=headers()) + self.assertEqual( + (refused.status_code, refused.json()), (429, {"status": "overloaded"}) + ) + self.assertEqual(len(self.backend.calls), 1) + finally: + drain.set() + self.assertEqual((await first).status_code, 200) + self.assertEqual((await peer.post("/v1/live", headers=headers())).status_code, 200) + + async def test_partial_response_deadline_and_disconnect_release_the_slot(self) -> None: + for reason in ("deadline", "disconnect"): + with self.subTest(reason=reason): + await self._assert_partial_response_releases_slot(reason) + + async def _assert_partial_response_releases_slot(self, reason: str) -> None: + service = self._service(timeout=0.15 if reason == "deadline" else 3) + app = create_app(service) + sending = asyncio.Event() + disconnected = asyncio.Event() + cancelled = asyncio.Event() + frames = [] + + async def receive(): + await disconnected.wait() + return {"type": "http.disconnect"} + + async def send(message): + if message["type"] == "http.response.body": + sending.set() + try: + await asyncio.Future() + finally: + cancelled.set() + frames.append(message["type"]) + + scope = { + "type": "http", + "method": "POST", + "path": "/v1/live", + "query_string": b"", + "headers": [(b"authorization", ("Bearer " + self._token(self._live())).encode())], + } + async with asyncio.timeout(2): + response = asyncio.create_task(app(scope, receive, send)) + await sending.wait() + if reason == "disconnect": + disconnected.set() + await response + self.assertTrue(cancelled.is_set()) + self.assertEqual(frames, ["http.response.start"]) + self.assertIsNotNone((await service.execute(self._token(self._live()), "live")).document) + async def test_stalled_upstream_has_a_distinct_timeout(self) -> None: self.backend.release.clear() with self.assertRaisesRegex(ReadFailure, "^timeout$"): From a48b5426426d933d345399504bd7809758c220ce Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:17:45 +0000 Subject: [PATCH 23/31] Bound mapped discovery and finish malformed MCP replies Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 25 +- .../tests/test_mcp_discovery_bounds.py | 218 ++++++++++++++++++ 2 files changed, 235 insertions(+), 8 deletions(-) create mode 100644 source_worker/tests/test_mcp_discovery_bounds.py diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 114ce443c4..613e9a05ae 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -1026,7 +1026,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None: message_handler=self._message_handler, ) ) - result = await self._session.initialize() + result = await self._request(ClientSession.initialize) self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) await self._authorize() @@ -1068,7 +1068,10 @@ async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: self._leave_private() async def _message_handler(self, message: Any) -> None: - if isinstance(message, types.ServerNotification) and isinstance( + if isinstance(message, Exception): + assert self._transport is not None + self._transport.record_failure(MCPSourceError("protocol")) + elif isinstance(message, types.ServerNotification) and isinstance( message.root, types.ToolListChangedNotification ): self._tool_epoch += 1 @@ -1139,11 +1142,17 @@ async def _discover(self, session: ClientSession) -> MCPDiscovery: cursor: str | None = None seen: set[str] = set() if approved: - for _ in range(self._config.limits.max_pages): - result = await session.list_tools( - params=types.PaginatedRequestParams(cursor=cursor) + limits, policy = self._config.limits, self._config.data_policy + for _ in range(limits.max_pages): + params = types.PaginatedRequestParams(cursor=cursor) + reply = await session.send_request( + types.ClientRequest(types.ListToolsRequest(params=params)), + types.Result, ) - if len(result.tools) > self._config.limits.max_results: + data = reply.model_dump(by_alias=True, exclude_unset=True) + _bounded_data(data, limits.max_wire_bytes, policy) + result = types.ListToolsResult.model_validate(data) + if len(result.tools) > limits.max_results: raise MCPSourceError("limit") for tool in result.tools: if tool.name in seen: @@ -1153,9 +1162,9 @@ async def _discover(self, session: ClientSession) -> MCPDiscovery: continue for mapping in (self._config.search, self._config.read): if mapping is not None and mapping.name == tool.name: - _check_tool_schema(tool, mapping, self._config.data_policy) + _check_tool_schema(tool, mapping, policy) found.add(tool.name) - if len(seen) > self._config.limits.max_results: + if len(seen) > limits.max_results: raise MCPSourceError("limit") cursor = result.nextCursor if cursor is None: diff --git a/source_worker/tests/test_mcp_discovery_bounds.py b/source_worker/tests/test_mcp_discovery_bounds.py new file mode 100644 index 0000000000..e19eed3821 --- /dev/null +++ b/source_worker/tests/test_mcp_discovery_bounds.py @@ -0,0 +1,218 @@ +from __future__ import annotations + +import asyncio +import ipaddress +import json +import logging +from collections.abc import AsyncIterator +from typing import Any + +import httpx +import pytest +from loom_source_worker import mcp_client +from loom_source_worker.mcp_client import ( + MCPDataPolicy, + MCPLimits, + MCPSourceClient, + MCPSourceConfig, + MCPSourceError, + MCPToolMapping, +) + +_ENDPOINT = "https://source.example/mcp" +_DOCUMENT = "mcp://fixture/document" +_PRIVATE_MARKER = "synthetic-private-malformed-response" +_MALFORMED = b'{"result":"' + _PRIVATE_MARKER.encode() + b'",' +_INPUT_SCHEMA = {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]} +_OUTPUT_SCHEMA = {"type": "object"} +_APPROVED_TOOL = {"name": "read", "inputSchema": _INPUT_SCHEMA, "outputSchema": _OUTPUT_SCHEMA} +_UNAPPROVED_TOOL = {"name": "other", "inputSchema": {"type": "object"}} + + +class _Body(httpx.AsyncByteStream): + def __init__(self, content: bytes) -> None: + self.content = content + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield self.content + + +class _Source(httpx.MockTransport): + def __init__(self) -> None: + super().__init__(self.respond) + self.methods: list[str] = [] + self.cursors: list[str | None] = [] + self.pages: dict[str | None, dict[str, Any]] = {} + self.malformed_method: str | None = None + self.malformed_body = _MALFORMED + self.closed = False + + async def aclose(self) -> None: + self.closed = True + + async def respond(self, request: httpx.Request) -> httpx.Response: + assert request.method == "POST" + message = json.loads(request.content) + method = message["method"] + self.methods.append(method) + if method == self.malformed_method: + body = self.malformed_body + elif method == "notifications/initialized": + return httpx.Response(202, stream=_Body(b"")) + else: + if method == "initialize": + result = { + "protocolVersion": message["params"]["protocolVersion"], + "capabilities": {"resources": {}, "tools": {}}, + "serverInfo": {"name": "fixture", "version": "1"}, + } + elif method == "tools/list": + cursor = message.get("params", {}).get("cursor") + self.cursors.append(cursor) + result = self.pages[cursor] + else: + pytest.fail(f"unexpected fixture method: {method}") + reply = {"jsonrpc": "2.0", "id": message["id"], "result": result} + body = json.dumps(reply).encode() + return httpx.Response(200, headers={"content-type": "application/json"}, stream=_Body(body)) + + +@pytest.fixture(autouse=True) +def _pin(monkeypatch: pytest.MonkeyPatch) -> None: + async def resolve(host: str) -> ipaddress.IPv6Address: + assert host == "source.example" + return ipaddress.IPv6Address("2600::10") + + monkeypatch.setattr(mcp_client, "resolve_public_address", resolve) + + +async def _authorized() -> None: + return None + + +def _mapped_client(source: _Source, policy: MCPDataPolicy) -> MCPSourceClient: + config = MCPSourceConfig( + _ENDPOINT, + approved_tools=("read",), + read=MCPToolMapping("read", _INPUT_SCHEMA, _OUTPUT_SCHEMA, "id"), + data_policy=policy, + ) + return MCPSourceClient(config, None, validate_access=_authorized, _transport=source) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("location", "fields", "policy"), + [ + ("approved", {"description": "é" * 17}, MCPDataPolicy(max_string_bytes=32)), + ("approved", {"_meta": {"labels": [1, 2, 3]}}, MCPDataPolicy(max_items=2)), + ("approved", {"extension": list(range(64))}, MCPDataPolicy(max_nodes=48)), + ("page", {"_meta": {"extension": "é" * 17}}, MCPDataPolicy(max_string_bytes=32)), + ("page", {"extension": list(range(64))}, MCPDataPolicy(max_nodes=48)), + ( + "unapproved", + {"outputSchema": {"type": "object", "examples": [[[[[True]]]]]}}, + MCPDataPolicy(max_depth=7), + ), + ], +) +async def test_discovery_bounds_complete_page_before_filtering( + location: str, fields: dict[str, Any], policy: MCPDataPolicy +) -> None: + source = _Source() + page: dict[str, Any] = {"tools": [_APPROVED_TOOL]} + if location == "page": + page.update(fields) + elif location == "approved": + page["tools"] = [{**_APPROVED_TOOL, **fields}] + else: + page["tools"].append({**_UNAPPROVED_TOOL, **fields}) + source.pages[None] = page + + async with _mapped_client(source, policy) as client: + with pytest.raises(MCPSourceError, match="^MCP source limit$"): + await client.discover() + + assert source.cursors == [None] + assert source.closed + + +@pytest.mark.asyncio +async def test_bounded_discovery_pages_without_the_sdk_caching_helper( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def refuse_helper(*args: Any, **kwargs: Any) -> None: + pytest.fail("the SDK listing helper caches provider schemas before policy validation") + + monkeypatch.setattr(mcp_client.ClientSession, "list_tools", refuse_helper) + source = _Source() + source.pages = { + None: { + "tools": [{**_UNAPPROVED_TOOL, "outputSchema": {"not": {"type": "number"}}}], + "nextCursor": "next", + "_meta": {"note": "bounded"}, + }, + "next": {"tools": [{**_APPROVED_TOOL, "description": "bounded"}]}, + } + async with _mapped_client(source, MCPDataPolicy(max_depth=7)) as client: + assert (await client.discover()).tools == ("read",) + + assert source.cursors == [None, "next"] + assert source.closed + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["initialize", "resources/read"]) +@pytest.mark.parametrize("revoked_on_close", [False, True]) +async def test_malformed_json_finishes_rpc_and_rechecks_access_after_sdk_close( + method: str, revoked_on_close: bool, caplog: pytest.LogCaptureFixture +) -> None: + caplog.set_level(logging.DEBUG) + source = _Source() + source.malformed_method = method + checked_after_close = False + + async def validate_access() -> None: + nonlocal checked_after_close + if source.closed: + checked_after_close = True + if revoked_on_close: + raise MCPSourceError("denied") + + config = MCPSourceConfig( + _ENDPOINT, + limits=MCPLimits(timeout_seconds=20, request_seconds=15), + approved_resource_ids=(_DOCUMENT,), + ) + client = MCPSourceClient(config, None, validate_access=validate_access, _transport=source) + code = "denied" if revoked_on_close else "protocol" + with pytest.raises(MCPSourceError, match=f"^MCP source {code}$"): + async with asyncio.timeout(3), client: + assert method == "resources/read" + await client.read(_DOCUMENT) + + assert source.methods == ( + ["initialize"] + if method == "initialize" + else ["initialize", "notifications/initialized", "resources/read"] + ) + assert source.closed and checked_after_close + assert _PRIVATE_MARKER not in caplog.text + + +@pytest.mark.asyncio +async def test_malformed_reply_cannot_replace_existing_wire_limit() -> None: + source = _Source() + source.malformed_method = "initialize" + source.malformed_body = _MALFORMED + b" " * 1024 + config = MCPSourceConfig(_ENDPOINT, limits=MCPLimits(max_wire_bytes=1024)) + + with pytest.raises(MCPSourceError, match="^MCP source limit$"): + async with ( + asyncio.timeout(3), + MCPSourceClient(config, None, validate_access=_authorized, _transport=source), + ): + pytest.fail("a wire limit refusal opened a client session") + + assert source.methods == ["initialize"] + assert source.closed From 0c55b8b5c4ec746f9d17777d8caaa6cc3233819b Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:18:50 +0000 Subject: [PATCH 24/31] Bound worker payload bytes across admitted reads Signed-off-by: zlareb1 --- source_worker/README.md | 10 ++++++++- source_worker/loom_source_worker/main.py | 6 +++++ .../loom_source_worker/read_service.py | 3 +++ source_worker/tests/test_main.py | 22 ++++++++++++++++++- 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/source_worker/README.md b/source_worker/README.md index 535c560324..f1ee0b3414 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -50,6 +50,13 @@ Keep the signer and worker profile digest in agreement. Any account, profile, selection or authority change requires a current grant. An access check returns a content digest and fetch time without the body. +Read slots stay occupied until the worker sends the response, the deadline +expires, or the request disconnects. Startup rejects configurations where +`concurrent × content_bytes` exceeds 8 MiB, or `concurrent × max_wire_bytes` +for any profile exceeds 16 MiB. These limits account for admitted document +and wire bytes. They do not measure process memory or qualify infrastructure +buffering. Set smaller limits for the intended MCP server and deployment. + A grant is reusable until its expiry for the same read, within the worker's capacity limits. It never authorizes a stored write. The issuer must check selection and requester authority before issuing it and before delivering a @@ -85,7 +92,8 @@ Save the worker configuration as `config.json`: "link_origins": ["https://docs.example"], "config": { "endpoint": "https://mcp.example/rpc", - "bearer_audience": "https://mcp.example/rpc" + "bearer_audience": "https://mcp.example/rpc", + "limits": { "max_wire_bytes": 2000000 } } } ] diff --git a/source_worker/loom_source_worker/main.py b/source_worker/loom_source_worker/main.py index cb7dec3e58..ea4c3c4f22 100644 --- a/source_worker/loom_source_worker/main.py +++ b/source_worker/loom_source_worker/main.py @@ -47,6 +47,7 @@ _VAULT_TOKEN = Path("/run/loom-source-worker/credentials/vault-token") _SOCKET = Path("/run/loom-source-worker/socket/worker.sock") _CONFIG_BYTES = 2 * 1024 * 1024 +_MAX_ADMITTED_WIRE_BYTES = 16 * 1024 * 1024 _TOKEN_BYTES = 8192 _BACKLOG = 64 _CERTIFICATE = rb"-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+-----END CERTIFICATE-----" @@ -152,6 +153,11 @@ def _parse_settings(raw: bytes) -> _Settings: or not all(_https_origin(origin) for origin in profile.link_origins) ): raise ValueError("invalid profile scope") + if ( + settings.read_limits.concurrent * profile.config.limits.max_wire_bytes + > _MAX_ADMITTED_WIRE_BYTES + ): + raise ValueError("worker wire budget exceeded") audience = profile.config.bearer_audience if audience is not None and not _visible_ascii(audience, 2048): raise ValueError("invalid profile audience") diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index ac997e0e0e..54cdae3035 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -19,6 +19,8 @@ FailureCode = Literal["denied", "reconnect", "overloaded", "timeout", "unavailable", "unsupported"] CurrentAccess = Callable[[], Awaitable[None]] +_MAX_ADMITTED_CONTENT_BYTES = 8 * 1024 * 1024 + class ReadFailure(Exception): def __init__(self, code: FailureCode) -> None: @@ -73,6 +75,7 @@ def __post_init__(self) -> None: or not 1 <= self.concurrent_per_org <= self.concurrent <= 256 or type(self.content_bytes) is not int or not 1 <= self.content_bytes <= 4_000_000 + or self.concurrent * self.content_bytes > _MAX_ADMITTED_CONTENT_BYTES or type(self.timeout_seconds) not in (float, int) or not math.isfinite(self.timeout_seconds) or not 0 < self.timeout_seconds <= 30 diff --git a/source_worker/tests/test_main.py b/source_worker/tests/test_main.py index e2c99c76ff..a382c95b8b 100644 --- a/source_worker/tests/test_main.py +++ b/source_worker/tests/test_main.py @@ -42,7 +42,10 @@ def config(): { "organizations": ["tenant"], "link_origins": ["https://docs.example"], - "config": {"endpoint": "https://mcp.example/rpc"}, + "config": { + "endpoint": "https://mcp.example/rpc", + "limits": {"max_wire_bytes": 2_000_000}, + }, } ], } @@ -67,6 +70,23 @@ def test_resource_profile_and_transport_settings(config): assert not transport.proxy_headers +@pytest.mark.parametrize("limit", ["content", "wire"]) +def test_refuses_slot_limits_above_the_worker_byte_budget(config, limit): + settings = config["read_limits"] + profile = config["profiles"][0]["config"] + if limit == "content": + settings["content_bytes"] = 1024 * 1024 + else: + profile["limits"]["max_wire_bytes"] = 2 * 1024 * 1024 + _parse_settings(json.dumps(config).encode()) + if limit == "content": + settings["content_bytes"] += 1 + else: + profile["limits"]["max_wire_bytes"] += 1 + with pytest.raises(StartupError, match="^invalid worker configuration$"): + _parse_settings(json.dumps(config).encode()) + + def test_mapped_read_profile_is_validated_at_startup(config): source = config["profiles"][0]["config"] source.update( From be5c5e6579847c2afc24bbe49d55fb4f1a368167 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:19:07 +0000 Subject: [PATCH 25/31] Qualify the installed worker over owned TLS sockets Signed-off-by: zlareb1 --- .github/workflows/mcp-source-worker.yml | 11 + source_worker/qualification/test_real_tls.py | 484 +++++++++++++++++++ 2 files changed, 495 insertions(+) create mode 100644 source_worker/qualification/test_real_tls.py diff --git a/.github/workflows/mcp-source-worker.yml b/.github/workflows/mcp-source-worker.yml index b47a6e9385..425c4ecc07 100644 --- a/.github/workflows/mcp-source-worker.yml +++ b/.github/workflows/mcp-source-worker.yml @@ -42,3 +42,14 @@ jobs: run: | git rev-parse HEAD "$RUNNER_TEMP/source-worker/bin/python" -m pytest -q source_worker/tests + - name: Verify the installed worker over owned TLS sockets + if: runner.environment == 'github-hosted' + timeout-minutes: 2 + env: + QUALIFICATION_SHA: ${{ github.event.pull_request.head.sha }} + LOOM_SOURCE_WORKER_REAL_TLS: "1" + run: | + test "$GITHUB_ACTIONS" = true + test "$RUNNER_ENVIRONMENT" = github-hosted + test "$(git rev-parse HEAD)" = "$QUALIFICATION_SHA" + "$RUNNER_TEMP/source-worker/bin/python" -I -m pytest -q source_worker/qualification/test_real_tls.py diff --git a/source_worker/qualification/test_real_tls.py b/source_worker/qualification/test_real_tls.py new file mode 100644 index 0000000000..7acd389836 --- /dev/null +++ b/source_worker/qualification/test_real_tls.py @@ -0,0 +1,484 @@ +"""The installed worker and official MCP SDK over an owned loopback TLS listener.""" + +from __future__ import annotations + +import asyncio +import hashlib +import ipaddress +import json +import os +import socket +import ssl +import time +from collections.abc import AsyncIterator, Iterator +from contextlib import AsyncExitStack, asynccontextmanager, contextmanager +from dataclasses import dataclass, field +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any +from uuid import UUID, uuid4 + +import certifi +import pytest +import uvicorn +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from loom_source_worker import mcp_client +from loom_source_worker.credential_store import CredentialRecord +from loom_source_worker.direct_backend import ApprovedProfile, DirectBackend +from loom_source_worker.mcp_client import ( + MCPBearer, + MCPSourceClient, + MCPSourceConfig, + MCPSourceError, + MCPToolMapping, +) +from loom_source_worker.protocol import ConnectionBinding, ReadBinding, ReadGrant, issue_read_grant +from loom_source_worker.read_service import ReadFailure, ReadLimits, ReadService +from mcp import types +from mcp.server import Server +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from pydantic import AnyUrl, SecretStr +from starlette.requests import Request +from starlette.responses import Response +from starlette.types import Message, Receive, Scope, Send + +pytestmark = [ + pytest.mark.asyncio, + pytest.mark.skipif( + os.environ.get("LOOM_SOURCE_WORKER_REAL_TLS") != "1" + or os.environ.get("GITHUB_ACTIONS") != "true" + or os.environ.get("RUNNER_ENVIRONMENT") != "github-hosted", + reason="requires the installed-worker GitHub-hosted TLS step", + ), +] + +_HOST = "mcp-worker.invalid" +_WRONG_HOST = "other-worker.invalid" +_LOOPBACK = "127.0.0.1" +_ACCOUNTS = ("alice", "bob") +_REFUSALS = {"expired": 401, "forbidden": 403} + + +def _schema(*fields: str) -> dict[str, Any]: + return { + "type": "object", + "properties": {name: {"type": "string"} for name in fields}, + "required": list(fields), + "additionalProperties": False, + } + + +def _identity(account: str) -> str: + return f"urn:fixture:tls:{account}" + + +def _text(mode: str, account: str) -> str: + return f"{mode}: synthetic content for {account}" + + +def _sdk_server(mode: str, account: str) -> StreamableHTTPSessionManager: + sdk: Server[Any, Any] = Server(f"fixture-{mode}-{account}") + identity = _identity(account) + if mode == "resource": + + @sdk.list_resources() + async def list_resources() -> list[types.Resource]: + return [types.Resource(uri=AnyUrl(identity), name=account)] + + @sdk.read_resource() + async def read_resource(uri: AnyUrl) -> str: + assert str(uri) == identity + return _text(mode, account) + + else: + + @sdk.list_tools() + async def list_tools() -> list[types.Tool]: + return [ + types.Tool( + name="read", + inputSchema=_schema("id"), + outputSchema=_schema("id", "title", "uri", "text"), + ) + ] + + @sdk.call_tool() + async def call_tool(name: str, arguments: dict[str, Any]) -> dict[str, str]: + assert name == "read" and arguments == {"id": identity} + return {"id": identity, "title": account, "uri": identity, "text": _text(mode, account)} + + return StreamableHTTPSessionManager(app=sdk, json_response=mode == "mapped", stateless=False) + + +def _certificates(tmp_path: Path) -> tuple[Path, Path, bytes]: + ca_key = ec.generate_private_key(ec.SECP256R1()) + leaf_key = ec.generate_private_key(ec.SECP256R1()) + ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Worker fixture root")]) + leaf_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, _HOST)]) + now = datetime.now(UTC) + + def builder(name: x509.Name, key: ec.EllipticCurvePrivateKey) -> x509.CertificateBuilder: + return ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(ca_name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)) + .not_valid_after(now + timedelta(hours=1)) + ) + + ca = ( + builder(ca_name, ca_key) + .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) + .add_extension( + x509.KeyUsage( + digital_signature=False, + content_commitment=False, + key_encipherment=False, + data_encipherment=False, + key_agreement=False, + key_cert_sign=True, + crl_sign=True, + encipher_only=False, + decipher_only=False, + ), + critical=True, + ) + .add_extension( + x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()), critical=False + ) + .sign(ca_key, hashes.SHA256()) + ) + leaf = ( + builder(leaf_name, leaf_key) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension(x509.SubjectAlternativeName([x509.DNSName(_HOST)]), critical=False) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False) + .add_extension( + x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False + ) + .sign(ca_key, hashes.SHA256()) + ) + cert_path, key_path = tmp_path / "leaf.pem", tmp_path / "leaf.key" + cert_path.write_bytes(leaf.public_bytes(serialization.Encoding.PEM)) + with os.fdopen(os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as key: + key.write( + leaf_key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + return cert_path, key_path, ca.public_bytes(serialization.Encoding.PEM) + + +@contextmanager +def _trust_fixture_ca( + tmp_path: Path, root: bytes, monkeypatch: pytest.MonkeyPatch +) -> Iterator[None]: + original = ssl.SSLContext.load_verify_locations + bundle = Path(certifi.where()) + combined = tmp_path / "fixture-ca-bundle.pem" + combined.write_bytes(bundle.read_bytes() + b"\n" + root) + + def load_locations( + context: ssl.SSLContext, + cafile: str | os.PathLike[str] | None = None, + capath: str | os.PathLike[str] | None = None, + cadata: str | bytes | None = None, + ) -> None: + if cafile is not None and Path(cafile) == bundle: + cafile = str(combined) + original(context, cafile=cafile, capath=capath, cadata=cadata) + + with monkeypatch.context() as scoped: + scoped.setattr(ssl.SSLContext, "load_verify_locations", load_locations) + yield + + +class _FixtureServer(uvicorn.Server): + @contextmanager + def capture_signals(self) -> Iterator[None]: + yield + + +@dataclass +class _Fixture: + port: int + root: bytes + sni: list[str | None] = field(default_factory=list) + requests: list[tuple[str, str]] = field(default_factory=list) + sessions: dict[str, str] = field(default_factory=dict) + terminations: list[tuple[str, str, int]] = field(default_factory=list) + refusals: list[tuple[str, int]] = field(default_factory=list) + stalled: asyncio.Event = field(default_factory=asyncio.Event) + disconnected: asyncio.Event = field(default_factory=asyncio.Event) + + def endpoint(self, host: str = _HOST) -> str: + return f"https://{host}:{self.port}/mcp" + + +@asynccontextmanager +async def _service( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str = "resource" +) -> AsyncIterator[_Fixture]: + cert, key, root = _certificates(tmp_path) + managers = {account: _sdk_server(mode, account) for account in _ACCOUNTS} + with ( + socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener, + monkeypatch.context() as scoped, + ): + listener.bind((_LOOPBACK, 0)) + fixture = _Fixture(listener.getsockname()[1], root) + + async def fixture_pin(host: str) -> ipaddress.IPv4Address: + assert host in {_HOST, _WRONG_HOST} + return ipaddress.IPv4Address(_LOOPBACK) + + scoped.setattr(mcp_client, "resolve_public_address", fixture_pin) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + request = Request(scope, receive) + assert request.url.scheme == "https" and request.url.path == "/mcp" + assert scope["server"] == (_LOOPBACK, fixture.port) + assert request.headers["host"] == f"{_HOST}:{fixture.port}" + bearer = request.headers["authorization"] + prefix = "Bearer fixture-" + assert bearer.startswith(prefix) + account = bearer.removeprefix(prefix) + fixture.requests.append((account, request.method)) + if account in _REFUSALS: + status = _REFUSALS[account] + fixture.refusals.append((account, status)) + await Response(status_code=status)(scope, receive, send) + return + if account == "stall": + assert request.method == "POST" + assert json.loads(await request.body())["method"] == "initialize" + fixture.stalled.set() + assert (await receive())["type"] == "http.disconnect" + fixture.disconnected.set() + return + + async def observe(message: Message) -> None: + if message["type"] == "http.response.start": + session = request.headers.get("mcp-session-id") + if request.method == "DELETE": + assert session + fixture.terminations.append((account, session, message["status"])) + elif request.method == "POST" and session is None: + assigned = dict(message["headers"]).get(b"mcp-session-id") + if assigned: + fixture.sessions[account] = assigned.decode("ascii") + await send(message) + + await managers[account].handle_request(scope, receive, observe) + + config = uvicorn.Config( + app, + ssl_certfile=str(cert), + ssl_keyfile=str(key), + http="h11", + lifespan="off", + log_config=None, + access_log=False, + proxy_headers=False, + timeout_graceful_shutdown=3, + ) + config.load() + assert config.ssl is not None + + def record_sni(_connection: Any, name: str | None, _context: ssl.SSLContext) -> None: + fixture.sni.append(name) + + config.ssl.set_servername_callback(record_sni) + server = _FixtureServer(config) + async with AsyncExitStack() as stack: + for manager in managers.values(): + await stack.enter_async_context(manager.run()) + task = asyncio.create_task(server.serve(sockets=[listener])) + try: + async with asyncio.timeout(10): + while not server.started: + if task.done(): + task.result() + pytest.fail("TLS listener exited before startup") + await asyncio.sleep(0.01) + yield fixture + finally: + server.should_exit = True + async with asyncio.timeout(5): + await task + + +@dataclass +class _Accounts: + records: dict[UUID, CredentialRecord] = field(default_factory=dict) + + async def get(self, connection_id: UUID) -> CredentialRecord: + return self.records[connection_id] + + +def _bind_account( + worker_id: UUID, profile: ApprovedProfile, accounts: _Accounts, account: str +) -> ReadBinding: + binding = ReadBinding( + worker_id=worker_id, + org="fixture-org", + namespace="fixture-team", + source_id=uuid4(), + selection_generation=1, + requester=account, + connection_id=uuid4(), + connection_generation=1, + profile_digest=profile.digest, + resource_id=_identity(account), + ) + accounts.records[binding.connection_id] = CredentialRecord( + binding=ConnectionBinding( + worker_id=worker_id, + org=binding.org, + owner=account, + connection_id=binding.connection_id, + generation=1, + profile_digest=profile.digest, + ), + state="active", + auth="bearer", + audience=profile.config.bearer_audience, + token=SecretStr(f"fixture-{account}"), + expires_at=int(time.time()) + 60, + ) + return binding + + +@pytest.mark.parametrize("mode", ["resource", "mapped"]) +async def test_signed_exact_reads_over_tls( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + async with _service(tmp_path, monkeypatch, mode) as fixture: + with _trust_fixture_ca(tmp_path, fixture.root, monkeypatch): + endpoint = fixture.endpoint() + mapping = ( + MCPToolMapping("read", _schema("id"), _schema("id", "title", "uri", "text"), "id") + if mode == "mapped" + else None + ) + profile = ApprovedProfile( + MCPSourceConfig( + endpoint, + bearer_audience=endpoint, + approved_tools=("read",) if mapping else (), + read=mapping, + ), + ("fixture-org",), + ) + worker_id = uuid4() + accounts = _Accounts() + bindings = [_bind_account(worker_id, profile, accounts, name) for name in _ACCOUNTS] + key = Ed25519PrivateKey.generate() + service = ReadService( + worker_id=worker_id, + issuer="fixture-issuer", + verifier=key.public_key(), + backend=DirectBackend(accounts, (profile,)), + limits=ReadLimits( + concurrent=2, concurrent_per_org=2, timeout_seconds=10, content_bytes=2048 + ), + ) + + def sign(binding: ReadBinding) -> tuple[str, UUID]: + grant = ReadGrant(request_id=uuid4(), operation="live", binding=binding) + token = issue_read_grant( + grant, issuer="fixture-issuer", key=key, lifetime_seconds=20 + ) + return token, grant.request_id + + wrong_owner = bindings[0].model_copy(update={"requester": "bob"}) + token, _ = sign(wrong_owner) + with pytest.raises(ReadFailure, match="^denied$"): + await service.execute(token, "live") + assert not fixture.requests + + for binding in bindings: + token, request_id = sign(binding) + result = await service.execute(token, "live") + assert result.request_id == request_id + assert result.document is not None + assert result.document.resource_id == binding.resource_id + expected = _text(mode, binding.requester) + assert result.document.text == expected + assert result.content_sha256 == hashlib.sha256(expected.encode()).hexdigest() + + assert set(fixture.sessions) == set(_ACCOUNTS) + assert len(set(fixture.sessions.values())) == len(_ACCOUNTS) + assert fixture.terminations == [(name, fixture.sessions[name], 200) for name in _ACCOUNTS] + assert fixture.sni and set(fixture.sni) == {_HOST} + + +async def _current() -> None: + return None + + +def _client(endpoint: str, account: str, *, deadline: float | None = None) -> MCPSourceClient: + return MCPSourceClient( + MCPSourceConfig(endpoint, bearer_audience=endpoint), + MCPBearer(f"fixture-{account}", endpoint), + validate_access=_current, + deadline=deadline, + ) + + +async def test_ca_and_hostname_verification( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + async with _service(tmp_path, monkeypatch) as fixture: + with pytest.raises(MCPSourceError, match="^MCP source protocol$"): + async with _client(fixture.endpoint(), "alice"): + pytest.fail("untrusted fixture CA was accepted") + assert fixture.sni == [_HOST] + assert not fixture.requests + with _trust_fixture_ca(tmp_path, fixture.root, monkeypatch): + with pytest.raises(MCPSourceError, match="^MCP source protocol$"): + async with _client(fixture.endpoint(_WRONG_HOST), "alice"): + pytest.fail("certificate for a different hostname was accepted") + assert fixture.sni == [_HOST, _WRONG_HOST] + assert not fixture.requests + async with _client(fixture.endpoint(), "alice"): + assert fixture.sessions["alice"] + assert fixture.terminations == [("alice", fixture.sessions["alice"], 200)] + + +@pytest.mark.parametrize( + ("account", "status", "code"), [("expired", 401, "reconnect"), ("forbidden", 403, "denied")] +) +async def test_tls_http_refusal( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, account: str, status: int, code: str +) -> None: + async with _service(tmp_path, monkeypatch) as fixture: + with _trust_fixture_ca(tmp_path, fixture.root, monkeypatch): + with pytest.raises(MCPSourceError, match=f"^MCP source {code}$"): + async with _client(fixture.endpoint(), account): + pytest.fail("HTTP refusal opened a session") + assert fixture.refusals == [(account, status)] + assert fixture.requests == [(account, "POST")] + assert not fixture.sessions + + +async def test_deadline_closes_tls_socket(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + async with _service(tmp_path, monkeypatch) as fixture: + with _trust_fixture_ca(tmp_path, fixture.root, monkeypatch): + deadline = asyncio.get_running_loop().time() + 4 + async with asyncio.timeout(12): + with pytest.raises(MCPSourceError, match="^MCP source timeout$"): + async with _client(fixture.endpoint(), "stall", deadline=deadline): + pytest.fail("stalled initialize opened a session") + assert fixture.stalled.is_set() + await fixture.disconnected.wait() + assert fixture.requests == [("stall", "POST")] + assert not fixture.sessions From 74cbd234d246c2320e473260443129b493747e91 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:20:28 +0000 Subject: [PATCH 26/31] Keep the profile digest fixture within the worker budget Signed-off-by: zlareb1 --- source_worker/tests/test_mcp_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index eacadc683a..f7009ef85c 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -44,7 +44,7 @@ def test_equivalent_effective_deadlines_share_one_approved_profile_digest() -> N "issuer": "synthetic-grants", "vault": {"origin": "https://vault.example", "mount": "connections"}, "read_limits": { - "concurrent": 8, + "concurrent": 4, "concurrent_per_org": 2, "timeout_seconds": 5, "content_bytes": 4096, From 7c547c9481d8273511c872da086bc92a0395f982 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:22:00 +0000 Subject: [PATCH 27/31] Expect the fixed unavailable status for TLS failures Signed-off-by: zlareb1 --- source_worker/qualification/test_real_tls.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source_worker/qualification/test_real_tls.py b/source_worker/qualification/test_real_tls.py index 7acd389836..0779816158 100644 --- a/source_worker/qualification/test_real_tls.py +++ b/source_worker/qualification/test_real_tls.py @@ -438,13 +438,13 @@ async def test_ca_and_hostname_verification( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: async with _service(tmp_path, monkeypatch) as fixture: - with pytest.raises(MCPSourceError, match="^MCP source protocol$"): + with pytest.raises(MCPSourceError, match="^MCP source unavailable$"): async with _client(fixture.endpoint(), "alice"): pytest.fail("untrusted fixture CA was accepted") assert fixture.sni == [_HOST] assert not fixture.requests with _trust_fixture_ca(tmp_path, fixture.root, monkeypatch): - with pytest.raises(MCPSourceError, match="^MCP source protocol$"): + with pytest.raises(MCPSourceError, match="^MCP source unavailable$"): async with _client(fixture.endpoint(_WRONG_HOST), "alice"): pytest.fail("certificate for a different hostname was accepted") assert fixture.sni == [_HOST, _WRONG_HOST] From 73f233699bfb04aaa697846958d0bedd877250a6 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:39:48 +0000 Subject: [PATCH 28/31] Reject expired MCP results before sending the document Response rendering can finish after the read deadline without yielding. Check the cutoff again before the first frame. Distinguish a DNS outage or timeout from address policy refusal, and document the listener overload response. Signed-off-by: zlareb1 --- source_worker/README.md | 23 ++++--- .../loom_source_worker/_mcp_transport.py | 18 +++-- .../loom_source_worker/http_service.py | 7 +- .../loom_source_worker/mcp_client.py | 4 +- .../loom_source_worker/read_service.py | 9 +-- source_worker/tests/test_protocol_servers.py | 49 +++++++++++-- source_worker/tests/test_read_service.py | 68 +++++++++++++++++++ 7 files changed, 153 insertions(+), 25 deletions(-) diff --git a/source_worker/README.md b/source_worker/README.md index f1ee0b3414..b53fff6fb5 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -169,14 +169,21 @@ lifetime_seconds=10)` on the issuer. Mount only the corresponding public key in the worker. Send the resulting grant as the authorization bearer on the matching route. For `/v1/check-access`, use operation `check_access`. -The worker returns `200` with `ok` on success, `403` for `denied`, `409` for -`reconnect`, `422` for `unsupported`, `429` for `overloaded`, `503` for -`unavailable`, and `504` for `timeout`. Connection errors, upstream 5xx and an -expired stateful MCP session return `unavailable`. Any retry needs current -authority and a new session; the worker does not retry inside the failed read. -The worker handler refuses a body or query with `400`. The TLS proxy rejects -query strings and other request targets outside the two routes with `404`, and -may return `413` when a body exceeds the proxy's limit. +The read handler returns JSON: `200` with `ok` on success, `403` for `denied`, +`409` for `reconnect`, `422` for `unsupported`, `429` for `overloaded`, `503` for +`unavailable`, and `504` for `timeout`. DNS resolver outages, connection +errors, upstream 5xx and an expired stateful MCP session return `unavailable`. +DNS timeouts return `timeout`; prohibited addresses return `denied`. Any retry +needs current authority and a new session; the worker does not retry inside +the failed read. The handler refuses a body or query with `400`. + +The handler's `429 overloaded` means no read slot is available. The listener +enforces a separate connection and task limit before the handler runs. When +that limit is reached, the listener returns a plain-text `503` that the TLS +proxy passes through. Callers must handle that `503` without expecting the +worker's JSON envelope. The TLS proxy rejects query strings and other request +targets outside the two routes with `404`, and may return `413` when a body +exceeds the proxy's limit. ## Docker Compose diff --git a/source_worker/loom_source_worker/_mcp_transport.py b/source_worker/loom_source_worker/_mcp_transport.py index 96b5dd9dd0..e928070cda 100644 --- a/source_worker/loom_source_worker/_mcp_transport.py +++ b/source_worker/loom_source_worker/_mcp_transport.py @@ -8,15 +8,23 @@ from collections.abc import Iterator from contextlib import contextmanager from contextvars import ContextVar +from typing import Literal import dns.asyncresolver import dns.exception +import dns.resolver _PRIVATE = ContextVar("mcp_private_work", default=False) _NAT64 = ipaddress.IPv6Network("64:ff9b::/96") _Address = ipaddress.IPv4Address | ipaddress.IPv6Address +class AddressResolutionError(Exception): + def __init__(self, code: Literal["unavailable", "timeout"]) -> None: + super().__init__(code) + self.code = code + + class _PrivateFilter(logging.Filter): def filter(self, record: logging.LogRecord) -> bool: return not _PRIVATE.get() @@ -70,11 +78,13 @@ async def resolve_public_address(host: str) -> _Address | None: return_exceptions=True, ) for answer in answers: - if isinstance(answer, asyncio.CancelledError): - raise answer if isinstance(answer, BaseException): - return None + raise answer addresses.extend(ipaddress.ip_address(record.to_text()) for record in answer) - except (ValueError, OSError, dns.exception.DNSException): + except (ValueError, dns.resolver.NXDOMAIN): return None + except (dns.exception.Timeout, TimeoutError): + raise AddressResolutionError("timeout") from None + except (dns.exception.DNSException, OSError): + raise AddressResolutionError("unavailable") from None return addresses[0] if addresses and all(map(_is_public, addresses)) else None diff --git a/source_worker/loom_source_worker/http_service.py b/source_worker/loom_source_worker/http_service.py index 4ef0c0ec6e..2cb56f7684 100644 --- a/source_worker/loom_source_worker/http_service.py +++ b/source_worker/loom_source_worker/http_service.py @@ -74,7 +74,7 @@ async def emit(message: Message) -> None: await send(message) try: - async with self.service.admitted_read(token, self.operation) as reading: + async with self.service.admitted_read(token, self.operation) as (reading, deadline): body = { "status": "ok", "request_id": str(reading.request_id), @@ -82,7 +82,10 @@ async def emit(message: Message) -> None: "content_sha256": reading.content_sha256, "document": asdict(reading.document) if reading.document else None, } - await JSONResponse(body, headers=_CACHE_HEADERS)(scope, receive, emit) + response = JSONResponse(body, headers=_CACHE_HEADERS) + if asyncio.get_running_loop().time() >= deadline: + raise ReadFailure("timeout") + await response(scope, receive, emit) except ReadFailure as error: if not started: await _error(error.code, _STATUSES[error.code])(scope, receive, send) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 613e9a05ae..9ebfd81f8f 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -28,7 +28,7 @@ from referencing import Registry from referencing.exceptions import Unresolvable -from ._mcp_transport import private_work, resolve_public_address +from ._mcp_transport import AddressResolutionError, private_work, resolve_public_address ErrorCode = Literal[ "config", @@ -68,7 +68,7 @@ def __init__(self, code: ErrorCode) -> None: def _error_code(error: BaseException) -> ErrorCode: - if isinstance(error, MCPSourceError): + if isinstance(error, (AddressResolutionError, MCPSourceError)): return error.code if isinstance(error, (TimeoutError, httpx.TimeoutException)): return "timeout" diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index 54cdae3035..ee2c912146 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -119,14 +119,14 @@ async def _slot(self, org: str) -> AsyncIterator[None]: del self._by_org[org] async def execute(self, token: str, operation: Literal["live", "check_access"]) -> ReadResult: - async with self.admitted_read(token, operation) as result: + async with self.admitted_read(token, operation) as (result, _): return result @asynccontextmanager async def admitted_read( self, token: str, operation: Literal["live", "check_access"] - ) -> AsyncIterator[ReadResult]: - """Keep capacity and the deadline until the consumer finishes sending.""" + ) -> AsyncIterator[tuple[ReadResult, float]]: + """Yield the result and its monotonic deadline, keeping the slot through delivery.""" try: grant, expires_at = verify_read_grant( token, issuer=self._issuer, worker_id=self._worker_id, key=self._verifier @@ -164,12 +164,13 @@ async def require_current() -> None: await require_current() raise await require_current() - yield ReadResult( + result = ReadResult( grant.request_id, fetched_at, content_sha256, document if operation == "live" else None, ) + yield result, deadline except TimeoutError: raise ReadFailure("timeout") from None except ReadGrantRefused: diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index cfdca2936f..4b5138282e 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -11,6 +11,9 @@ from typing import Any from uuid import UUID, uuid4 +import dns.asyncresolver +import dns.rdata +import dns.resolver import httpx import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey @@ -390,19 +393,52 @@ def client_for(token: str, selected: str) -> mcp_client.MCPSourceClient: ("route", "operation"), [("live", "live"), ("check-access", "check_access")] ) @pytest.mark.parametrize( - ("fault", "status"), - [("network", 503), ("upstream-503", 503), ("expired-session", 503), ("missing-endpoint", 422)], + ("fault", "status", "code"), + [ + ("network", 503, "unavailable"), + ("upstream-503", 503, "unavailable"), + ("expired-session", 503, "unavailable"), + ("missing-endpoint", 422, "unsupported"), + ("dns-unavailable", 503, "unavailable"), + ("dns-timeout", 504, "timeout"), + ("dns-prohibited", 403, "denied"), + ], ) async def test_signed_route_distinguishes_transport_failure_from_unsupported( - route: str, operation: str, fault: str, status: int, monkeypatch: pytest.MonkeyPatch + route: str, + operation: str, + fault: str, + status: int, + code: str, + monkeypatch: pytest.MonkeyPatch, ) -> None: faulted = True stale_session: bytes | None = None successful_sessions: list[bytes] = [] + upstream_requests: list[str] = [] + queries: list[str] = [] manager = _resource_server(lambda: None, stateless=False) + class Resolver: + async def resolve(self, host: str, family: str, **options: Any) -> list[dns.rdata.Rdata]: + assert host == "source.example.test" + assert options == {"search": False, "raise_on_no_answer": False} + queries.append(family) + if family == ("A" if route == "live" else "AAAA"): + address = "8.8.8.8" if family == "A" else "2600::10" + elif faulted and fault == "dns-unavailable": + raise dns.resolver.NoNameservers("synthetic private DNS detail") + elif faulted and fault == "dns-timeout": + raise dns.resolver.LifetimeTimeout(timeout=0.1, errors=[]) + elif faulted and fault == "dns-prohibited": + address = "127.0.0.1" if family == "A" else "::1" + else: + return [] + return [dns.rdata.from_text("IN", family, address)] + async def app(scope: Scope, receive: Receive, send: Send) -> None: nonlocal stale_session + upstream_requests.append(scope["method"]) if scope["method"] != "POST": await manager.handle_request(scope, receive, send) return @@ -448,7 +484,7 @@ def routed_client(config, credential, *, validate_access, deadline): ) monkeypatch.setattr(direct_backend, "MCPSourceClient", routed_client) - monkeypatch.setattr(mcp_client, "resolve_public_address", _synthetic_pin) + monkeypatch.setattr(dns.asyncresolver, "Resolver", Resolver) profile = ApprovedProfile( MCPSourceConfig(endpoint=_ENDPOINT, bearer_audience=_ENDPOINT), ("org",) ) @@ -492,9 +528,12 @@ def headers() -> dict[str, str]: ): failed = await worker.post(f"/v1/{route}", headers=headers()) assert failed.status_code == status - assert failed.json() == {"status": "unavailable" if status == 503 else "unsupported"} + assert failed.json() == {"status": code} assert failed.headers["Cache-Control"] == "no-store" assert not successful_sessions + assert sorted(queries) == ["A", "AAAA"] + if fault.startswith("dns-"): + assert upstream_requests == [] faulted = False succeeded = await worker.post(f"/v1/{route}", headers=headers()) assert succeeded.status_code == 200 diff --git a/source_worker/tests/test_read_service.py b/source_worker/tests/test_read_service.py index 6bce932202..55b6b2c1d8 100644 --- a/source_worker/tests/test_read_service.py +++ b/source_worker/tests/test_read_service.py @@ -1,16 +1,19 @@ import asyncio import hashlib import unittest +from unittest.mock import patch from uuid import uuid4 import httpx from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from loom_source_worker import read_service from loom_source_worker.http_service import create_app from loom_source_worker.protocol import ( ConnectionBinding, ReadBinding, ReadGrant, issue_read_grant, + verify_read_grant, ) from loom_source_worker.read_service import ( BoundReader, @@ -20,6 +23,8 @@ ReadLimits, ReadService, ) +from starlette.responses import JSONResponse +from starlette.types import Message, Receive, Scope, Send class _Backend: @@ -163,6 +168,69 @@ async def test_saturation_and_cancellation_release_the_live_slot(self) -> None: self.backend.release.set() self.assertIsNotNone((await service.execute(self._token(self._live()), "live")).document) + async def test_http_render_must_finish_before_the_effective_deadline(self) -> None: + for budget, read_seconds in (("read", 1), ("grant", 15)): + for expired in (False, True): + with self.subTest(budget=budget, expired=expired): + await self._assert_render_deadline(read_seconds, expired) + + async def _assert_render_deadline(self, read_seconds: float, expired: bool) -> None: + token = self._token(self._live()) + _, expires_at = verify_read_grant( + token, issuer="loom", worker_id=self.binding.worker_id, key=self.key.public_key() + ) + app = create_app(self._service(timeout=read_seconds)) + loop = asyncio.get_running_loop() + now = loop.time() + budget = min(read_seconds, 10) + elapsed = 0.0 + render = JSONResponse.render + frames: list[Message] = [] + + def render_with_clock(response: JSONResponse, content: dict[str, object]) -> bytes: + nonlocal elapsed + encoded = render(response, content) + if content["status"] == "ok": + elapsed += budget if expired else budget / 2 + return encoded + + async def record_app(scope: Scope, receive: Receive, send: Send) -> None: + async def record(message: Message) -> None: + frames.append(message) + await send(message) + + await app(scope, receive, record) + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=record_app), base_url="http://worker.test" + ) as worker: + with ( + patch.object(loop, "time", lambda: now + elapsed), + patch.object(read_service, "time") as wall, + patch.object(JSONResponse, "render", render_with_clock), + ): + wall.time.side_effect = lambda: expires_at - 10 + elapsed + response = await worker.post( + "/v1/live", headers={"Authorization": f"Bearer {token}"} + ) + self.assertEqual( + [frame["type"] for frame in frames], + ["http.response.start", "http.response.body"], + ) + self.assertEqual(response.headers["Cache-Control"], "no-store") + if expired: + self.assertEqual( + (frames[0]["status"], response.json()), (504, {"status": "timeout"}) + ) + self.assertNotIn(self.backend.payload.encode(), frames[1]["body"]) + retry = await worker.post( + "/v1/live", headers={"Authorization": f"Bearer {self._token(self._live())}"} + ) + self.assertEqual(retry.status_code, 200) + else: + self.assertEqual(frames[0]["status"], 200) + self.assertEqual(response.json()["document"]["text"], self.backend.payload) + async def test_http_body_backpressure_holds_the_org_slot(self) -> None: app = create_app(self._service(timeout=3)) sending = asyncio.Event() From 43e0501449013883428d05a7381f6647ef7feb1d Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 26 Nov 2026 16:18:02 +0000 Subject: [PATCH 29/31] Fence worker MCP calls and validate POST acknowledgments Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 115 +++++++++++++----- source_worker/tests/test_mcp_client.py | 80 ++++++++++++ 2 files changed, 167 insertions(+), 28 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 9ebfd81f8f..7fa510a75b 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -104,7 +104,9 @@ def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = T raise MCPSourceError("timeout") -def _check_response(method: str, response: httpx.Response, *, has_session: bool) -> None: +def _check_response( + method: str, response: httpx.Response, *, has_session: bool, expects_post_reply: bool +) -> None: status = response.status_code if status == 401: raise MCPSourceError("reconnect") @@ -122,7 +124,9 @@ def _check_response(method: str, response: httpx.Response, *, has_session: bool) if status not in {200, 204}: raise MCPSourceError("protocol") return - if method == "POST" and status == 202: + if method == "POST" and not expects_post_reply: + if status != 202: + raise MCPSourceError("protocol") return if status != 200: raise MCPSourceError("protocol") @@ -662,7 +666,9 @@ def __init__( validate_access: Callable[[], Awaitable[None]], *, transport: httpx.AsyncBaseTransport | None = None, + guard_tool_dispatch: Callable[[], None] | None = None, ) -> None: + self.guard_tool_dispatch = guard_tool_dispatch self.endpoint = _endpoint_url(config.endpoint) self.credential, self.deadline, self.limits = credential, deadline, config.limits self.validate_access = validate_access @@ -700,6 +706,40 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials raise MCPSourceError(self.record_failure(error)) from None + def _expects_post_reply(self, method: str, body: bytes) -> bool: + if method != "POST": + return False + message = types.JSONRPCMessage.model_validate_json(body).root + if not isinstance(message, types.JSONRPCRequest): + return False + if message.method == "tools/call" and self.guard_tool_dispatch is not None: + self.guard_tool_dispatch() + return True + + async def _validate_response( + self, request: httpx.Request, response: httpx.Response, *, expects_post_reply: bool + ) -> httpx.Response: + _check_response( + request.method, + response, + has_session="mcp-session-id" in request.headers, + expects_post_reply=expects_post_reply, + ) + if request.method == "DELETE": + return httpx.Response(response.status_code, content=b"") + # Reject compression so the wire budget bounds decoded protocol bytes. + if response.headers.get("content-encoding", "identity") != "identity": + raise MCPSourceError("protocol") + if not isinstance(response.stream, httpx.AsyncByteStream): + raise MCPSourceError("protocol") + response.stream = _LimitedStream(response.stream, self) + if request.method == "POST" and not expects_post_reply: + async for chunk in response.stream: + if chunk: + raise MCPSourceError("protocol") + return httpx.Response(response.status_code, headers=response.headers, content=b"") + return response + async def _handle(self, request: httpx.Request) -> httpx.Response: response: httpx.Response | None = None handed_off = False @@ -764,19 +804,14 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: }, ) await self._authorize() + expects_post_reply = self._expects_post_reply(request.method, body) response = await self.inner.handle_async_request(outgoing) self._check_state() - _check_response(request.method, response, has_session="mcp-session-id" in headers) - if request.method == "DELETE": - return httpx.Response(response.status_code, content=b"") - # Reject compression so the wire budget bounds decoded protocol bytes. - if response.headers.get("content-encoding", "identity") != "identity": - raise MCPSourceError("protocol") - if not isinstance(response.stream, httpx.AsyncByteStream): - raise MCPSourceError("protocol") - response.stream = _LimitedStream(response.stream, self) - handed_off = True - return response + validated = await self._validate_response( + outgoing, response, expects_post_reply=expects_post_reply + ) + handed_off = validated is response + return validated except Exception as error: # noqa: BLE001 — poison the session before awaiting private failure cleanup raise MCPSourceError(self.record_failure(error)) from None finally: @@ -853,6 +888,8 @@ def __init__( self._discovery: MCPDiscovery | None = None self._tool_epoch = 0 self._discovered_epoch = -1 + self._tool_dispatch_epoch: int | None = None + self._tool_dispatch_lock = asyncio.Lock() self._pages, self._results = 0, 0 self._issued_cursors: set[tuple[tuple[str, str], str]] = set() self._used_cursors: set[tuple[tuple[str, str], str]] = set() @@ -1005,6 +1042,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None: self._deadline, self._transport_authorize, transport=self._test_transport, + guard_tool_dispatch=self._check_tool_dispatch, ) self._transport = transport client = await stack.enter_async_context( @@ -1076,9 +1114,11 @@ async def _message_handler(self, message: Any) -> None: ): self._tool_epoch += 1 - async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + async def _run( + self, action: Callable[[ClientSession], Awaitable[_T]], *, pins_tools: bool = False + ) -> _T: with private_work(): - return await self._execute(action) + return await self._execute(action, pins_tools=pins_tools) async def _request(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: # The SDK RPC can keep waiting after its HTTP task has refused the request. @@ -1095,12 +1135,15 @@ async def _request(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T request.cancel() await asyncio.gather(request, return_exceptions=True) - async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + async def _execute( + self, action: Callable[[ClientSession], Awaitable[_T]], *, pins_tools: bool + ) -> _T: try: self._check_state(require_session=True) async with asyncio.timeout_at(self._deadline): await self._authorize() self._check_state(require_session=True) + epoch = self._tool_epoch try: result = await self._request(action) except Exception: # Check authority before reporting an upstream error. @@ -1108,6 +1151,8 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T raise await self._authorize() self._check_state(require_session=True) + if pins_tools and epoch != self._tool_epoch: + raise MCPSourceError("schema") return result except ( Exception, # Terminal refusals must drain owned HTTP work before returning. @@ -1133,7 +1178,7 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T raise MCPSourceError(code) from None async def discover(self) -> MCPDiscovery: - return await self._run(self._discover) + return await self._run(self._discover, pins_tools=bool(self._config.approved_tools)) async def _discover(self, session: ClientSession) -> MCPDiscovery: approved = set(self._config.approved_tools) @@ -1245,6 +1290,10 @@ async def action(session: ClientSession) -> MCPPage: return await self._run(action) + def _check_tool_dispatch(self) -> None: + if self._tool_dispatch_epoch != self._tool_epoch: + raise MCPSourceError("schema") + async def _tool( self, session: ClientSession, mapping: MCPToolMapping, value: str, cursor: str | None = None ) -> Any: @@ -1263,16 +1312,26 @@ async def _tool( raise MCPSourceError("unsupported") arguments[mapping.cursor_argument] = cursor _validate(mapping.input_schema, arguments, 32_768, self._config.data_policy) - # Public SDK RPC path lets independent data bounds precede schema validation. - result = await session.send_request( - types.ClientRequest( - types.CallToolRequest( - params=types.CallToolRequestParams(name=mapping.name, arguments=arguments) + epoch = self._discovered_epoch + async with self._tool_dispatch_lock: + self._check_state(require_session=True) + self._tool_dispatch_epoch = epoch + try: + self._check_tool_dispatch() + # Public SDK RPC path lets independent data bounds precede schema validation. + result = await session.send_request( + types.ClientRequest( + types.CallToolRequest( + params=types.CallToolRequestParams( + name=mapping.name, arguments=arguments + ) + ) + ), + types.CallToolResult, ) - ), - types.CallToolResult, - ) - if self._tool_epoch != self._discovered_epoch: + finally: + self._tool_dispatch_epoch = None + if self._tool_epoch != epoch: raise MCPSourceError("schema") return _tool_value(result, mapping, self._config.limits, self._config.data_policy) @@ -1312,7 +1371,7 @@ async def action(session: ClientSession) -> MCPPage: ("search", query), ) - return await self._run(action) + return await self._run(action, pins_tools=True) async def _read_tool(self, session: ClientSession, identity: str) -> MCPEvidence: mapping = self._config.read @@ -1358,4 +1417,4 @@ async def action(session: ClientSession) -> MCPEvidence: "resources/read", ) - return await self._run(action) + return await self._run(action, pins_tools=self._config.read is not None) diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index f7009ef85c..c5c7c94db3 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -769,3 +769,83 @@ async def current_authority() -> None: for request, method in source.calls if method in {"resources/read", "DELETE"} ] == [("resources/read", "synthetic-session"), ("DELETE", "synthetic-session")] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stage", ["dispatch", "publication"]) +async def test_catalog_invalidation_refuses_mapped_read( + pin: list[str], monkeypatch: pytest.MonkeyPatch, stage: str +) -> None: + source, mapping = _mapped_source() + entered = asyncio.Event() + release = asyncio.Event() + dispatch_task: asyncio.Task[Any] | None = None + operation: asyncio.Task[Any] | None = None + original_aread = httpx.Request.aread + + async def mark_tool_request(request: httpx.Request) -> bytes: + data = await original_aread(request) + if request.method == "POST" and json.loads(data)["method"] == "tools/call": + nonlocal dispatch_task + dispatch_task = asyncio.current_task() + return data + + async def validate_access() -> None: + current = asyncio.current_task() + dispatched = any(method == "tools/call" for _, method in source.calls) + if (stage == "dispatch" and current is dispatch_task and not dispatched) or ( + stage == "publication" and current is operation and dispatched and not entered.is_set() + ): + entered.set() + await release.wait() + + monkeypatch.setattr(httpx.Request, "aread", mark_tool_request) + config = MCPSourceConfig( + _ENDPOINT, approved_tools=("read",), read=mapping, approved_resource_ids=(_DOCUMENT,) + ) + async with MCPSourceClient( + config, None, validate_access=validate_access, _transport=source + ) as client: + operation = asyncio.create_task(client.read(_DOCUMENT)) + try: + await asyncio.wait_for(entered.wait(), 1) + await client._message_handler( + mcp_client.types.ServerNotification(mcp_client.types.ToolListChangedNotification()) + ) + finally: + release.set() + with pytest.raises(MCPSourceError, match="^MCP source schema$"): + await operation + assert sum(method == "tools/call" for _, method in source.calls) == (stage == "publication") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("method", "status", "payload"), + [ + ("notifications/initialized", 200, b"{}"), + ("notifications/initialized", 202, b"{}"), + ("resources/read", 202, b""), + ], +) +async def test_refuses_invalid_post_response( + pin: list[str], method: str, status: int, payload: bytes +) -> None: + def respond(request: httpx.Request) -> httpx.Response: + return httpx.Response( + status, stream=_Body(payload), headers={"content-type": "application/json"} + ) + + message: dict[str, str | int] = {"jsonrpc": "2.0", "method": method} + if method == "resources/read": + message["id"] = 1 + transport = mcp_client._PinnedTransport( + MCPSourceConfig(_ENDPOINT), + None, + asyncio.get_running_loop().time() + 1, + _authorized, + transport=httpx.MockTransport(respond), + ) + async with httpx.AsyncClient(transport=transport) as client: + with pytest.raises(MCPSourceError, match="^MCP source protocol$"): + await client.post(_ENDPOINT, json=message) From 32e4b2fa83ef488d5516ae9a794c00b956025cd9 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 26 Nov 2026 16:31:33 +0000 Subject: [PATCH 30/31] Reject ambiguous MCP worker resource selections Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 4 +- source_worker/tests/test_mcp_client.py | 39 +++++++++++++++++-- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 7fa510a75b..901ec57c28 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -285,7 +285,7 @@ def _resource_url(identity: str) -> AnyUrl: uri = AnyUrl(identity) except ValidationError: raise MCPSourceError("unsupported") from None - if str(uri) != identity: + if str(uri) != identity or uri.username is not None or uri.password is not None: raise MCPSourceError("unsupported") return uri @@ -484,7 +484,7 @@ def validate_mcp_tool_mapping( or mapping.input_schema.get("type") != "object" or mapping.output_schema.get("type") != ("string" if mapping.result_format == "text" else "object") - or (search and mapping.result_format == "text") + or (search and (mapping.result_format == "text" or not mapping.items_path)) or (mapping.result_format == "text" and mapping.items_path) ): raise MCPSourceError("config") diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index c5c7c94db3..583ee9c5be 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -507,7 +507,14 @@ async def test_stateful_read_accepts_idle_notifications_and_does_not_drain_termi assert source.termination.closed and not source.termination.started.is_set() -@pytest.mark.parametrize("identity", ["https://source.example", "https://résumé.example/item"]) +@pytest.mark.parametrize( + "identity", + [ + "https://source.example", + "https://résumé.example/item", + "https://user:password@source.example/item", + ], +) def test_resource_selection_refuses_a_uri_the_sdk_would_rewrite(identity: str) -> None: source = _Source() with pytest.raises(MCPSourceError, match="^MCP source unsupported$"): @@ -561,9 +568,12 @@ async def test_resource_parser_bounds_cover_metadata_and_extensions( @pytest.mark.asyncio -async def test_list_does_not_offer_a_normalized_replacement_identity(pin: list[str]) -> None: +@pytest.mark.parametrize( + "identity", ["https://UPSTREAM.example/path", "https://user:password@source.example/item"] +) +async def test_list_refuses_unsafe_resource_identity(pin: list[str], identity: str) -> None: source = _Source() - source.listed_uri = "https://UPSTREAM.example/path" + source.listed_uri = identity async with _client(source) as client: with pytest.raises(MCPSourceError, match="^MCP source unsupported$"): await client.list_resources() @@ -849,3 +859,26 @@ def respond(request: httpx.Request) -> httpx.Response: async with httpx.AsyncClient(transport=transport) as client: with pytest.raises(MCPSourceError, match="^MCP source protocol$"): await client.post(_ENDPOINT, json=message) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("identity", ["file:///local/example", "urn:example:document"]) +async def test_native_resources_preserve_exact_hostless_identity( + pin: list[str], identity: str +) -> None: + source = _Source() + source.listed_uri = source.resource_uri = identity + async with _client(source, approved_resource_ids=(identity,)) as client: + assert (await client.list_resources()).items[0].resource_id == identity + item = await client.read(identity) + assert item.receipt is not None and item.receipt.requested_id == identity + for request, method in source.calls: + if method == "resources/read": + assert json.loads(request.content)["params"]["uri"] == identity + + +def test_mapped_search_requires_an_items_selector() -> None: + source, mapping = _mapped_source() + with pytest.raises(MCPSourceError, match="^MCP source config$"): + _client(source, approved_tools=(mapping.name,), search=mapping) + assert not source.calls From d9e1ffb730e54c4fc83d314dc0cf3d3f860570d7 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 26 Nov 2026 16:45:39 +0000 Subject: [PATCH 31/31] Keep interrupted MCP responses retryable Report remote HTTP protocol failures as unavailable so an interrupted response retains its transport status. Preserve the timeout status for read deadlines. Signed-off-by: zlareb1 --- .../loom_source_worker/mcp_client.py | 2 +- source_worker/tests/test_mcp_client.py | 30 ++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 901ec57c28..7abcef6ba8 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -72,7 +72,7 @@ def _error_code(error: BaseException) -> ErrorCode: return error.code if isinstance(error, (TimeoutError, httpx.TimeoutException)): return "timeout" - if isinstance(error, httpx.NetworkError): + if isinstance(error, (httpx.NetworkError, httpx.RemoteProtocolError)): return "unavailable" if isinstance(error, McpError) and error.error.code == httpx.codes.REQUEST_TIMEOUT: return "timeout" diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 583ee9c5be..70813dc212 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -105,6 +105,7 @@ def __init__(self) -> None: self.resource_parts = 1 self.initialize_error: int | None = None self.resource_error: int | None = None + self.resource_transport_error: httpx.TransportError | None = None self.resource_rpc_error = False self.resource_extensions: dict[str, Any] = {} self.notifications: _IdleBody | None = None @@ -181,7 +182,11 @@ async def respond(self, request: httpx.Request) -> httpx.Response: envelope = json.dumps({"jsonrpc": "2.0", "id": body["id"], "result": result}) return httpx.Response( 200, - stream=_Body(f"event: message\ndata: {envelope}\n\n".encode()), + stream=( + _Body(f"event: message\ndata: {envelope}\n\n".encode()) + if self.resource_transport_error is None + else _InterruptedBody(self.resource_transport_error) + ), headers={ "content-type": "text/event-stream", "content-encoding": self.content_encoding, @@ -219,6 +224,15 @@ async def __aiter__(self) -> AsyncIterator[bytes]: yield self.content[64:] +class _InterruptedBody(httpx.AsyncByteStream): + def __init__(self, failure: httpx.TransportError) -> None: + self.failure = failure + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield b"event: message\ndata: " + raise self.failure + + class _IdleBody(httpx.AsyncByteStream): def __init__(self) -> None: self.started = asyncio.Event() @@ -665,6 +679,20 @@ async def validate_access() -> None: assert source.closed +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("failure", "status"), + [(httpx.RemoteProtocolError, "unavailable"), (httpx.ReadTimeout, "timeout")], +) +async def test_interrupted_response_retains_transport_status(pin, failure, status) -> None: + source = _Source() + source.resource_transport_error = failure("synthetic upstream detail") + async with _client(source, approved_resource_ids=(_DOCUMENT,)) as client: + with pytest.raises(MCPSourceError, match=f"^MCP source {status}$"): + await client.read(_DOCUMENT) + assert source.closed + + @pytest.mark.asyncio async def test_session_deadline_cancels_stalled_read(pin: list[str]) -> None: source = _Source()