mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(lambda): correct Function URL body encoding, cookies, and error status (#3196)
Base64-encode non-UTF8 request bodies instead of lossily decoding them, map response cookies to separate Set-Cookie headers, and return 502 when the invoked function raises an unhandled error. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> * Fix #3153
This commit is contained in:
1 parent
f765195991
commit
d049875aaf
2 files changed
+248
-3
No files matched your search
+40
-3
@@ -28,10 +28,12 @@ import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
@@ -46,6 +48,7 @@ import java.util.UUID;
|
||||
public class LambdaUrlInvocationController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaUrlInvocationController.class);
|
||||
private static final int FUNCTION_ERROR_STATUS = 502;
|
||||
|
||||
private final LambdaService lambdaService;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -169,8 +172,13 @@ public class LambdaUrlInvocationController {
|
||||
httpNode.put("userAgent", headers.getHeaderString("user-agent"));
|
||||
|
||||
if (body != null && body.length > 0) {
|
||||
root.put("body", new String(body));
|
||||
root.put("isBase64Encoded", false);
|
||||
if (isTextMediaType(headers.getHeaderString(HttpHeaders.CONTENT_TYPE))) {
|
||||
root.put("body", new String(body, StandardCharsets.UTF_8));
|
||||
root.put("isBase64Encoded", false);
|
||||
} else {
|
||||
root.put("body", Base64.getEncoder().encodeToString(body));
|
||||
root.put("isBase64Encoded", true);
|
||||
}
|
||||
} else {
|
||||
root.putNull("body");
|
||||
root.put("isBase64Encoded", false);
|
||||
@@ -179,7 +187,23 @@ public class LambdaUrlInvocationController {
|
||||
return root.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors how AWS decides isBase64Encoded for Function URL / API Gateway proxy
|
||||
* integration requests: it is driven by the Content-Type header, not by whether
|
||||
* the raw bytes happen to be valid UTF-8. Same content-type allowlist already used
|
||||
* for the equivalent ALB-Lambda integration in ElbV2DataPlane, normalized to
|
||||
* lowercase first since media types are case-insensitive.
|
||||
*/
|
||||
private boolean isTextMediaType(String contentType) {
|
||||
String normalized = contentType == null ? null : contentType.toLowerCase(Locale.ROOT);
|
||||
return normalized == null || normalized.startsWith("text/") || normalized.contains("json")
|
||||
|| normalized.contains("xml") || normalized.contains("form");
|
||||
}
|
||||
|
||||
private Response buildResponse(InvokeResult result) {
|
||||
if (result.getFunctionError() != null) {
|
||||
return buildFunctionErrorResponse(result);
|
||||
}
|
||||
if (result.getPayload() == null || result.getPayload().length == 0) {
|
||||
return Response.status(result.getStatusCode()).build();
|
||||
}
|
||||
@@ -191,10 +215,13 @@ public class LambdaUrlInvocationController {
|
||||
if (node.has("headers")) {
|
||||
node.get("headers").fields().forEachRemaining(e -> builder.header(e.getKey(), e.getValue().asText()));
|
||||
}
|
||||
if (node.has("cookies") && node.get("cookies").isArray()) {
|
||||
node.get("cookies").forEach(cookie -> builder.header("Set-Cookie", cookie.asText()));
|
||||
}
|
||||
if (node.has("body")) {
|
||||
String body = node.get("body").asText();
|
||||
boolean isBase64 = node.path("isBase64Encoded").asBoolean(false);
|
||||
byte[] bytes = isBase64 ? Base64.getDecoder().decode(body) : body.getBytes();
|
||||
byte[] bytes = isBase64 ? Base64.getDecoder().decode(body) : body.getBytes(StandardCharsets.UTF_8);
|
||||
builder.entity(bytes);
|
||||
}
|
||||
return builder.build();
|
||||
@@ -206,6 +233,16 @@ public class LambdaUrlInvocationController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Real Function URLs never surface the raw invocation error payload (stack traces,
|
||||
* error types, internal fields) to the caller. A raw error payload has no "body"
|
||||
* field, so, matching ApiGatewayController's Lambda proxy integration, the response
|
||||
* carries the 502 status with no entity at all.
|
||||
*/
|
||||
private Response buildFunctionErrorResponse(InvokeResult result) {
|
||||
return Response.status(FUNCTION_ERROR_STATUS).build();
|
||||
}
|
||||
|
||||
private String jsonMessage(String message) {
|
||||
return objectMapper.createObjectNode().put("message", message).toString();
|
||||
}
|
||||
|
||||
+208
@@ -1,11 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
@@ -15,8 +17,12 @@ import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -26,6 +32,33 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class LambdaUrlInvocationControllerTest {
|
||||
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:100000000012:function:my-function";
|
||||
|
||||
private LambdaUrlInvocationController newController(LambdaService lambdaService) {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("100000000012");
|
||||
return new LambdaUrlInvocationController(
|
||||
lambdaService, regionResolver, new ObjectMapper(), new RequestContext());
|
||||
}
|
||||
|
||||
private HttpHeaders headersWith(String contentType) {
|
||||
HttpHeaders headers = mock(HttpHeaders.class);
|
||||
MultivaluedHashMap<String, String> requestHeaders = new MultivaluedHashMap<>();
|
||||
if (contentType != null) {
|
||||
requestHeaders.putSingle("content-type", contentType);
|
||||
}
|
||||
when(headers.getRequestHeaders()).thenReturn(requestHeaders);
|
||||
when(headers.getHeaderString(HttpHeaders.CONTENT_TYPE)).thenReturn(contentType);
|
||||
return headers;
|
||||
}
|
||||
|
||||
private UriInfo uriInfoFor(String uri) {
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create(uri));
|
||||
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
return uriInfo;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aliasUrlInvokesOwningAccountAliasArn() {
|
||||
String accountId = "100000000012";
|
||||
@@ -68,4 +101,179 @@ class LambdaUrlInvocationControllerTest {
|
||||
assertTrue(new String(event.getValue(), StandardCharsets.UTF_8)
|
||||
.contains("\"accountId\":\"" + accountId + "\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void binaryRequestBodyIsBase64EncodedInEvent() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-function");
|
||||
fn.setFunctionArn(FUNCTION_ARN);
|
||||
fn.setAccountId("100000000012");
|
||||
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.getTargetByUrlId("url-id")).thenReturn(fn);
|
||||
InvokeResult invokeResult = new InvokeResult();
|
||||
invokeResult.setStatusCode(200);
|
||||
invokeResult.setPayload("{\"statusCode\":200,\"body\":\"ok\"}".getBytes(StandardCharsets.UTF_8));
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(invokeResult);
|
||||
|
||||
LambdaUrlInvocationController controller = newController(lambdaService);
|
||||
byte[] binaryBody = new byte[] {0x00, (byte) 0xff, (byte) 0x80, 0x0a};
|
||||
|
||||
controller.handlePost("url-id", "", headersWith("application/octet-stream"),
|
||||
uriInfoFor("http://localhost/lambda-url/url-id/"), binaryBody);
|
||||
|
||||
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), event.capture(), eq(InvocationType.RequestResponse));
|
||||
JsonNode eventNode = readTree(event.getValue());
|
||||
|
||||
assertTrue(eventNode.get("isBase64Encoded").asBoolean());
|
||||
assertEquals(Base64.getEncoder().encodeToString(binaryBody), eventNode.get("body").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void octetStreamBodyIsBase64EncodedEvenWhenValidUtf8() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-function");
|
||||
fn.setFunctionArn(FUNCTION_ARN);
|
||||
fn.setAccountId("100000000012");
|
||||
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.getTargetByUrlId("url-id")).thenReturn(fn);
|
||||
InvokeResult invokeResult = new InvokeResult();
|
||||
invokeResult.setStatusCode(200);
|
||||
invokeResult.setPayload("{\"statusCode\":200,\"body\":\"ok\"}".getBytes(StandardCharsets.UTF_8));
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(invokeResult);
|
||||
|
||||
LambdaUrlInvocationController controller = newController(lambdaService);
|
||||
byte[] textLookingBody = "hello world".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
controller.handlePost("url-id", "", headersWith("application/octet-stream"),
|
||||
uriInfoFor("http://localhost/lambda-url/url-id/"), textLookingBody);
|
||||
|
||||
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), event.capture(), eq(InvocationType.RequestResponse));
|
||||
JsonNode eventNode = readTree(event.getValue());
|
||||
|
||||
assertTrue(eventNode.get("isBase64Encoded").asBoolean());
|
||||
assertEquals(Base64.getEncoder().encodeToString(textLookingBody), eventNode.get("body").asText());
|
||||
}
|
||||
|
||||
/** Media types are case-insensitive, so a mixed-case Content-Type must still classify as text. */
|
||||
@Test
|
||||
void mixedCaseJsonContentTypeIsStillPassedThroughAsText() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-function");
|
||||
fn.setFunctionArn(FUNCTION_ARN);
|
||||
fn.setAccountId("100000000012");
|
||||
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.getTargetByUrlId("url-id")).thenReturn(fn);
|
||||
InvokeResult invokeResult = new InvokeResult();
|
||||
invokeResult.setStatusCode(200);
|
||||
invokeResult.setPayload("{\"statusCode\":200,\"body\":\"ok\"}".getBytes(StandardCharsets.UTF_8));
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(invokeResult);
|
||||
|
||||
LambdaUrlInvocationController controller = newController(lambdaService);
|
||||
byte[] body = "{\"a\":1}".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
controller.handlePost("url-id", "", headersWith("Application/JSON"),
|
||||
uriInfoFor("http://localhost/lambda-url/url-id/"), body);
|
||||
|
||||
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), event.capture(), eq(InvocationType.RequestResponse));
|
||||
JsonNode eventNode = readTree(event.getValue());
|
||||
|
||||
assertFalse(eventNode.get("isBase64Encoded").asBoolean());
|
||||
assertEquals(new String(body, StandardCharsets.UTF_8), eventNode.get("body").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void textRequestBodyIsPassedThroughUndecoded() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-function");
|
||||
fn.setFunctionArn(FUNCTION_ARN);
|
||||
fn.setAccountId("100000000012");
|
||||
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.getTargetByUrlId("url-id")).thenReturn(fn);
|
||||
InvokeResult invokeResult = new InvokeResult();
|
||||
invokeResult.setStatusCode(200);
|
||||
invokeResult.setPayload("{\"statusCode\":200,\"body\":\"ok\"}".getBytes(StandardCharsets.UTF_8));
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(invokeResult);
|
||||
|
||||
LambdaUrlInvocationController controller = newController(lambdaService);
|
||||
|
||||
controller.handlePost("url-id", "", headersWith("application/json"),
|
||||
uriInfoFor("http://localhost/lambda-url/url-id/"), "{\"hello\":\"world\"}".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), event.capture(), eq(InvocationType.RequestResponse));
|
||||
JsonNode eventNode = readTree(event.getValue());
|
||||
|
||||
assertFalse(eventNode.get("isBase64Encoded").asBoolean());
|
||||
assertEquals("{\"hello\":\"world\"}", eventNode.get("body").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseCookiesArrayBecomesMultipleSetCookieHeaders() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-function");
|
||||
fn.setFunctionArn(FUNCTION_ARN);
|
||||
fn.setAccountId("100000000012");
|
||||
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.getTargetByUrlId("url-id")).thenReturn(fn);
|
||||
InvokeResult invokeResult = new InvokeResult();
|
||||
invokeResult.setStatusCode(200);
|
||||
invokeResult.setPayload(("{\"statusCode\":200,\"body\":\"ok\","
|
||||
+ "\"cookies\":[\"a=1; Path=/\",\"b=2; Max-Age=60\"]}").getBytes(StandardCharsets.UTF_8));
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(invokeResult);
|
||||
|
||||
LambdaUrlInvocationController controller = newController(lambdaService);
|
||||
|
||||
Response response = controller.handleGet("url-id", "", headersWith(null),
|
||||
uriInfoFor("http://localhost/lambda-url/url-id/"));
|
||||
|
||||
List<Object> setCookieHeaders = response.getHeaders().get("Set-Cookie");
|
||||
assertEquals(2, setCookieHeaders.size());
|
||||
assertTrue(setCookieHeaders.contains("a=1; Path=/"));
|
||||
assertTrue(setCookieHeaders.contains("b=2; Max-Age=60"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unhandledFunctionErrorMapsToBadGateway() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("my-function");
|
||||
fn.setFunctionArn(FUNCTION_ARN);
|
||||
fn.setAccountId("100000000012");
|
||||
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.getTargetByUrlId("url-id")).thenReturn(fn);
|
||||
InvokeResult invokeResult = new InvokeResult(200, "Unhandled",
|
||||
"{\"errorMessage\":\"boom\",\"errorType\":\"RuntimeException\"}".getBytes(StandardCharsets.UTF_8),
|
||||
null, "req-1");
|
||||
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(invokeResult);
|
||||
|
||||
LambdaUrlInvocationController controller = newController(lambdaService);
|
||||
|
||||
Response response = controller.handleGet("url-id", "", headersWith(null),
|
||||
uriInfoFor("http://localhost/lambda-url/url-id/"));
|
||||
|
||||
assertEquals(502, response.getStatus());
|
||||
assertNull(response.getEntity());
|
||||
}
|
||||
|
||||
private JsonNode readTree(byte[] json) {
|
||||
try {
|
||||
return new ObjectMapper().readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user