mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(apigateway): match Content-Type case-insensitively in Lambda proxy responses (#2150)
* fix(apigateway): match Content-Type case-insensitively in Lambda proxy responses
buildProxyResponse re-derives the response Content-Type with an exact-case
JSON field lookup (node.path("headers").path("Content-Type")), even though
the header-copy loop just above it already handles arbitrary casing
correctly by iterating every field. Lambda proxy integrations commonly
return lowercased header names - e.g. the AWS Lambda Web Adapter sidecar
returns "content-type", not "Content-Type" - which the exact-case lookup
misses, silently falling back to "application/json" regardless of what the
Lambda actually set. HTTP header names are case-insensitive on the wire
(RFC 7230 §3.2), so this affected every response whose handler didn't
happen to use the exact AWS-console casing, most visibly every RFC 9457
application/problem+json error response.
Confirmed via debug logging of the raw Lambda payload before fixing:
{"statusCode":404,"headers":{"content-type":"application/problem+json",...
Replaces the exact-case lookup with a case-insensitive scan
(findHeaderIgnoreCase) reusing the already-fetched headers node.
* test(apigateway): cover case-insensitive Content-Type matching in proxy responses
Widens buildProxyResponse to package-private (matching dispatch()'s existing
visibility, which exists for the same reason: direct unit testing from
ApiGatewayExecuteControllerTest without standing up a full Lambda invoke).
Covers lowercase, exact-case, and mixed-case Content-Type header names, plus
the pre-existing default-to-application/json behavior when no Content-Type
header is present at all.
Verified by reverting findHeaderIgnoreCase to the old exact-case lookup:
the lowercase and mixed-case tests fail (2 of 13) while the exact-case and
no-header tests keep passing, confirming none of the four are vacuous.
* fix(apigateway): preserve JSON-null Content-Type fallback in findHeaderIgnoreCase
findHeaderIgnoreCase called JsonNode#asText() unconditionally on a matched
header, so a Lambda proxy response with an explicit "Content-Type": null
produced the literal string "null" instead of falling through to the
application/json default the old exact-case lookup preserved (it checked
!ctNode.isNull() before using the value). Response.Builder#type("null")
throws, turning what used to be a 200 with the JSON default into a 502 with
the raw Lambda payload.
Also adds braces to the two new conditionals in findHeaderIgnoreCase per the
project's Java style (AGENTS.md).
Both caught by Greptile review on #2150. Verified the regression test fails
against the un-braced, null-unguarded version before this fix.
* chore: trigger CI
* fix(apigateway): scan multiValueHeaders for Content-Type, preferring it over headers
* chore: retrigger CI (previous run hit 20m job timeout)
This commit is contained in:
2 files changed
+112
-4
No files matched your search
+28
-4
@@ -44,6 +44,7 @@ import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -766,7 +767,7 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
}
|
||||
|
||||
private Response buildProxyResponse(InvokeResult result) {
|
||||
Response buildProxyResponse(InvokeResult result) {
|
||||
if (result.getPayload() == null || result.getPayload().length == 0) {
|
||||
return Response.status(result.getFunctionError() != null ? 502 : result.getStatusCode()).build();
|
||||
}
|
||||
@@ -793,9 +794,9 @@ public class ApiGatewayExecuteController {
|
||||
String bodyStr = bodyNode.asText();
|
||||
boolean isBase64 = node.path("isBase64Encoded").asBoolean(false);
|
||||
byte[] bytes = isBase64 ? Base64.getDecoder().decode(bodyStr) : bodyStr.getBytes();
|
||||
String ct = MediaType.APPLICATION_JSON;
|
||||
JsonNode ctNode = node.path("headers").path("Content-Type");
|
||||
if (!ctNode.isMissingNode() && !ctNode.isNull()) ct = ctNode.asText();
|
||||
String ct = findHeaderIgnoreCase(multiHeaders, "Content-Type")
|
||||
.or(() -> findHeaderIgnoreCase(respHeaders, "Content-Type"))
|
||||
.orElse(MediaType.APPLICATION_JSON);
|
||||
builder.entity(bytes).type(ct);
|
||||
}
|
||||
return builder.build();
|
||||
@@ -805,6 +806,29 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP header names are case-insensitive on the wire (RFC 7230 §3.2), and Lambda proxy
|
||||
* integrations commonly return lowercased names (e.g. the AWS Lambda Web Adapter emits
|
||||
* "content-type", not "Content-Type"). A plain JsonNode#path lookup is exact-case and
|
||||
* silently misses those, so Content-Type detection needs to scan case-insensitively.
|
||||
* Handles both the "headers" shape (single string value) and the "multiValueHeaders"
|
||||
* shape (array value, first element wins).
|
||||
*/
|
||||
private static Optional<String> findHeaderIgnoreCase(JsonNode headersNode, String name) {
|
||||
if (headersNode == null || !headersNode.isObject()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
var it = headersNode.fields();
|
||||
while (it.hasNext()) {
|
||||
var e = it.next();
|
||||
if (e.getKey().equalsIgnoreCase(name)) {
|
||||
JsonNode value = e.getValue().isArray() ? e.getValue().get(0) : e.getValue();
|
||||
return value == null || value.isNull() ? Optional.empty() : Optional.of(value.asText());
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// ──────────────────────────── AWS (non-proxy) ────────────────────────────
|
||||
|
||||
private MultivaluedMap<String, String> parseFormEncodedBody(String body) {
|
||||
|
||||
+84
@@ -3,11 +3,14 @@ package io.github.hectorvent.floci.services.apigateway;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -109,4 +112,85 @@ class ApiGatewayExecuteControllerTest {
|
||||
objectMapper.valueToTree(List.of("first", "second", "third")),
|
||||
event.path("multiValueHeaders").path("X-Dup"));
|
||||
}
|
||||
|
||||
// ── Lambda proxy response Content-Type header matching ──────
|
||||
|
||||
private static InvokeResult proxyPayload(String payloadJson) {
|
||||
return new InvokeResult(200, null, payloadJson.getBytes(StandardCharsets.UTF_8), null, "req-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildProxyResponseMatchesLowercaseContentType() {
|
||||
// The AWS Lambda Web Adapter sidecar (and many handlers) emit lowercase header names.
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
Response response = controller.buildProxyResponse(proxyPayload("""
|
||||
{"statusCode":404,"headers":{"content-type":"application/problem+json"},"body":"{}"}
|
||||
"""));
|
||||
assertEquals("application/problem+json", response.getMediaType().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildProxyResponseMatchesExactCaseContentType() {
|
||||
// The pre-existing exact-case path must keep working — this is a regression guard,
|
||||
// not a new behavior.
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
Response response = controller.buildProxyResponse(proxyPayload("""
|
||||
{"statusCode":200,"headers":{"Content-Type":"text/plain"},"body":"hi"}
|
||||
"""));
|
||||
assertEquals("text/plain", response.getMediaType().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildProxyResponseMatchesMixedCaseContentType() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
Response response = controller.buildProxyResponse(proxyPayload("""
|
||||
{"statusCode":200,"headers":{"CONTENT-TYPE":"application/xml"},"body":"<a/>"}
|
||||
"""));
|
||||
assertEquals("application/xml", response.getMediaType().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildProxyResponseDefaultsToJsonWhenNoContentTypeHeaderPresent() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
Response response = controller.buildProxyResponse(proxyPayload("""
|
||||
{"statusCode":200,"headers":{"X-Other":"value"},"body":"{}"}
|
||||
"""));
|
||||
assertEquals("application/json", response.getMediaType().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildProxyResponseDefaultsToJsonWhenContentTypeIsJsonNull() {
|
||||
// A JSON-null Content-Type must fall back to the default, the same as a missing header —
|
||||
// not be coerced to the literal string "null" (an invalid media type).
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
Response response = controller.buildProxyResponse(proxyPayload("""
|
||||
{"statusCode":200,"headers":{"content-type":null},"body":"{}"}
|
||||
"""));
|
||||
assertEquals("application/json", response.getMediaType().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildProxyResponseMatchesContentTypeInMultiValueHeaders() {
|
||||
// multiValueHeaders is a fully valid way to return any header, including Content-Type —
|
||||
// not just repeated ones — and must be scanned the same as headers.
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
Response response = controller.buildProxyResponse(proxyPayload("""
|
||||
{"statusCode":200,"multiValueHeaders":{"content-type":["application/xml"]},"body":"<a/>"}
|
||||
"""));
|
||||
assertEquals("application/xml", response.getMediaType().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildProxyResponseMultiValueHeadersTakesPrecedenceOverHeaders() {
|
||||
// API Gateway merges headers and multiValueHeaders, with multiValueHeaders winning
|
||||
// on conflicts.
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
Response response = controller.buildProxyResponse(proxyPayload("""
|
||||
{"statusCode":200,\
|
||||
"headers":{"Content-Type":"text/plain"},\
|
||||
"multiValueHeaders":{"Content-Type":["application/xml"]},\
|
||||
"body":"<a/>"}
|
||||
"""));
|
||||
assertEquals("application/xml", response.getMediaType().toString());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user