fix(bedrock-runtime): preserve images sent through the proxy (#4681)

* fix(bedrock-runtime): preserve inline images in proxy requests

* fix(bedrock-runtime): bound image validation allocations
This commit is contained in:
david lee authored and GitHub committed 2026-10-12 13:32:54 -04:00
1 parent 2cade5cd21
commit 3bdb07deac
3 files changed
+219 -7

No files matched your search

+27
View File
@@ -54,6 +54,33 @@ Useful for integration testing: applications that call Bedrock directly don't ne
## Examples
### Inline images through the proxy
Both `Converse` and `ConverseStream` forward inline `image` blocks as OpenAI
`image_url` data URLs, preserving the order of text and images in each message.
The supported image formats are `png`, `jpeg`, `gif`, and `webp`. The configured
backend and model must support image input. Text-only messages keep their
existing string representation.
```python
with open("image.png", "rb") as image:
response = client.converse(
modelId="your-mapped-model-id",
messages=[{"role": "user", "content": [
{"text": "Describe this image."},
{"image": {"format": "png", "source": {"bytes": image.read()}}},
]}],
)
```
Supply raw bytes to the AWS SDK; it performs the wire-level Base64 encoding.
The proxy rejects unsupported formats, malformed Base64, empty byte sources,
and S3 image sources with `400 ValidationException` before contacting the backend.
It does not decode image files or enforce model-specific image dimensions and
size limits; those remain the responsibility of the configured backend.
### Text requests
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
@@ -10,6 +10,7 @@ import org.jboss.logging.Logger;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -116,16 +117,16 @@ final class BedrockOpenAiTranslator {
}
/**
* A Bedrock message's content[] blocks map to OpenAI in three different ways:
* plain text accumulates into the message's content string, toolUse blocks become
* entries in that same message's tool_calls[], and toolResult blocks become their
* own standalone OpenAI message with role=tool — so one Bedrock message can expand
* into zero, one, or several OpenAI messages.
* Text-only messages retain string content; messages with images use ordered
* content parts. Tool uses stay on the message, while tool results become
* standalone OpenAI messages with role=tool.
*/
private static void translateMessage(ObjectMapper mapper, ArrayNode openAiMessages, JsonNode message) {
String role = message.path("role").asText("user");
JsonNode content = message.path("content");
StringBuilder text = new StringBuilder();
ArrayNode parts = mapper.createArrayNode();
boolean hasImages = false;
ArrayNode toolCalls = null;
if (content.isArray()) {
@@ -151,8 +152,15 @@ final class BedrockOpenAiTranslator {
function.put("arguments", toJsonString(mapper, toolUse.path("input")));
continue;
}
if (block.has("image")) {
parts.addObject().put("type", "image_url").putObject("image_url")
.put("url", imageDataUrl(block.path("image")));
hasImages = true;
continue;
}
String blockText = block.path("text").asText(null);
if (blockText != null) {
parts.addObject().put("type", "text").put("text", blockText);
if (text.length() > 0) {
text.append('\n');
}
@@ -161,10 +169,12 @@ final class BedrockOpenAiTranslator {
}
}
if (text.length() > 0 || toolCalls != null) {
if (text.length() > 0 || hasImages || toolCalls != null) {
ObjectNode msg = openAiMessages.addObject();
msg.put("role", role);
if (text.length() > 0) {
if (hasImages) {
msg.set("content", parts);
} else if (text.length() > 0) {
msg.put("content", text.toString());
} else {
// OpenAI's spec treats content as optional when tool_calls is present; some
@@ -177,6 +187,35 @@ final class BedrockOpenAiTranslator {
}
}
private static String imageDataUrl(JsonNode image) {
String format = image.path("format").asText("");
if (!List.of("png", "jpeg", "gif", "webp").contains(format)) {
throw new AwsException("ValidationException", "Image format must be png, jpeg, gif, or webp.", 400);
}
JsonNode source = image.path("source");
JsonNode bytes = source.path("bytes");
if (!source.isObject() || source.size() != 1 || !bytes.isTextual() || bytes.asText().isEmpty()) {
throw new AwsException("ValidationException",
"The proxy supports only inline image source.bytes; provide non-empty Base64 bytes, not S3 sources.",
400);
}
String encoded = bytes.asText();
try {
// Validate aligned quartets in bounded chunks instead of allocating the whole decoded image.
for (int offset = 0; offset < encoded.length();) {
int end = offset + Math.min(8192, encoded.length() - offset);
int decodedLength = Base64.getDecoder().decode(encoded.substring(offset, end)).length;
if (end < encoded.length() && decodedLength != (end - offset) / 4 * 3) {
throw new IllegalArgumentException("Image padding must occur only at the end.");
}
offset = end;
}
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Image source.bytes must contain valid Base64.", 400);
}
return "data:image/" + format + ";base64," + encoded;
}
private static String extractToolResultText(JsonNode toolResultContent) {
if (!toolResultContent.isArray()) {
return "";
@@ -11,10 +11,13 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
@@ -25,6 +28,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -102,6 +106,148 @@ class BedrockProxyIntegrationTest {
.body("usage.totalTokens", equalTo(16));
}
@ParameterizedTest
@ValueSource(strings = {"converse", "converse-stream"})
void imagesAndTextReachProxyInOriginalOrder(String operation) throws IOException {
nextResponseBody.set(operation.equals("converse")
? """
{"choices":[{"finish_reason":"stop","message":{"role":"assistant","content":"two images"}}]}
"""
: """
data: {"choices":[{"delta":{"content":"two images"},"finish_reason":"stop"}]}
data: [DONE]
""");
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"messages":[{"role":"user","content":[
{"text":"First"},
{"image":{"format":"png","source":{"bytes":"AQID"}}},
{"text":"Second"},
{"image":{"format":"jpeg","source":{"bytes":"BAUG"}}},
{"text":"Compare them"}
]}]}
""")
.when()
.post("/model/" + MAPPED_MODEL_ID + "/" + operation)
.then()
.statusCode(200);
JsonNode sent = objectMapper.readTree(received.get().body());
assertEquals(operation.equals("converse-stream"), sent.path("stream").asBoolean());
assertEquals(objectMapper.readTree("""
[{"type":"text","text":"First"},
{"type":"image_url","image_url":{"url":"data:image/png;base64,AQID"}},
{"type":"text","text":"Second"},
{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,BAUG"}},
{"type":"text","text":"Compare them"}]
"""), sent.path("messages").get(0).path("content"));
}
@ParameterizedTest
@ValueSource(strings = {"png", "jpeg", "gif", "webp"})
void imageOnlyMessagesReachProxy(String format) throws IOException {
nextResponseBody.set("""
{"choices":[{"finish_reason":"stop","message":{"content":"image received"}}]}
""");
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"messages":[{"role":"user","content":[
{"image":{"format":"%s","source":{"bytes":"AQID"}}}
]}]}
""".formatted(format))
.when()
.post("/model/" + MAPPED_MODEL_ID + "/converse")
.then()
.statusCode(200);
JsonNode messages = objectMapper.readTree(received.get().body()).path("messages");
assertEquals(1, messages.size());
assertEquals("data:image/" + format + ";base64,AQID",
messages.get(0).path("content").get(0).path("image_url").path("url").asText());
}
@ParameterizedTest
@ValueSource(ints = {6143, 6144, 6145, 12288})
void largerImagesKeepTheirExactEncoding(int byteCount) throws IOException {
nextResponseBody.set("""
{"choices":[{"finish_reason":"stop","message":{"content":"image received"}}]}
""");
String encoded = Base64.getEncoder().encodeToString(new byte[byteCount]);
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"messages":[{"role":"user","content":[
{"image":{"format":"png","source":{"bytes":"%s"}}}
]}]}
""".formatted(encoded))
.when()
.post("/model/" + MAPPED_MODEL_ID + "/converse")
.then()
.statusCode(200);
assertEquals("data:image/png;base64," + encoded, objectMapper.readTree(received.get().body())
.path("messages").get(0).path("content").get(0).path("image_url").path("url").asText());
}
@Test
void imagePaddingBeforeTheLastChunkIsRejected() {
nextResponseBody.set("""
{"choices":[{"finish_reason":"stop","message":{"content":"unexpected"}}]}
""");
String encoded = Base64.getEncoder().encodeToString(new byte[6143]) + "AQID";
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"messages":[{"role":"user","content":[
{"image":{"format":"png","source":{"bytes":"%s"}}}
]}]}
""".formatted(encoded))
.when()
.post("/model/" + MAPPED_MODEL_ID + "/converse")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
assertNull(received.get());
}
@ParameterizedTest
@ValueSource(strings = {
"null",
"{}",
"{\"format\":\"bmp\",\"source\":{\"bytes\":\"AQID\"}}",
"{\"format\":\"png\",\"source\":{\"s3Location\":{\"uri\":\"s3://bucket/image.png\"}}}",
"{\"format\":\"png\",\"source\":{\"bytes\":\"AQID\",\"s3Location\":{\"uri\":\"s3://bucket/image.png\"}}}",
"{\"format\":\"png\",\"source\":{\"bytes\":\"\"}}",
"{\"format\":\"png\",\"source\":{\"bytes\":123}}",
"{\"format\":\"png\",\"source\":{\"bytes\":\"not base64!\"}}"
})
void invalidImagesFailBeforeCallingProxy(String image) {
nextResponseBody.set("""
{"choices":[{"finish_reason":"stop","message":{"content":"unexpected"}}]}
""");
for (String operation : new String[]{"converse", "converse-stream"}) {
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"messages":[{"role":"user","content":[{"text":"Describe"},{"image":%s}]}]}
""".formatted(image))
.when()
.post("/model/" + MAPPED_MODEL_ID + "/" + operation)
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
assertNull(received.get());
}
}
@Test
void converse_toolCallsTranslateToToolUse() throws IOException {
nextResponseBody.set("""