serve: /v1/responses refuses a file image from another origin (#553); a bad data: URL or unreadable file is a 400 (from #582)

This commit is contained in:
Niko1221 committed 2026-10-05 13:16:53 +02:00
1 parent 58dd26b9f2
commit 264e81265b
3 files changed
+40 -2

No files matched your search

+12 -2
View File
@@ -1325,7 +1325,10 @@ class Vision:
@staticmethod
def load(source: str) -> bytes:
if source.startswith("data:"):
return base64.b64decode(source.split(",", 1)[1])
try:
return base64.b64decode(source.split(",", 1)[1])
except (IndexError, ValueError) as e: # no comma, or not base64
raise ValueError(f"the image's data: URL could not be read ({e})") from None
if source.startswith(("http://", "https://")):
return Vision.download(source)
path = source[7:] if source.startswith("file://") else source
@@ -1336,7 +1339,10 @@ class Vision:
raise ValueError("an image file must be on this computer: network paths (\\\\host\\share, //host/share, "
"file://host/...) are not read")
if path and os.path.isfile(path):
return Path(path).read_bytes()
try:
return Path(path).read_bytes()
except OSError as e:
raise ValueError(f"the image could not be read from {path} ({e})") from None
raise ValueError("an image must be a data: URL, an http(s) URL or a local file path")
@staticmethod
@@ -3559,6 +3565,10 @@ def make_handler(svc: Service):
messages = responses_api.input_messages(req)
tools, names, skipped = responses_api.request_tools(req)
kw = responses_api.template_kwargs(req, svc.shared)
try:
self._no_local_images(messages) # as on the chat route: no file read for a foreign page
except ValueError as e:
raise ResponsesError(str(e), "input") from None
try:
messages, validator = prepare_format(responses_api.text_format(req), messages)
except ValueError as e:
+16
View File
@@ -264,6 +264,22 @@ class OverHttp(Server):
code, r = self.post({"model": "m", "input": "hi"}, headers={"Origin": "https://evil.example.com"})
self.assertEqual(code, 403)
def test_a_foreign_page_cannot_name_a_file_as_an_image(self):
"""#553: the chat routes refuse a file image from another origin; so does /v1/responses."""
def body(src):
return {"model": "m", "input": [{"role": "user", "content": [
{"type": "input_text", "text": "what is it?"}, {"type": "input_image", "image_url": src}]}]}
self.svc.cors_origins = ["*"] # a page cors_origins lets in may send JSON, not name a file
for src in (r"\\host\share\x.png", "/etc/passwd", "file:///C:/x.png"):
with self.subTest(src=src):
code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"})
self.assertEqual(code, 400, r)
self.assertIn("another origin", r["error"]["message"])
# data: and http(s) are the page's own to send: not refused by this check (no vision here, so a 400 of another kind)
for src in ("data:image/png;base64,iVBORw0KGgo=", "https://example.com/x.png"):
code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"})
self.assertNotIn("another origin", json.dumps(r))
def test_json_schema_text_format(self):
self.engine.scripts = [self.tok.encode("</think>\n\n{\"n\": 3}<|im_end|>", parse_special=True)]
self.engine.script = self.engine.scripts[0]
+12
View File
@@ -2713,6 +2713,18 @@ class ImageSources(unittest.TestCase):
with self.subTest(src=src):
self.assertEqual(Vision.load(src), b"\x89PNG\r\n\x1a\n")
def test_unreadable_sources_are_a_value_error(self):
"""From #582: a bad data: URL or an unreadable file is a 400, not a dropped connection."""
from serve.server import Vision
for src in ("data:image/png", "data:image/png;base64,abcde"):
with self.subTest(src=src), self.assertRaisesRegex(ValueError, "data: URL could not be read"):
Vision.load(src)
with tempfile.TemporaryDirectory() as d:
f = Path(d) / "x.png"
f.write_bytes(b"x")
with mock.patch.object(Path, "read_bytes", side_effect=PermissionError("denied")), self.assertRaisesRegex(ValueError, "could not be read from"):
Vision.load(str(f))
def test_a_url_is_read_up_to_the_cap(self):
import http.server
import serve.server as server