Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(media): add fetch_to_workspace and share the SSRF guard
trohitg038ecd2577ea
diff --git a/server/nodes/code/monty_executor/__init__.py b/server/nodes/code/monty_executor/__init__.pyindex 950f27f7..e74fb611 100644--- a/server/nodes/code/monty_executor/__init__.py+++ b/server/nodes/code/monty_executor/__init__.py@@ -30,10 +30,7 @@ Verified against pydantic-monty==0.0.18 (the pinned version):from __future__ import annotations-import ipaddress-import socketfrom typing import Any, Callable, Dict, Optional, Tuple-from urllib.parse import urlparsefrom pydantic import BaseModel, ConfigDict, Field@@ -61,38 +58,10 @@ _UNSUPPORTED = "class, yield/generators, with, match, `import random|collections# ----------------------------------------------------------------------------def _is_public_url(url: str) -> Tuple[bool, str]:- """SSRF guard: allow only http/https to a publicly-routable host.-- Resolves every A/AAAA record and rejects loopback / private / link-local /- reserved / multicast / unspecified addresses. (DNS is re-resolved by httpx,- so this is a best-effort guard, not TOCTOU-proof — acceptable for v1.)- """- parsed = urlparse(url)- if parsed.scheme not in ("http", "https"):- return False, f"only http/https allowed (got {parsed.scheme or 'no scheme'!r})"- host = parsed.hostname- if not host:- return False, "missing host"- try:- infos = socket.getaddrinfo(host, None)- except socket.gaierror as exc:- return False, f"DNS resolution failed: {exc}"- for info in infos:- try:- ip = ipaddress.ip_address(info[4][0])- except ValueError:- continue- if (- ip.is_private- or ip.is_loopback- or ip.is_link_local- or ip.is_reserved- or ip.is_multicast- or ip.is_unspecified- ):- return False, f"blocked non-public address {ip}"- return True, ""+# Promoted to services/net.py so the workspace fetcher shares one+# implementation. Re-exported under the original private name because the+# call site below and any monkeypatching in tests reference it.+from services.net import is_public_url as _is_public_url # noqa: E402def _make_http_get(timeout: float = 15.0) -> Callable[[str], str]:diff --git a/server/services/media/__init__.py b/server/services/media/__init__.pyindex c752dc72..8ca1d3b2 100644--- a/server/services/media/__init__.py+++ b/server/services/media/__init__.py@@ -10,6 +10,7 @@ The contract in one line: **a node returns an**:mod:`services.media.limits` for the measured reason."""+from services.media.fetch import fetch_to_workspacefrom services.media.inspect import AudioProbe, inspect_audiofrom services.media.limits import (MEDIA_MAX_AUDIO_SECONDS,@@ -46,6 +47,7 @@ __all__ = ["TEMPORAL_PAYLOAD_ERROR_BYTES","TEMPORAL_PAYLOAD_WARN_BYTES","coerce_file_param",+ "fetch_to_workspace","inspect_audio","read_media_bytes","resolve_media",diff --git a/server/services/media/fetch.py b/server/services/media/fetch.pynew file mode 100644index 00000000..7c5ae7d6--- /dev/null+++ b/server/services/media/fetch.py@@ -0,0 +1,145 @@+"""Download a remote file straight into a workflow workspace.++Separate module rather than part of :mod:`services.media.workspace` because+that one is synchronous by contract (see its ``workspace_root`` docstring --+it must never do the database read the id->slug translation would need) and+this is unavoidably async.++The alternative every caller reaches for otherwise is ``httpx.get`` followed+by ``open(path, "wb").write(...)``, which is what ``fileDownloader`` does:+no containment, a filename taken from the remote URL, a non-atomic write and+no size cap. This exists so that is never the easy option.+"""++from __future__ import annotations++import mimetypes+from pathlib import PurePosixPath+from typing import Any, Dict, Optional+from urllib.parse import unquote, urlparse++from core.logging import get_logger+from services.media.limits import MEDIA_MAX_READ_BYTES+from services.media.refs import FileKind, FileRef+from services.media.workspace import MEDIA_SUBDIR, write_media++logger = get_logger(__name__)++# Bounded so a hostile Content-Length cannot make us allocate; the running+# total is what enforces the cap, mirroring the upload route.+_CHUNK_BYTES = 64 * 1024++_DEFAULT_TIMEOUT_SECONDS = 30.0+++def _extension_for(url: str, content_type: Optional[str]) -> str:+ """Best available extension, preferring what the server actually served.++ The URL path is the weaker signal: providers routinely serve media from+ extensionless, query-signed URLs (Meta's lookaside CDN is one), so the+ Content-Type is tried first and the path is the fallback.+ """+ if content_type:+ # Strip parameters: "audio/ogg; codecs=opus" -> "audio/ogg".+ base = content_type.split(";")[0].strip()+ guessed = mimetypes.guess_extension(base)+ if guessed:+ return guessed.lstrip(".")++ suffix = PurePosixPath(unquote(urlparse(url).path)).suffix+ if suffix:+ return suffix.lstrip(".")+ return "bin"+++async def fetch_to_workspace(+ url: str,+ *,+ ctx: Any,+ stem: str,+ kind: FileKind = "file",+ headers: Optional[Dict[str, str]] = None,+ max_bytes: int = MEDIA_MAX_READ_BYTES,+ subdir: str = MEDIA_SUBDIR,+ timeout: float = _DEFAULT_TIMEOUT_SECONDS,+ ext: Optional[str] = None,+) -> FileRef:+ """Stream ``url`` into the workspace and return a reference to it.++ ``headers`` carries provider authentication -- several media APIs sign+ their download URLs *and* still require the bearer token, and hand out+ URLs that expire in minutes, so resolve immediately before calling this+ rather than storing one.++ Raises :class:`NodeUserError` for every failure a caller can act on: a+ blocked host, a non-2xx response, an oversize body, an empty body. Those+ are user- or provider-correctable, so they log one warning rather than a+ traceback.+ """+ import httpx++ from services.net import is_public_url+ from services.plugin import NodeUserError++ ok, reason = is_public_url(url)+ if not ok:+ # Deliberately not echoing the URL: it may carry a signed query+ # string, and this message reaches logs and the LLM context.+ raise NodeUserError(f"Refusing to download from that URL: {reason}.")++ if kind == "audio":+ # Same rule as write_media: that kind asserts a real probe.+ raise NodeUserError(+ "fetch_to_workspace cannot produce kind='audio': that claims the "+ "container was probed. Download as 'file', then write with write_audio."+ )++ chunks: list[bytes] = []+ total = 0+ try:+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:+ async with client.stream("GET", url, headers=headers or {}) as response:+ if response.status_code >= 400:+ # Read nothing further; the body of an error page is not+ # something we want in the workspace.+ raise NodeUserError(+ f"Download failed with HTTP {response.status_code}. "+ "If the URL was issued by a provider it may have expired -- "+ "re-resolve it and retry."+ )+ content_type = response.headers.get("content-type")+ async for chunk in response.aiter_bytes(_CHUNK_BYTES):+ total += len(chunk)+ if total > max_bytes:+ raise NodeUserError(+ f"Download exceeds the {max_bytes // (1024 * 1024)} MB limit."+ )+ chunks.append(chunk)+ except httpx.TimeoutException as exc:+ raise NodeUserError(f"Download timed out after {timeout:g}s.") from exc+ except httpx.HTTPError as exc:+ raise NodeUserError(f"Download failed: {exc}") from exc++ if not total:+ raise NodeUserError("Download returned an empty file.")++ ref = write_media(+ b"".join(chunks),+ ctx=ctx,+ stem=stem,+ ext=ext or _extension_for(url, content_type),+ kind=kind,+ mime_type=(content_type or "").split(";")[0].strip() or None,+ subdir=subdir,+ )++ logger.info(+ "fetched media into workspace",+ path=ref.path,+ size_bytes=ref.size_bytes,+ kind=ref.kind,+ )+ return ref+++__all__ = ["fetch_to_workspace"]diff --git a/server/services/net.py b/server/services/net.pynew file mode 100644index 00000000..89d58850--- /dev/null+++ b/server/services/net.py@@ -0,0 +1,55 @@+"""Network egress guards shared by anything that fetches a caller-supplied URL.++Lives here rather than inside one plugin because more than one consumer needs+the same check, and two copies of an SSRF guard is how one of them silently+falls behind the other.+"""++from __future__ import annotations++import ipaddress+import socket+from typing import Tuple+from urllib.parse import urlparse+++def is_public_url(url: str) -> Tuple[bool, str]:+ """SSRF guard: allow only http/https to a publicly-routable host.++ Resolves every A/AAAA record and rejects loopback / private / link-local /+ reserved / multicast / unspecified addresses.++ Best-effort, not TOCTOU-proof: httpx re-resolves DNS when it connects, so a+ hostile record could change between this check and the request. Closing+ that needs connection-time pinning, which is a bigger change than the+ threat has so far justified. Returns ``(ok, reason)`` rather than raising+ so callers can phrase the refusal in their own error vocabulary.+ """+ parsed = urlparse(url)+ if parsed.scheme not in ("http", "https"):+ return False, f"only http/https allowed (got {parsed.scheme or 'no scheme'!r})"+ host = parsed.hostname+ if not host:+ return False, "missing host"+ try:+ infos = socket.getaddrinfo(host, None)+ except socket.gaierror as exc:+ return False, f"DNS resolution failed: {exc}"+ for info in infos:+ try:+ ip = ipaddress.ip_address(info[4][0])+ except ValueError:+ continue+ if (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_reserved+ or ip.is_multicast+ or ip.is_unspecified+ ):+ return False, f"blocked non-public address {ip}"+ return True, ""+++__all__ = ["is_public_url"]diff --git a/server/tests/media/test_fetch_to_workspace.py b/server/tests/media/test_fetch_to_workspace.pynew file mode 100644index 00000000..58e37d30--- /dev/null+++ b/server/tests/media/test_fetch_to_workspace.py@@ -0,0 +1,200 @@+"""Contract for ``fetch_to_workspace``.++The failure modes that matter are the ones the hand-rolled downloaders get+wrong: trusting Content-Length, writing outside the workspace, taking the+filename from the remote URL, and treating an expired provider URL as a+server fault rather than something the caller can retry.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from types import SimpleNamespace++import httpx+import pytest++from services.media import MEDIA_SUBDIR, fetch_to_workspace, read_media_bytes+++pytestmark = pytest.mark.unit+++def _ctx(tmp_path: Path, *, node_id: str = "wa-node-1", workflow_id: str = "wf-1"):+ return SimpleNamespace(+ node_id=node_id,+ workflow_id=workflow_id,+ workspace_dir=str(tmp_path),+ raw={"workspace_dir": str(tmp_path)},+ )+++def _run(coro):+ return asyncio.new_event_loop().run_until_complete(coro)+++def _transport(handler):+ """Route httpx through a stub so no test touches the network."""+ return httpx.MockTransport(handler)+++def public_url(monkeypatch):+ """Neutralise the SSRF guard; example.com does not resolve in CI."""+ monkeypatch.setattr("services.net.is_public_url", lambda _url: (True, ""))+++def stub_http(monkeypatch):+ """Install a MockTransport into every AsyncClient fetch_to_workspace builds."""++ def _install(handler):+ original = httpx.AsyncClient++ def _factory(*args, **kwargs):+ kwargs["transport"] = _transport(handler)+ return original(*args, **kwargs)++ monkeypatch.setattr(httpx, "AsyncClient", _factory)++ return _install+++class TestFetchToWorkspace:+ def test_writes_body_into_the_workspace(self, tmp_path, public_url, stub_http):+ stub_http(lambda _req: httpx.Response(200, content=b"binary-body", headers={"content-type": "image/png"}))+ ctx = _ctx(tmp_path)++ ref = _run(fetch_to_workspace("https://example.com/x", ctx=ctx, stem="photo", kind="image"))++ assert ref.kind == "image"+ assert ref.path.startswith(f"{MEDIA_SUBDIR}/")+ assert read_media_bytes(ref, ctx=ctx)[1] == b"binary-body"++ def test_extension_comes_from_content_type_not_the_url(self, tmp_path, public_url, stub_http):+ """Provider CDNs serve media from extensionless, query-signed URLs."""+ stub_http(lambda _req: httpx.Response(200, content=b"x", headers={"content-type": "image/jpeg"}))++ ref = _run(+ fetch_to_workspace(+ "https://example.com/whatsapp_business/attachments/?mid=123&ext=1",+ ctx=_ctx(tmp_path),+ stem="inbound",+ kind="image",+ )+ )+ assert ref.filename.endswith(".jpg") or ref.filename.endswith(".jpeg")+ assert ref.mime_type == "image/jpeg"++ def test_falls_back_to_the_url_suffix(self, tmp_path, public_url, stub_http):+ stub_http(lambda _req: httpx.Response(200, content=b"x"))++ ref = _run(fetch_to_workspace("https://example.com/report.pdf", ctx=_ctx(tmp_path), stem="r"))+ assert ref.filename.endswith(".pdf")++ def test_filename_is_ours_not_the_servers(self, tmp_path, public_url, stub_http):+ """A server-controlled filename is how fileDownloader escapes its dir."""+ stub_http(+ lambda _req: httpx.Response(+ 200,+ content=b"x",+ headers={"content-disposition": 'attachment; filename="../../evil.sh"'},+ )+ )++ ref = _run(fetch_to_workspace("https://example.com/../../evil.sh", ctx=_ctx(tmp_path), stem="safe"))+ assert ".." not in ref.path+ assert ref.path.startswith(f"{MEDIA_SUBDIR}/")+ assert ref.filename.startswith("safe-")++ def test_cap_is_enforced_on_bytes_actually_read(self, tmp_path, public_url, stub_http):+ """Content-Length is attacker-controlled; the running total is not."""+ from services.plugin import NodeUserError++ big = b"a" * 5000+ stub_http(lambda _req: httpx.Response(200, content=big, headers={"content-length": "1"}))++ with pytest.raises(NodeUserError, match="limit"):+ _run(fetch_to_workspace("https://example.com/x", ctx=_ctx(tmp_path), stem="x", max_bytes=1000))++ def test_nothing_is_written_when_the_cap_trips(self, tmp_path, public_url, stub_http):+ from services.plugin import NodeUserError++ stub_http(lambda _req: httpx.Response(200, content=b"a" * 5000))+ with pytest.raises(NodeUserError):+ _run(fetch_to_workspace("https://example.com/x", ctx=_ctx(tmp_path), stem="x", max_bytes=10))++ assert not (tmp_path / MEDIA_SUBDIR).exists()++ def test_expired_url_is_a_user_error_not_a_crash(self, tmp_path, public_url, stub_http):+ """Provider media URLs expire in minutes; that is retryable, not a bug."""+ from services.plugin import NodeUserError++ stub_http(lambda _req: httpx.Response(404, content=b"gone"))++ with pytest.raises(NodeUserError, match="expired"):+ _run(fetch_to_workspace("https://example.com/x", ctx=_ctx(tmp_path), stem="x"))++ def test_empty_body_is_refused(self, tmp_path, public_url, stub_http):+ from services.plugin import NodeUserError++ stub_http(lambda _req: httpx.Response(200, content=b""))++ with pytest.raises(NodeUserError, match="empty"):+ _run(fetch_to_workspace("https://example.com/x", ctx=_ctx(tmp_path), stem="x"))++ def test_auth_headers_are_forwarded(self, tmp_path, public_url, stub_http):+ """Meta's media URLs are signed AND still require the bearer token."""+ seen = {}++ def handler(request):+ seen["auth"] = request.headers.get("authorization")+ return httpx.Response(200, content=b"x")++ stub_http(handler)+ _run(+ fetch_to_workspace(+ "https://example.com/x",+ ctx=_ctx(tmp_path),+ stem="x",+ headers={"Authorization": "Bearer tok"},+ )+ )+ assert seen["auth"] == "Bearer tok"++ def test_refuses_to_claim_audio(self, tmp_path, public_url, stub_http):+ from services.plugin import NodeUserError++ stub_http(lambda _req: httpx.Response(200, content=b"x"))+ with pytest.raises(NodeUserError, match="write_audio"):+ _run(fetch_to_workspace("https://example.com/x", ctx=_ctx(tmp_path), stem="x", kind="audio"))+++class TestSsrfGuard:+ """The guard is shared with monty_executor rather than duplicated."""++ @pytest.mark.parametrize(+ "url",+ [+ "http://127.0.0.1/admin",+ "http://localhost/admin",+ "file:///etc/passwd",+ "ftp://example.com/x",+ "not-a-url",+ ],+ )+ def test_blocked_targets_are_refused(self, tmp_path, url):+ from services.plugin import NodeUserError++ with pytest.raises(NodeUserError, match="Refusing to download"):+ _run(fetch_to_workspace(url, ctx=_ctx(tmp_path), stem="x"))++ def test_refusal_does_not_echo_the_url(self, tmp_path):+ """Signed query strings must not leak into logs or LLM context."""+ from services.plugin import NodeUserError++ secret = "https://127.0.0.1/x?sig=SUPERSECRET"+ with pytest.raises(NodeUserError) as exc:+ _run(fetch_to_workspace(secret, ctx=_ctx(tmp_path), stem="x"))+ assert "SUPERSECRET" not in str(exc.value)