fix(image-generation): validate provider download URLs before fetching (#8457)

* fix(image-generation): validate provider download URLs before fetching

The OpenAI-compatible image path fetched the provider-supplied data[].url
with requests.get and default redirects, so a compromised provider could point
the skill at a loopback, private or link-local service, or bounce a public URL
through a redirect. Require HTTPS on port 443, a public host, and re-validate
every redirect hop, mirroring the video-generation download guard.

* fix(image-generation): constrain provider redirects and download status

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
yetuge 2026-11-22 08:32:19 +08:00 committed by GitHub
parent 1c286b9336
commit 3de205c5ce
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 429 additions and 15 deletions

View File

@ -210,7 +210,11 @@ OpenAI-compatible settings:
Text-to-image calls use `POST {base_url}/images/generations`. Reference-image calls
use multipart `POST {base_url}/images/edits`; a relay may support generation without
supporting edits. Responses may contain base64 image data, a data URL, or a downloadable
URL. Aspect ratios map to `1024x1024`, `1536x1024`, or `1024x1536` unless
URL. Downloads require HTTPS on port 443 and a final 2xx response. The downloader
accepts public IPv4 literals and checks DNS hostname syntax without resolving names.
It revalidates the URL at every redirect.
Aspect ratios map to `1024x1024`, `1536x1024`, or `1024x1536` unless
`IMAGE_GENERATION_SIZE` is set. The output extension selects the API `output_format`:
`.jpg`/`.jpeg` uses `jpeg`, `.webp` uses `webp`, and all other extensions use `png`.
When `dall-e-2` or `dall-e-3` is configured instead, the request uses the model's
@ -218,6 +222,10 @@ supported dimensions and `response_format=b64_json`; DALL-E output files must us
`.png` extension. Reference-image editing with DALL-E models is not supported by this
skill; use the default GPT Image model for edits.
Gemini, MiniMax, and OpenAI-compatible generation requests follow up to five
HTTP 307 or 308 redirects on the same scheme, host, and port. These redirects
preserve the POST body, including reference images.
MiniMax optional overrides: `MINIMAX_API_HOST` (default `https://api.minimaxi.com`),
`MINIMAX_IMAGE_MODEL` (default `image-01`). Reference images are sent as the MiniMax
`subject_reference` character image. The CLI and `--prompt-file` / `--reference-images`

View File

@ -1,13 +1,19 @@
import base64
from contextlib import ExitStack
import ipaddress
import json
import os
import re
import sys
from typing import BinaryIO
from urllib.parse import urljoin, urlsplit
import requests
MINIMAX_DEFAULT_HOST = "https://api.minimaxi.com"
OPENAI_DEFAULT_BASE_URL = "https://api.openai.com/v1"
OPENAI_DEFAULT_MODEL = "gpt-image-2.5-flare"
MAX_REDIRECTS = 5
# MiniMax image-01 caps the prompt at 1500 characters and rejects longer requests
# with a generic "invalid params" error, so validate before calling the API.
MINIMAX_PROMPT_MAX_CHARS = 1500
@ -131,6 +137,106 @@ def _ensure_output_dir(output_file: str) -> None:
os.makedirs(output_dir, exist_ok=True)
def _download_host(url: str) -> str:
"""Validate one provider-supplied image URL before fetching it.
Accept HTTPS on port 443 with a DNS hostname or a public IPv4 literal.
Check DNS hostname syntax here and leave DNS resolution to the transport.
The caller validates each redirect before following it.
"""
if not isinstance(url, str) or re.search(r"[\x00-\x20\x7f\\]", url):
raise ValueError("Invalid image download URL")
parsed = urlsplit(url)
host = parsed.hostname
if (
parsed.scheme != "https"
or not host
or parsed.netloc.lower() not in {host, f"{host}:443"}
):
raise ValueError(
"Image downloads require an HTTPS host on port 443 without user information"
)
try:
address = ipaddress.IPv4Address(host)
except ValueError:
if host == "localhost" or not re.fullmatch(
r"(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]*", host
):
raise ValueError("Invalid image download hostname")
else:
if not address.is_global or address.is_multicast:
raise ValueError(f"Image download host {host!r} is not a public address")
return host
def _download_image(url: str) -> bytes:
"""Download a provider image URL, validating the target and every redirect."""
for _ in range(MAX_REDIRECTS + 1):
_download_host(url)
response = requests.get(url, timeout=120, allow_redirects=False)
if response.status_code in {301, 302, 303, 307, 308}:
location = (getattr(response, "headers", None) or {}).get("Location")
if not location:
raise ValueError("Image download redirect has no destination")
url = urljoin(url, location)
continue
_require_success(response)
return response.content
raise ValueError("Too many image download redirects")
def _require_success(response: requests.Response) -> None:
response.raise_for_status()
if not 200 <= response.status_code < 300:
raise ValueError(
f"Unexpected HTTP status {response.status_code} from image provider"
)
def _api_origin(url: str) -> tuple[str, str, int]:
parsed = urlsplit(url)
if (
parsed.scheme not in {"http", "https"}
or not parsed.hostname
or parsed.username is not None
or parsed.password is not None
):
raise ValueError("Invalid image generation API URL")
port = parsed.port
if port is None:
port = 443 if parsed.scheme == "https" else 80
return parsed.scheme, parsed.hostname, port
def _post_image(
url: str,
*,
files: list[tuple[str, tuple[str, BinaryIO, str]]] | None = None,
**kwargs,
) -> requests.Response:
"""Preserve the POST body and credentials only on same-origin redirects."""
origin = _api_origin(url)
for hop in range(MAX_REDIRECTS + 1):
response = requests.post(url, files=files, allow_redirects=False, **kwargs)
if response.status_code not in {307, 308}:
_require_success(response)
return response
if hop == MAX_REDIRECTS:
break
location = response.headers.get("Location")
if not location:
raise ValueError("Image generation redirect has no destination")
if re.search(r"[\x00-\x20\x7f\\]", location):
raise ValueError("Invalid image generation redirect destination")
destination = urljoin(url, location)
if _api_origin(destination) != origin:
raise ValueError("Image generation redirect points to a different origin")
url = destination
for _, (_, file, _) in files or ():
file.seek(0)
raise ValueError("Too many image generation redirects")
def _minimax_prompt(raw: str) -> str:
"""Extract the single text prompt MiniMax image-01 expects.
@ -181,7 +287,7 @@ def _generate_image_minimax(
{"type": "character", "image_file": _to_data_url(p)}
for p in reference_images
]
response = requests.post(
response = _post_image(
f"{_minimax_host()}/v1/image_generation",
headers={
"Authorization": f"Bearer {bearer_value}",
@ -190,7 +296,6 @@ def _generate_image_minimax(
json=body,
timeout=60,
)
response.raise_for_status()
payload = response.json()
_check_base_resp(payload)
images = (payload.get("data") or {}).get("image_base64") or []
@ -226,7 +331,7 @@ def _generate_image_gemini(
bearer_value = os.getenv("GEMINI_API_KEY")
if not bearer_value:
return "GEMINI_API_KEY is not set"
response = requests.post(
response = _post_image(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent",
headers={"x-goog-api-key": bearer_value, "Content-Type": "application/json"},
json={
@ -234,7 +339,6 @@ def _generate_image_gemini(
"contents": [{"parts": [*parts, {"text": prompt}]}],
},
)
response.raise_for_status()
data = response.json()
response_parts: list[dict] = data["candidates"][0]["content"]["parts"]
image_parts = [part for part in response_parts if part.get("inlineData", False)]
@ -267,9 +371,7 @@ def _write_openai_image(payload: dict, output_file: str) -> str:
_, encoded = image_url.split(",", 1)
image_bytes = base64.b64decode(encoded)
else:
download = requests.get(image_url, timeout=120)
download.raise_for_status()
image_bytes = download.content
image_bytes = _download_image(image_url)
_ensure_output_dir(output_file)
with open(output_file, "wb") as f:
@ -319,17 +421,16 @@ def _generate_image_openai(
)
for path in reference_images
]
response = requests.post(
response = _post_image(
url, headers=headers, data=fields, files=files, timeout=180
)
else:
response = requests.post(
response = _post_image(
url,
headers={**headers, "Content-Type": "application/json"},
json=fields,
timeout=180,
)
response.raise_for_status()
return _write_openai_image(response.json(), output_file)
@ -398,4 +499,5 @@ if __name__ == "__main__":
)
)
except Exception as e:
print(f"Error while generating image: {e}")
print(f"Error while generating image: {e}", file=sys.stderr)
sys.exit(1)

View File

@ -36,10 +36,11 @@ def load(skill_name: str):
class FakeResp:
"""Minimal stand-in for requests.Response."""
def __init__(self, json_data=None, content=b"", status_code=200):
def __init__(self, json_data=None, content=b"", status_code=200, headers=None):
self._json = json_data if json_data is not None else {}
self.content = content
self.status_code = status_code
self.headers = headers or {}
def raise_for_status(self):
if self.status_code >= 400:

View File

@ -1,4 +1,5 @@
import base64
import runpy
import sys
from pathlib import Path
@ -269,7 +270,10 @@ def test_openai_compatible_generation_writes_base64(monkeypatch, tmp_path):
assert "Successfully generated image" in result
def test_openai_compatible_generation_downloads_url(monkeypatch, tmp_path):
@pytest.mark.parametrize("download_host", ["cdn.example", "8.8.8.8"])
def test_openai_compatible_generation_downloads_url(
monkeypatch, tmp_path, download_host
):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai-compatible")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
@ -277,7 +281,7 @@ def test_openai_compatible_generation_downloads_url(monkeypatch, tmp_path):
img.requests,
"post",
lambda *args, **kwargs: FakeResp(
{"data": [{"url": "https://cdn.example/image.png"}]}
{"data": [{"url": f"https://{download_host}/image.png"}]}
),
)
monkeypatch.setattr(
@ -294,6 +298,305 @@ def test_openai_compatible_generation_downloads_url(monkeypatch, tmp_path):
assert output_file.read_bytes() == b"downloaded-image"
@pytest.mark.parametrize(
"url",
[
"http://cdn.example/image.png",
"https://user@cdn.example/image.png",
"https://cdn.example:8443/image.png",
"https://127.0.0.1/image.png",
"https://169.254.169.254/latest/meta-data",
"https://10.0.0.1/image.png",
"https://localhost/image.png",
"https://224.0.0.1/image.png",
"https://[2606:4700::1111]/image.png",
"https://cdn.example\\@evil.example/image.png",
],
ids=[
"plain-http",
"userinfo",
"non-443-port",
"loopback-ip",
"link-local-ip",
"private-ip",
"localhost-name",
"multicast-ip",
"ipv6-literal",
"backslash-host",
],
)
def test_openai_compatible_download_rejects_unsafe_urls(monkeypatch, tmp_path, url):
"""A provider-supplied URL is untrusted: unsafe targets must not be fetched."""
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai-compatible")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setattr(
img.requests,
"post",
lambda *args, **kwargs: FakeResp({"data": [{"url": url}]}),
)
def fail_get(*args, **kwargs):
raise AssertionError("an unsafe download URL must not be fetched")
monkeypatch.setattr(img.requests, "get", fail_get)
prompt_file = tmp_path / "prompt.txt"
prompt_file.write_text("a red deer", encoding="utf-8")
with pytest.raises(ValueError):
img.generate_image(str(prompt_file), [], str(tmp_path / "image.png"), "1:1")
def test_openai_compatible_download_revalidates_each_redirect(monkeypatch, tmp_path):
"""A public host must not be able to redirect the fetch to an internal one."""
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai-compatible")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setattr(
img.requests,
"post",
lambda *args, **kwargs: FakeResp(
{"data": [{"url": "https://cdn.example/image.png"}]}
),
)
monkeypatch.setattr(
img.requests,
"get",
lambda *args, **kwargs: FakeResp(
status_code=302,
headers={"Location": "https://169.254.169.254/latest/meta-data"},
),
)
prompt_file = tmp_path / "prompt.txt"
prompt_file.write_text("a red deer", encoding="utf-8")
with pytest.raises(ValueError, match="not a public address"):
img.generate_image(str(prompt_file), [], str(tmp_path / "image.png"), "1:1")
def test_openai_compatible_download_follows_a_valid_redirect(monkeypatch, tmp_path):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai-compatible")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setattr(
img.requests,
"post",
lambda *args, **kwargs: FakeResp(
{"data": [{"url": "https://cdn.example/image.png"}]}
),
)
responses = iter(
[
FakeResp(
status_code=302, headers={"Location": "https://cdn2.example/image.png"}
),
FakeResp(content=b"redirected-image"),
]
)
monkeypatch.setattr(img.requests, "get", lambda *args, **kwargs: next(responses))
prompt_file = tmp_path / "prompt.txt"
prompt_file.write_text("a red deer", encoding="utf-8")
output_file = tmp_path / "image.png"
img.generate_image(str(prompt_file), [], str(output_file), "1:1")
assert output_file.read_bytes() == b"redirected-image"
def test_openai_compatible_download_rejects_a_redirect_without_location(
monkeypatch, tmp_path
):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai-compatible")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setattr(
img.requests,
"post",
lambda *args, **kwargs: FakeResp(
{"data": [{"url": "https://cdn.example/image.png"}]}
),
)
monkeypatch.setattr(
img.requests,
"get",
lambda *args, **kwargs: FakeResp(status_code=302),
)
prompt_file = tmp_path / "prompt.txt"
prompt_file.write_text("a red deer", encoding="utf-8")
with pytest.raises(ValueError, match="redirect has no destination"):
img.generate_image(str(prompt_file), [], str(tmp_path / "image.png"), "1:1")
@pytest.mark.parametrize("status", [300, 304])
@pytest.mark.parametrize("existing", [False, True])
def test_openai_compatible_download_requires_2xx(
monkeypatch, tmp_path, status, existing
):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setattr(
img.requests,
"post",
lambda *args, **kwargs: FakeResp(
{"data": [{"url": "https://cdn.example/image.png"}]}
),
)
monkeypatch.setattr(
img.requests,
"get",
lambda *args, **kwargs: FakeResp(status_code=status),
)
prompt = tmp_path / "prompt.txt"
prompt.write_text("a red deer", encoding="utf-8")
output = tmp_path / "image.png"
if existing:
output.write_bytes(b"previous image")
with pytest.raises(ValueError, match=f"Unexpected HTTP status {status}"):
img.generate_image(str(prompt), [], str(output))
if existing:
assert output.read_bytes() == b"previous image"
else:
assert not output.exists()
@pytest.mark.parametrize(
("provider", "key", "edit"),
[
("gemini", "GEMINI_API_KEY", False),
("minimax", "MINIMAX_API_KEY", False),
("openai", "IMAGE_GENERATION_API_KEY", False),
("openai", "IMAGE_GENERATION_API_KEY", True),
],
)
def test_generation_rejects_cross_origin_post_redirect(
monkeypatch, tmp_path, provider, key, edit
):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", provider)
monkeypatch.setenv(key, "offline-key")
calls = []
def fake_post(url, **kwargs):
calls.append(url)
assert kwargs.get("allow_redirects") is False
return FakeResp(
status_code=307, headers={"Location": "https://other.example/generate"}
)
monkeypatch.setattr(img.requests, "post", fake_post)
prompt = tmp_path / "prompt.txt"
prompt.write_text("a red deer", encoding="utf-8")
reference = tmp_path / "reference.png"
reference.write_bytes(b"reference image")
output = tmp_path / "image.png"
with pytest.raises(ValueError, match="different origin"):
img.generate_image(str(prompt), [str(reference)] if edit else [], str(output))
assert len(calls) == 1
assert not output.exists()
@pytest.mark.parametrize(("status", "edit"), [(307, False), (308, True)])
def test_openai_replays_same_origin_post_with_the_full_body(
monkeypatch, tmp_path, status, edit
):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setenv("IMAGE_GENERATION_BASE_URL", "https://models.example/v1")
sent = []
def fake_post(url, **kwargs):
assert kwargs.get("allow_redirects") is False
if edit:
fields = kwargs["data"]
content = kwargs["files"][0][1][1].read()
else:
fields = kwargs["json"]
content = None
sent.append((url, dict(kwargs["headers"]), dict(fields), content))
if len(sent) == 1:
return FakeResp(status_code=status, headers={"Location": url + "/"})
return FakeResp({"data": [{"b64_json": "aW1hZ2U="}]})
monkeypatch.setattr(img.requests, "post", fake_post)
prompt = tmp_path / "prompt.txt"
prompt.write_text("a red deer", encoding="utf-8")
reference = tmp_path / "reference.png"
reference.write_bytes(b"reference image")
output = tmp_path / "image.png"
img.generate_image(str(prompt), [str(reference)] if edit else [], str(output))
assert len(sent) == 2
assert sent[1][0] == sent[0][0] + "/"
assert sent[1][1:] == sent[0][1:]
assert sent[0][1]["Authorization"] == "Bearer image-key"
assert sent[0][3] == (b"reference image" if edit else None)
assert output.read_bytes() == b"image"
@pytest.mark.parametrize(
("status", "location", "message"),
[
(302, "/generate", "Unexpected HTTP status 302"),
(307, None, "redirect has no destination"),
(307, "http://models.example/generate", "different origin"),
(308, "https://models.example:8443/generate", "different origin"),
(308, "/generate", "Too many image generation redirects"),
],
)
def test_generation_post_redirects_are_limited(
monkeypatch, tmp_path, status, location, message
):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setenv("IMAGE_GENERATION_BASE_URL", "https://models.example/v1")
calls = []
def fake_post(url, **kwargs):
calls.append(url)
return FakeResp(
status_code=status, headers={"Location": location} if location else {}
)
monkeypatch.setattr(img.requests, "post", fake_post)
prompt = tmp_path / "prompt.txt"
prompt.write_text("a red deer", encoding="utf-8")
with pytest.raises(ValueError, match=message):
img.generate_image(str(prompt), [], str(tmp_path / "image.png"))
assert len(calls) == (6 if location == "/generate" and status == 308 else 1)
def test_cli_failed_download_exits_nonzero(monkeypatch, tmp_path, capsys):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")
monkeypatch.setattr(
img.requests,
"post",
lambda *args, **kwargs: FakeResp(
{"data": [{"url": "https://cdn.example/image.png"}]}
),
)
monkeypatch.setattr(
img.requests, "get", lambda *args, **kwargs: FakeResp(status_code=304)
)
prompt = tmp_path / "prompt.txt"
prompt.write_text("a red deer", encoding="utf-8")
output = tmp_path / "image.png"
monkeypatch.setattr(
sys,
"argv",
[img.__file__, "--prompt-file", str(prompt), "--output-file", str(output)],
)
with pytest.raises(SystemExit) as error:
runpy.run_path(img.__file__, run_name="__main__")
assert error.value.code == 1
captured = capsys.readouterr()
assert "Unexpected HTTP status 304" in captured.err
assert not captured.out
assert not output.exists()
def test_openai_compatible_dall_e_uses_response_format(monkeypatch, tmp_path):
monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai")
monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key")