Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(dingtalk): sanitize remote filename before writing downloaded file

Lanre Shittu12bf37b10106
diff --git a/agent/src/channels/dingtalk.py b/agent/src/channels/dingtalk.py
index 7f81b714c..d0a53db79 100644
--- a/agent/src/channels/dingtalk.py
+++ b/agent/src/channels/dingtalk.py
@@ -17,6 +17,7 @@ from pydantic import Field
from src.channels.bus.events import OutboundMessage
from src.channels.bus.queue import MessageBus
from src.channels.base import BaseChannel
+from src.channels.utils import safe_filename
from pydantic import BaseModel
from src.security.network import validate_resolved_url, validate_url_target
@@ -761,10 +762,15 @@ class DingTalkChannel(BaseChannel):
self.logger.error("file download failed: status={}", file_resp.status_code)
return None
- # Save to media directory (accessible under workspace)
+ # Save to media directory (accessible under workspace). filename
+ # comes straight from the inbound payload, so it must be
+ # sanitized the same way every other adapter sanitizes remote
+ # filenames before joining it: an unsanitized "../../etc/x" (or
+ # an absolute path, which Path.__truediv__ would substitute for
+ # the whole intended path) would write outside download_dir.
download_dir = get_media_dir("dingtalk") / sender_id
download_dir.mkdir(parents=True, exist_ok=True)
- file_path = download_dir / filename
+ file_path = download_dir / safe_filename(filename)
await asyncio.to_thread(file_path.write_bytes, file_resp.content)
self.logger.info("file saved: {}", file_path)
return str(file_path)
diff --git a/agent/tests/test_dingtalk_file_download.py b/agent/tests/test_dingtalk_file_download.py
new file mode 100644
index 000000000..bf218f583
--- /dev/null
+++ b/agent/tests/test_dingtalk_file_download.py
@@ -0,0 +1,79 @@
+"""A remote fileName must not escape the per-sender download directory."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import pytest
+
+from src.channels.dingtalk import DingTalkChannel
+
+
+def _channel(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, file_bytes: bytes
+) -> DingTalkChannel:
+ channel = object.__new__(DingTalkChannel)
+ channel.logger = logging.getLogger("test.dingtalk")
+ channel.config = type("Config", (), {"client_id": "test-client"})()
+ channel._access_token = "test-token"
+ channel._token_expiry = float("inf")
+
+ token_response = type(
+ "Resp",
+ (),
+ {
+ "status_code": 200,
+ "json": lambda self: {"downloadUrl": "https://example.invalid/f"},
+ },
+ )()
+ file_response = type("Resp", (), {"status_code": 200, "content": file_bytes})()
+ http = AsyncMock()
+ http.post = AsyncMock(return_value=token_response)
+ http.get = AsyncMock(return_value=file_response)
+ channel._http = http
+
+ monkeypatch.setattr(
+ "src.channels.utils.get_media_dir", lambda name: tmp_path / name
+ )
+ return channel
+
+
+def test_path_traversal_filename_stays_inside_download_dir(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def scenario() -> None:
+ channel = _channel(tmp_path, monkeypatch, b"attacker content")
+
+ result = await channel._download_dingtalk_file(
+ "download-code", "../../../../../../tmp/evil.txt", "sender123"
+ )
+
+ assert result is not None
+ result_path = Path(result).resolve()
+ download_root = (tmp_path / "dingtalk" / "sender123").resolve()
+ assert download_root in result_path.parents
+ assert not (Path("/tmp") / "evil.txt").exists()
+
+ asyncio.run(scenario())
+
+
+def test_absolute_path_filename_stays_inside_download_dir(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def scenario() -> None:
+ channel = _channel(tmp_path, monkeypatch, b"attacker content")
+
+ result = await channel._download_dingtalk_file(
+ "download-code", "/tmp/evil_absolute.txt", "sender123"
+ )
+
+ assert result is not None
+ result_path = Path(result).resolve()
+ download_root = (tmp_path / "dingtalk" / "sender123").resolve()
+ assert download_root in result_path.parents
+ assert not Path("/tmp/evil_absolute.txt").exists()
+
+ asyncio.run(scenario())