diff --git a/zulip/tests/test_fetch_upload.py b/zulip/tests/test_fetch_upload.py new file mode 100644 index 000000000..57b884c55 --- /dev/null +++ b/zulip/tests/test_fetch_upload.py @@ -0,0 +1,98 @@ +from unittest.mock import MagicMock, patch + +import pytest + +from zulip import Client, ZulipError + + +def make_client() -> Client: + with patch.object( + Client, + "get_server_settings", + return_value={"zulip_version": "test-version", "zulip_feature_level": 1}, + ): + return Client( + email="test@example.com", + api_key="test-api-key", + site="https://zulip.example.com", + client="test-client", + ) + + +def mock_response(status_code: int, content: bytes) -> MagicMock: + response = MagicMock() + response.status_code = status_code + response.content = content + return response + + +class TestFetchUpload: + def test_absolute_url_passthrough(self) -> None: + client = make_client() + client.ensure_session() + assert client.session is not None + with patch.object( + client.session, "get", return_value=mock_response(200, b"file contents") + ) as mock_get: + result = client.fetch_upload("https://zulip.example.com/user_uploads/1/file.pdf") + mock_get.assert_called_once_with( + "https://zulip.example.com/user_uploads/1/file.pdf", timeout=90.0 + ) + assert result == b"file contents" + + def test_absolute_url_on_other_origin_rejected(self) -> None: + client = make_client() + client.ensure_session() + assert client.session is not None + with patch.object(client.session, "get") as mock_get: + with pytest.raises(ZulipError): + client.fetch_upload("https://evil.example.com/user_uploads/1/file.pdf") + mock_get.assert_not_called() + + def test_absolute_url_with_different_scheme_rejected(self) -> None: + client = make_client() + client.ensure_session() + assert client.session is not None + with patch.object(client.session, "get") as mock_get: + with pytest.raises(ZulipError): + client.fetch_upload("http://zulip.example.com/user_uploads/1/file.pdf") + mock_get.assert_not_called() + + def test_root_relative_path_resolved_against_server_root(self) -> None: + client = make_client() + client.ensure_session() + assert client.session is not None + with patch.object( + client.session, "get", return_value=mock_response(200, b"file contents") + ) as mock_get: + result = client.fetch_upload("/user_uploads/1/file.pdf") + mock_get.assert_called_once_with( + "https://zulip.example.com/user_uploads/1/file.pdf", timeout=90.0 + ) + assert result == b"file contents" + + def test_custom_timeout(self) -> None: + client = make_client() + client.ensure_session() + assert client.session is not None + with patch.object( + client.session, "get", return_value=mock_response(200, b"file contents") + ) as mock_get: + client.fetch_upload("/user_uploads/1/file.pdf", timeout=5) + mock_get.assert_called_once_with( + "https://zulip.example.com/user_uploads/1/file.pdf", timeout=5.0 + ) + + def test_non_root_relative_path_rejected(self) -> None: + client = make_client() + with pytest.raises(ZulipError): + client.fetch_upload("user_uploads/1/file.pdf") + + def test_non_200_raises(self) -> None: + client = make_client() + client.ensure_session() + assert client.session is not None + with patch.object( + client.session, "get", return_value=mock_response(403, b"") + ), pytest.raises(ZulipError): + client.fetch_upload("/user_uploads/1/file.pdf") diff --git a/zulip/zulip/__init__.py b/zulip/zulip/__init__.py index 6d725a10b..6e1cac486 100644 --- a/zulip/zulip/__init__.py +++ b/zulip/zulip/__init__.py @@ -876,6 +876,56 @@ def upload_file(self, file: IO[Any]) -> Dict[str, Any]: """ return self.call_endpoint(url="user_uploads", files=[file]) + def fetch_upload(self, url_or_path: str, timeout: Optional[float] = None) -> bytes: + """ + Download an uploaded file, using API authentication. + + Accepts the `/user_uploads/...` path returned as the `url` + field by `upload_file()`, a `/user_uploads/temporary/...` + token URL, or an absolute `http(s)` URL on this Zulip server. + Unlike `call_endpoint()` (which always requests a `/api/v1/` + path), this method is not tied to the API prefix: + `GET /api/v1/user_uploads/...` returns a JSON temporary-access + URL rather than the file, so downloads have to go to the + unprefixed path. + + Absolute URLs on other origins are rejected, because the + authenticated session would otherwise send the bot's API key + to a third-party host. + + `timeout` is the request timeout in seconds; defaults to 90, + like long-polling requests. + + Returns the file contents as bytes. + """ + server_root = self.base_url.removesuffix("/api/") + server_origin = urllib.parse.urlsplit(server_root) + if url_or_path.startswith(("http://", "https://")): + parsed = urllib.parse.urlsplit(url_or_path) + if (parsed.scheme.lower(), parsed.netloc.lower()) != ( + server_origin.scheme.lower(), + server_origin.netloc.lower(), + ): + raise ZulipError( + f"fetch_upload() requires an absolute URL on {server_root!r}; refusing to send credentials elsewhere" + ) + url = url_or_path + elif url_or_path.startswith("/"): + # Absolute path on the Zulip server root, e.g. /user_uploads/... + url = server_root + url_or_path + else: + raise ZulipError( + f"fetch_upload() requires an absolute URL or a server-root-relative path, got {url_or_path!r}" + ) + self.ensure_session() + assert self.session is not None + res = self.session.get(url, timeout=timeout if timeout is not None else 90.0) + if res.status_code != 200: + raise ZulipError( + f"Failed to fetch upload {url_or_path!r}: server returned {res.status_code}" + ) + return res.content + def get_attachments(self) -> Dict[str, Any]: """ Example usage: