fix(apigateway): format request times with an English locale (#5093)

* fix(apigateway): format request times with an English locale

The REST requestTime, the HTTP API requestContext.time and the Lambda
function URL requestContext.time were formatted with
"dd/MMM/yyyy:HH:mm:ss Z" under the JVM default locale, so on a
non-English machine the month came out localized (e.g. "10月"). A REST
context mapping forwards that value into an integration request header,
where the JDK HTTP client rejected it and the call failed with 500.

Pin the formatters to Locale.ENGLISH, as the WebSocket event builder
already does, and have the HTTP API proxy and authorizer events reuse
the shared formatter in UTC instead of the system time zone.

* test(apigateway): cover HTTP API event times under a non-UTC host

Build the HTTP API proxy and REQUEST authorizer events under a Japanese
default locale and an Asia/Tokyo default time zone, and assert that
requestContext.time has an English month, a +0000 offset and the same
instant as timeEpoch. buildRequestAuthorizerEventV2 becomes
package-private so the test can reach it.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-05 10:08:38 -04:00
1 parent b988a061b4
commit 523003972e
4 files changed
+115 -10

No files matched your search

@@ -3203,9 +3203,9 @@ public class ApiGatewayExecuteController {
* Builds a REQUEST authorizer event in payload format version 2.0.
* Uses the newer HTTP API-native shape with routeArn, routeKey, rawPath, and requestContext.http.
*/
private String buildRequestAuthorizerEventV2(String httpMethod, String path, String routeKey,
String apiId, String stageName, String region,
HttpHeaders headers, UriInfo uriInfo) {
String buildRequestAuthorizerEventV2(String httpMethod, String path, String routeKey,
String apiId, String stageName, String region,
HttpHeaders headers, UriInfo uriInfo) {
// rawPath is by contract the raw, unmodified path, so recover the trailing slash the
// JAX-RS {proxy} binding stripped. routeArn keeps the normalized path for the same reason
// methodArn does in the 1.0 shape above.
@@ -3249,8 +3249,7 @@ public class ApiGatewayExecuteController {
ctx.put("requestId", UUID.randomUUID().toString());
ctx.put("routeKey", routeKey != null ? routeKey : "$default");
ctx.put("stage", stageName);
ctx.put("time", java.time.format.DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
.format(java.time.ZonedDateTime.now()));
ctx.put("time", GATEWAY_REQUEST_TIME.format(Instant.now().atZone(ZoneOffset.UTC)));
ctx.put("timeEpoch", System.currentTimeMillis());
ObjectNode http = ctx.putObject("http");
@@ -3474,8 +3473,7 @@ public class ApiGatewayExecuteController {
ctx.put("requestId", requestId);
ctx.put("routeKey", routeKey != null ? routeKey : "$default");
ctx.put("stage", stageName);
ctx.put("time", java.time.format.DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
.format(java.time.ZonedDateTime.now()));
ctx.put("time", GATEWAY_REQUEST_TIME.format(Instant.now().atZone(ZoneOffset.UTC)));
ctx.put("timeEpoch", System.currentTimeMillis());
ObjectNode http = ctx.putObject("http");
@@ -3570,8 +3568,8 @@ public class ApiGatewayExecuteController {
// ──────────────────────────── Gateway responses ────────────────────────────
private static final String GATEWAY_RESPONSE_HEADER_PREFIX = "gatewayresponse.header.";
private static final DateTimeFormatter GATEWAY_REQUEST_TIME =
DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z");
static final DateTimeFormatter GATEWAY_REQUEST_TIME =
DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
/**
* The {@code {"message": ...}} answer a REST API gives when it, rather than the integration,
@@ -161,7 +161,8 @@ public class LambdaUrlInvocationController {
ctx.put("requestId", requestId);
ctx.put("routeKey", "$default");
ctx.put("stage", "$default");
ctx.put("time", DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z").withZone(ZoneOffset.UTC).format(Instant.now()));
ctx.put("time", DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH)
.withZone(ZoneOffset.UTC).format(Instant.now()));
ctx.put("timeEpoch", System.currentTimeMillis());
ObjectNode httpNode = ctx.putObject("http");
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -14,9 +15,16 @@ import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -486,4 +494,70 @@ class ApiGatewayExecuteControllerTest {
assertEquals("rest-v1", response.getHeaderString("X-Trace"));
}
}
@Test
void requestTimeUsesEnglishMonthUnderNonEnglishDefaultLocale() {
// The formatter is built at class initialisation, so switching the default locale here
// cannot reach it: pinning its locale is what keeps the month ASCII on any machine.
assertEquals(Locale.ENGLISH, ApiGatewayExecuteController.GATEWAY_REQUEST_TIME.getLocale());
Locale original = Locale.getDefault();
try {
Locale.setDefault(Locale.JAPAN);
assertEquals("05/Oct/2026:13:45:30 +0000", ApiGatewayExecuteController.GATEWAY_REQUEST_TIME
.format(Instant.parse("2026-10-05T13:45:30Z").atZone(ZoneOffset.UTC)));
} finally {
Locale.setDefault(original);
}
}
@Test
void v2ProxyEventTimeIsEnglishUtcUnderNonUtcHost() throws Exception {
ApiGatewayExecuteController controller = controller(new ObjectMapper());
assertEnglishUtcTimeUnderNonUtcHost(() -> controller.buildV2ProxyEvent("GET", "/items", "GET /items",
"api1", "us-east-1", "$default", emptyHeaders(), uriInfoFor("http://localhost/items"),
new byte[0], "req-1", null, null, null, null));
}
@Test
void v2RequestAuthorizerEventTimeIsEnglishUtcUnderNonUtcHost() throws Exception {
ApiGatewayExecuteController controller = controller(new ObjectMapper());
assertEnglishUtcTimeUnderNonUtcHost(() -> controller.buildRequestAuthorizerEventV2("GET", "/items",
"GET /items", "api1", "$default", "us-east-1", emptyHeaders(),
uriInfoFor("http://localhost/items")));
}
private static HttpHeaders emptyHeaders() {
HttpHeaders headers = mock(HttpHeaders.class);
when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
return headers;
}
private static UriInfo uriInfoFor(String uri) {
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getRequestUri()).thenReturn(URI.create(uri));
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
return uriInfo;
}
private static void assertEnglishUtcTimeUnderNonUtcHost(Supplier<String> buildEvent) throws Exception {
Locale originalLocale = Locale.getDefault();
TimeZone originalZone = TimeZone.getDefault();
String event;
try {
Locale.setDefault(Locale.JAPAN);
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo"));
event = buildEvent.get();
} finally {
Locale.setDefault(originalLocale);
TimeZone.setDefault(originalZone);
}
JsonNode ctx = new ObjectMapper().readTree(event).path("requestContext");
String time = ctx.path("time").asText();
assertTrue(time.matches("\\d{2}/[A-Z][a-z]{2}/\\d{4}:\\d{2}:\\d{2}:\\d{2} \\+0000"), time);
long timeMillis = ZonedDateTime.parse(time, ApiGatewayExecuteController.GATEWAY_REQUEST_TIME)
.toInstant().toEpochMilli();
long timeEpoch = ctx.path("timeEpoch").asLong();
assertTrue(timeEpoch >= timeMillis && timeEpoch - timeMillis < 2000, time + " vs " + timeEpoch);
}
}
@@ -19,6 +19,7 @@ import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -131,6 +132,37 @@ class LambdaUrlInvocationControllerTest {
assertEquals(Base64.getEncoder().encodeToString(binaryBody), eventNode.get("body").asText());
}
@Test
void requestContextTimeUsesEnglishMonthUnderNonEnglishDefaultLocale() {
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);
Locale original = Locale.getDefault();
try {
Locale.setDefault(Locale.JAPAN);
controller.handlePost("url-id", "", headersWith("text/plain"),
uriInfoFor("http://localhost/lambda-url/url-id/"), "hi".getBytes(StandardCharsets.UTF_8));
} finally {
Locale.setDefault(original);
}
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), event.capture(), eq(InvocationType.RequestResponse));
String time = readTree(event.getValue()).path("requestContext").path("time").asText();
assertTrue(time.matches("\\d{2}/[A-Z][a-z]{2}/\\d{4}:\\d{2}:\\d{2}:\\d{2} \\+0000"), time);
}
@Test
void octetStreamBodyIsBase64EncodedEvenWhenValidUtf8() {
LambdaFunction fn = new LambdaFunction();