Repository navigation
fix(router): refuse image bytes that are not an image (AI-3163) - #2679
Conversation
kanat
left a comment
There was a problem hiding this comment.
Text review: 4 unclear of 8
This is a read of the wording only, by a reader who had not seen the code. Two items a caller reads need a change; the other two are small.
- T1.1 (Should fix) error message,
acceleration/internal/llm/content.go:201. - T1.2 (Should fix)
invalid_imageentry in thecodedescription,acceleration/internal/api/apierror.go:250. Changing it means regeneratingacceleration/api/openapi.yamland every client (see "Regenerate the HTTP layer" inacceleration/README.md). - T1.3 (Nit) PR opening: it is only the ticket id. Suggested: "The router sent image bytes that were not an image to the model provider, which failed there with an error the caller could not act on. It now checks the bytes when the request arrives and answers 400
invalid_image, and it labels valid images by their real format instead of the label the caller sent." - T1.4 (Nit) comment,
acceleration/internal/llm/content.go:183-185.
c450b95 to
b098aac
Compare
|
T1.3: the PR opening now has your suggested text, under the issue id. |
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Security review, round 1, of the current head (the wording commit on top changes only the message). I found no hole. Every place that takes image bytes or a data URI now runs the same check: the responses, runs and session respond endpoints, the session socket's respond and tool_result, the stream socket's frame and tool_result, and hosted tool results. Images sent by URL were already checked by their bytes when the router fetched them, and that path is unchanged.
What I checked, on this branch merged onto current main:
- SVG, HTML (also with leading whitespace), PDF, ZIP, GZIP, BMP and plain text are refused under an image label and under no label. Before this PR, HTML labelled
image/pngwent through, since only the label was checked. - The check reads at most the first 512 bytes. A 10 MiB image costs about the same as a 1 KiB one, and nothing is decoded.
- The refusal is one fixed sentence. It does not repeat the caller's bytes or the type the bytes were detected as.
- A file that starts with a real image signature and carries something else after it still passes, labelled as that image format. A prefix check cannot tell more, and the caller's own label is never sent on, so I am fine with it.
- Mutations: turning off the refusal or the relabel, or dropping the
invalid_imagecode on the responses endpoint or the session socket, each fails the PR's tests.
Two Nits below. Neither is a security hole.
b098aac to
9e2355b
Compare
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Main review, round 1, of c450b955 merged onto current main (1bcaf50a). The head moved to b098aac4 during the review. That commit is a rebase plus the wording change, and streamws.go is unchanged, so R1.1 still applies there.
The sniff is sound. Real PNG, JPEG and GIF files from Go's encoders and real WebP files (lossy, lossless and extended) pass under any label and are relabelled. PDF, ZIP, HEIC, AVIF, SVG, TIFF, JSON, HTML and WAV bytes are refused. http.DetectContentType reads at most 512 bytes and decodes nothing. Images given by URL are unchanged. One entry point does not answer like the others: R1.1, which decides the verdict.
[Should fix] R1.1 acceleration/internal/api/streamws.go:742 and :748: on the stream socket, a frame or a tool_result carrying bytes that are not an image gets an error frame with the message and no code. socket.failed (streamws.go:1338) adds a code only for money refusals, so changing invalidRequest to invalidContent there changes nothing on the wire. The PR body says the socket error frame has code: invalid_image for both sockets. The security review raised this as S1.1 (Nit); I rate it Should fix because it is the one entry point that does not refuse the same way. The current head b098aac4 does not fix it. Fix: s.frame(withRefusal(frame{"type": "error", "error": store.RedactLogText(refusalText(err))}, err)) in socket.failed. With that change all of StreamsSuite passes, including the two rows below, which fail on the head:
StreamsSuite: send{"type":"frame","image_url":"data:image/jpeg;base64,<an HTML page>"}and expect an error frame withcodeinvalid_image.StreamsSuite: afters.calling(conversation, model, "c1"), send atool_resultforc1whoseoutputis[{"type":"image_url","image_url":{"url":<the same page>}}]and expectcodeinvalid_image.
[Should fix, follow-up] R1.3 .claude/skills/sdk/SKILL.md:717 still describes a run's image refusals as invalid_request or image_unavailable. A data URI whose bytes are not an image is now invalid_image. Add it to that line.
[Nit] R1.6 acceleration/internal/api/runs.go:258: fetchImage repeats the list of formats that llm.imageFormat now owns. One owner would keep the two lists from drifting apart.
Checked and sound: go run ./cmd/openapi and generated.sh leave no drift. go vet -tags integration is clean. The llm, llmrouter, api, session, agent and conversation unit suites pass with -race, and so do the touched integration tests. The changed error doc only adds a code and removes nothing, so no CHANGELOG line is needed. CI on the new head had no failures when I read it; go and the integration jobs were still pending. Mutations: 22 checked, 8 survived. A10 is equivalent, A7 and A8 are R1.1, and the other five have rows in R1.2 and R1.4.
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta round 2, head 9e2355b5 (already on current main, 9a5d84db). The blocking finding from round 1 is fixed, and I found nothing new that blocks.
Prior findings
- R1.1 / S1.1, fixed. On the stream socket, a
frameand atool_resultcarrying an HTML page labelleddata:image/jpegnow both answer anerrorframe withcode: invalid_imageand the new message. I ran both rows (theframerow is the PR's own test, thetool_resultrow is mine). Reverting thesocket.failedbranch (streamws.go:1343) fails the PR'sTestAFrameThatIsNotAnImageIsRefusedAsAnInvalidImageand both of my rows. - S1.2, fixed. The logged label goes through
labelPrefix(40 bytes). Dropping the cut failsTestALongLabelIsLoggedCutShortAndWhole. - T1.1, fixed. The message now says what to do, and the two tests that asserted the old text are updated.
- T1.2, fixed. The
invalid_imageentry in thecodedoc: no longer says "label" or "not sent to a model", and ends with "Send the image in one of those formats".go run ./cmd/openapileaves no diff, and the repo'sgenerated.shreports that every generated file matches its source (the openapi, Go, JS, Rust, .NET and Python copies carry the new text). - R1.2 and R1.3 stay follow-ups. R1.4 to R1.6 stay Nits.
Checked on the head
gofmtandgo vet -tags integrationare clean forinternal/apiandinternal/llm.go test -racefor./internal/llm/...,llmrouter,sessionandapipasses. The integration suites ResponsesAsked, SessionEvents, Runs and Streams pass for every image test. ThreeTestResponsesAskedSuitevideo tests fail on my machine only because it has noffmpeg("this deployment cannot read video"). They do not touch images.- CI (read once): everything that finished passed.
go,integration (store)andswiftwere still pending.
New findings, none block
[Nit, follow-up] acceleration/internal/api/streamws.go:748 The stream socket's tool_result call site is not pinned. Changing line 748 to invalidRequest(err.Error()) passes every test in StreamsSuite (the frame call site at line 742 is pinned). Row for StreamsSuite, which fails under that change and passes on the head:
conversation, model := s.converse(frame{"target": "stub/stub-sts"})
s.calling(conversation, model, "c1")
// tool_result for c1 with output [{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,<an HTML page>"}}]
// expect an error frame with code codeInvalidImage[Nit] acceleration/internal/llm/content_test.go TestALongLabelIsLoggedCutShortAndWhole does not test a cut inside a rune. strings.Repeat("é", 100) has a rune start at byte 40, so the loop in labelPrefix never runs, and removing it still passes. With "a" + strings.Repeat("é", 100), expecting a valid string of length 39, the test fails without the loop and passes with it.
kanat
left a comment
There was a problem hiding this comment.
Approving on the reviewers' GO. The delta review confirms R1.1/S1.1 (the stream socket answers invalid_image), S1.2 (the logged label is cut short), and T1.1 and T1.2 (the wording and regenerated clients have no drift). The call-site rows and the sdk skill line are follow-ups.
9e2355b to
16968ed
Compare
|
Main review round 1 (NO-GO on c450b95), answered on head 16968ed:
Tests: |
|
@kanat please approve head 16968ed if you are OK with it. Your approval is on 9e2355b. The changes after it are:
Please also resolve the threads you accept. |
The router checked only the label of an image. Bytes that are not an image, such as an HTML page sent as image/jpeg, went to the provider, which refused them. ImagePart.Validate now reads the bytes. Bytes that are not JPEG, PNG, WebP or GIF fail with llm.ErrInvalidImage. The API answers it with a 400 and the code invalid_image, on HTTP and on the sockets. A real image under a wrong label is sent with its real format. Regenerate openapi.yaml and the clients for the new code in the code list.
16968ed to
14ba6b1
Compare
|
@kanat main moved and the PR had conflicts, so I rebased it onto main (f3a383b). New head 14ba6b1. The conflicts were only in |
kanat
left a comment
There was a problem hiding this comment.
Approving again after the rebase onto main. The PR's own change matches the version approved earlier; only the generated error-code text was rewrapped.
AI-3163
The router sent image bytes that were not an image to the model provider, which failed there with an error the caller could not act on. It now checks the bytes when the request arrives and answers 400
invalid_image, and it labels valid images by their real format instead of the label the caller sent.Problem
A client can send bytes that are not an image under an image label, for example an HTML page as
data:image/jpeg. The router checked only the label. It sent the bytes to the model provider, and the provider refused them. The caller got only "something went wrong", after a provider call that could not work.The second part of the issue, the raw provider error with its URL, is already fixed on
main(#2249). Error frames and stored turns no longer carry the provider's text.The fix
llm.ImagePart.Validatereads the first bytes of an image withhttp.DetectContentType.llm.ErrInvalidImage. The label does not matter.image/jpeg, a JPEG labelledimage/heic) is accepted. The router sends its real format to the provider. A debug line records the change, at most once a minute.ErrInvalidImagewith a 400 and the new codeinvalid_image. This applies toPOST /v1/agents/sessions/{id}/responses, session respond, runs, the session socket (respondandtool_result) and the stream socket (frameandtool_result). The socket error frame hascode: invalid_image.image_unavailable).sequenceDiagram participant Client participant Router participant Provider Client->>Router: HTML as image/jpeg Note over Router: reads bytes: not an image Router-->>Client: 400 invalid_image Note over Provider: no callThe
invalid_imagecode is added to the documented code list.openapi.yamland the Go, Python, Kotlin, JS, .NET and Rust clients are regenerated. Swift, PHP, Ruby and Dart do not carry that text.Behavior change
Before, a label outside JPEG, PNG, WebP and GIF was refused with
invalid_request. Now the router reads the bytes and refuses non-images withinvalid_image. A client that branches oninvalid_requestfor a bad image sees a new code.Tests
internal/llm/content_test.go: non-image bytes are refused, a wrong label or no label is replaced by the real format, each accepted format passes, a BMP is refused.ResponsesAskedSuite: an HTML page asimage/jpegis a 400invalid_imageand the model is not asked. A PNG labelledimage/jpegreaches the model asimage/png.SessionEventsSuite: the same page on the socket gives an error frame withcode: invalid_image.[]byte{1},"png") now use real format headers.Commands:
Clients that put a fixed
image/jpeglabel on imagesThe router now sends the real format, so none of these break. The ones that encode to JPEG first send the right label.
sdks/go/stream/router.go:646image/jpegsdks/js/src/voice-session.ts:576,sdks/js/src/session.ts:1115canvas.toBlobsdks/swift/core/Sources/StreamAgents/AgentSession.swift:690$0.jpeg)sdks/kotlin/core/.../AgentSession.kt:592it.jpeg)sdks/dart/stream_agents/lib/src/core/agent_session.dart:747picture.jpeg)examples/voice_agents/*/photos.*,Photos.*(crew, react_native, android, flutter, react, swift)plugins/{gemini,huggingface,nvidia,openai}VLMssdks/python/vision_agents/core/messaging.py:45