Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/docgen/ai_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import random
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from dataclasses import dataclass
Expand Down Expand Up @@ -609,8 +610,17 @@ def _call() -> Any:
return _openai_stt_payload(result)


def _require_http_url(url: str) -> None:
"""Image fetches are http(s) only. ``file:`` and other schemes are refused."""
scheme = urllib.parse.urlparse(url).scheme.lower()
if scheme not in ("http", "https"):
shown = scheme or "an empty scheme"
raise AIError(f"image URL must use http or https, not {shown!r}")


def fetch_url_bytes(url: str, *, timeout: int = 120) -> bytes:
"""GET ``url`` and return the response body (image CDN / signed URLs)."""
_require_http_url(url)
last_exc: BaseException | None = None
for attempt in range(_MAX_HTTP_ATTEMPTS):
req = urllib.request.Request(url, method="GET")
Expand Down
9 changes: 9 additions & 0 deletions tests/test_ai_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,15 @@ def _urlopen(req: object, timeout: int = 120) -> _Resp:
assert calls["n"] == 2


def test_fetch_url_bytes_refuses_file_scheme() -> None:
from docgen.ai_client import fetch_url_bytes

with patch("docgen.ai_client.urllib.request.urlopen") as urlopen:
with pytest.raises(AIError, match="http or https"):
fetch_url_bytes("file:///etc/passwd")
urlopen.assert_not_called()


def test_chat_retries_rate_limit(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clear_ai_env: None
) -> None:
Expand Down
Loading