From aff365d1e5dd933633e68b4989509a26348e5753 Mon Sep 17 00:00:00 2001 From: Tyler Webb <85189637+T-Webb1@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:06:42 -0800 Subject: [PATCH] fix(apigateway): register the $foreach loop scope for native VTL (#7859) In the native image every $foreach property of a VTL mapping template resolved to null: #if($foreach.hasNext) was always false, so the usual comma-between-items pattern rendered invalid JSON, and $foreach.index, $foreach.count and $foreach.hasNext printed as literal text. Velocity binds $foreach to a ForeachScope and reads its getters through reflection, but only the Foreach directive was registered, not the scope it creates. Velocity then fell back to reading the scope as a map, which holds none of those keys. ForeachScope and its parent Scope are now registered alongside the directive. Reflection registration covers the whole image, so AppSync resolver templates, which loop through the same directive, get the scope too. --- .../test/ApiGatewayVtlCompatibilityTest.java | 153 ++++++++---------- .../apigateway/VtlTemplateEngine.java | 4 + 2 files changed, 68 insertions(+), 89 deletions(-) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayVtlCompatibilityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayVtlCompatibilityTest.java index eb7eec6c73..4355c58f26 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayVtlCompatibilityTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayVtlCompatibilityTest.java @@ -12,91 +12,83 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.Map; +import java.util.function.UnaryOperator; import static org.assertj.core.api.Assertions.assertThat; @DisplayName("API Gateway REST VTL") class ApiGatewayVtlCompatibilityTest { + private static final String STATUS_200_TEMPLATE = "{\"statusCode\": 200}"; + @Test @DisplayName("Parsed map and collection methods work in native REST response templates") void responseTemplateMapMethodsWorkInNativeImage() throws Exception { - Assumptions.assumeFalse(TestFixtures.isRealAws(), "Floci native-image regression test"); + String responseTemplate = "#set($parsed = $util.parseJson($input.body))" + + "#if($parsed.headers)$parsed.headers.isEmpty()|$parsed.headers.size()|" + + "#foreach($entry in $parsed.headers.entrySet())$entry.getKey()=$entry.getValue()#end|" + + "$parsed.items.isEmpty()|$parsed.items.size()|#foreach($item in $parsed.items)$item#end#end"; - ApiGatewayClient apiGateway = TestFixtures.apiGatewayClient(); - String apiId = apiGateway.createRestApi(request -> request.name(TestFixtures.uniqueName("apigw-vtl-response"))).id(); + HttpResponse response = invokeMockIntegration("response-map", STATUS_200_TEMPLATE, "200", + responseTemplate, request -> request + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString( + "{\"headers\":{\"x-test\":\"yes\"},\"items\":[\"a\",\"b\"]}"))); - try { - String rootId = apiGateway.getResources(request -> request.restApiId(apiId)).items().stream() - .filter(resource -> "/".equals(resource.path())) - .findFirst() - .map(Resource::id) - .orElseThrow(); - String resourceId = apiGateway.createResource(request -> request - .restApiId(apiId) - .parentId(rootId) - .pathPart("response-map")).id(); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body().trim()).isEqualTo("false|1|x-test=yes|false|2|ab"); + } - apiGateway.putMethod(request -> request - .restApiId(apiId) - .resourceId(resourceId) - .httpMethod("POST") - .authorizationType("NONE")); - apiGateway.putIntegration(request -> request - .restApiId(apiId) - .resourceId(resourceId) - .httpMethod("POST") - .type(IntegrationType.MOCK) - .requestTemplates(Map.of("application/json", "{\"statusCode\": 200}"))); - apiGateway.putMethodResponse(request -> request - .restApiId(apiId) - .resourceId(resourceId) - .httpMethod("POST") - .statusCode("200")); + @Test + @DisplayName("The $foreach loop scope works in native REST response templates") + void foreachScopeWorksInNativeImage() throws Exception { + String responseTemplate = "#foreach($i in [\"a\",\"b\"])" + + "$i:$foreach.index:$foreach.count:$foreach.hasNext#if($foreach.hasNext),#end#end"; - String responseTemplate = "#set($parsed = $util.parseJson($input.body))" - + "#if($parsed.headers)$parsed.headers.isEmpty()|$parsed.headers.size()|" - + "#foreach($entry in $parsed.headers.entrySet())$entry.getKey()=$entry.getValue()#end|" - + "$parsed.items.isEmpty()|$parsed.items.size()|#foreach($item in $parsed.items)$item#end#end"; - apiGateway.putIntegrationResponse(request -> request - .restApiId(apiId) - .resourceId(resourceId) - .httpMethod("POST") - .statusCode("200") - .responseTemplates(Map.of("application/json", responseTemplate))); + HttpResponse response = invokeMockIntegration("foreach", STATUS_200_TEMPLATE, "200", + responseTemplate, HttpRequest.Builder::GET); - String deploymentId = apiGateway.createDeployment(request -> request.restApiId(apiId)).id(); - apiGateway.createStage(request -> request - .restApiId(apiId) - .stageName("test") - .deploymentId(deploymentId)); - - HttpClient httpClient = TestFixtures.emulatorHttpClient(); - URI uri = URI.create(TestFixtures.endpoint() + "/execute-api/" + apiId + "/test/response-map"); - HttpRequest request = HttpRequest.newBuilder(uri) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString( - "{\"headers\":{\"x-test\":\"yes\"},\"items\":[\"a\",\"b\"]}")) - .build(); - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.body().trim()).isEqualTo("false|1|x-test=yes|false|2|ab"); - } finally { - apiGateway.deleteRestApi(request -> request.restApiId(apiId)); - apiGateway.close(); - } + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body().trim()).isEqualTo("a:0:1:true,b:1:2:false"); } @Test @DisplayName("Header map get and keySet work in the native image") void headerMapMethodsWorkInNativeImage() throws Exception { + String requestTemplate = """ + #set($headers = $input.params().header) + #set($direct = $headers.get('x-repro-header')) + #set($status = 500) + #foreach($name in $headers.keySet()) + #if($direct == 'repro-header-value' && $headers.get($name) == 'repro-header-value') + #set($status = 201) + #end + #end + {"statusCode": $status} + """; + + HttpResponse response = invokeMockIntegration("headers", requestTemplate, "201", + null, request -> request + .header("Content-Type", "application/json") + .header("x-repro-header", "repro-header-value") + .POST(HttpRequest.BodyPublishers.ofString("{}"))); + + assertThat(response.statusCode()).isEqualTo(201); + } + + private static HttpResponse invokeMockIntegration(String pathPart, String requestTemplate, + String statusCode, String responseTemplate, UnaryOperator requestCustomizer) + throws Exception { Assumptions.assumeFalse(TestFixtures.isRealAws(), "Floci native-image regression test"); ApiGatewayClient apiGateway = TestFixtures.apiGatewayClient(); - String apiId = apiGateway.createRestApi(request -> request.name(TestFixtures.uniqueName("apigw-vtl"))).id(); + String apiId = apiGateway.createRestApi(request -> request.name(TestFixtures.uniqueName("apigw-vtl-" + pathPart))).id(); try { + URI uri = URI.create(TestFixtures.endpoint() + "/execute-api/" + apiId + "/test/" + pathPart); + HttpRequest httpRequest = requestCustomizer.apply(HttpRequest.newBuilder(uri)).build(); + String httpMethod = httpRequest.method(); + String rootId = apiGateway.getResources(request -> request.restApiId(apiId)).items().stream() .filter(resource -> "/".equals(resource.path())) .findFirst() @@ -105,41 +97,32 @@ class ApiGatewayVtlCompatibilityTest { String resourceId = apiGateway.createResource(request -> request .restApiId(apiId) .parentId(rootId) - .pathPart("headers")).id(); + .pathPart(pathPart)).id(); apiGateway.putMethod(request -> request .restApiId(apiId) .resourceId(resourceId) - .httpMethod("POST") + .httpMethod(httpMethod) .authorizationType("NONE")); - - String requestTemplate = """ - #set($headers = $input.params().header) - #set($direct = $headers.get('x-repro-header')) - #set($status = 500) - #foreach($name in $headers.keySet()) - #if($direct == 'repro-header-value' && $headers.get($name) == 'repro-header-value') - #set($status = 201) - #end - #end - {"statusCode": $status} - """; apiGateway.putIntegration(request -> request .restApiId(apiId) .resourceId(resourceId) - .httpMethod("POST") + .httpMethod(httpMethod) .type(IntegrationType.MOCK) .requestTemplates(Map.of("application/json", requestTemplate))); apiGateway.putMethodResponse(request -> request .restApiId(apiId) .resourceId(resourceId) - .httpMethod("POST") - .statusCode("201")); + .httpMethod(httpMethod) + .statusCode(statusCode)); apiGateway.putIntegrationResponse(request -> request .restApiId(apiId) .resourceId(resourceId) - .httpMethod("POST") - .statusCode("201")); + .httpMethod(httpMethod) + .statusCode(statusCode) + .responseTemplates(responseTemplate == null + ? null + : Map.of("application/json", responseTemplate))); String deploymentId = apiGateway.createDeployment(request -> request.restApiId(apiId)).id(); apiGateway.createStage(request -> request @@ -148,15 +131,7 @@ class ApiGatewayVtlCompatibilityTest { .deploymentId(deploymentId)); HttpClient httpClient = TestFixtures.emulatorHttpClient(); - URI uri = URI.create(TestFixtures.endpoint() + "/execute-api/" + apiId + "/test/headers"); - HttpRequest request = HttpRequest.newBuilder(uri) - .header("Content-Type", "application/json") - .header("x-repro-header", "repro-header-value") - .POST(HttpRequest.BodyPublishers.ofString("{}")) - .build(); - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - assertThat(response.statusCode()).isEqualTo(201); + return httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); } finally { apiGateway.deleteRestApi(request -> request.restApiId(apiId)); apiGateway.close(); diff --git a/src/main/java/io/floci/aws/services/apigateway/VtlTemplateEngine.java b/src/main/java/io/floci/aws/services/apigateway/VtlTemplateEngine.java index dc46b9cdc8..6312057c0a 100644 --- a/src/main/java/io/floci/aws/services/apigateway/VtlTemplateEngine.java +++ b/src/main/java/io/floci/aws/services/apigateway/VtlTemplateEngine.java @@ -15,9 +15,11 @@ import org.apache.velocity.runtime.directive.Break; import org.apache.velocity.runtime.directive.Define; import org.apache.velocity.runtime.directive.Evaluate; import org.apache.velocity.runtime.directive.Foreach; +import org.apache.velocity.runtime.directive.ForeachScope; import org.apache.velocity.runtime.directive.Include; import org.apache.velocity.runtime.directive.Macro; import org.apache.velocity.runtime.directive.Parse; +import org.apache.velocity.runtime.directive.Scope; import org.apache.velocity.runtime.directive.Stop; import org.apache.velocity.runtime.parser.StandardParser; import org.apache.velocity.runtime.resource.ResourceCacheImpl; @@ -59,6 +61,8 @@ import java.util.Set; StringResourceRepositoryImpl.class, Foreach.class, SandboxedForeach.class, + ForeachScope.class, + Scope.class, Include.class, Parse.class, Macro.class,