Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigateway): expose VTL authorizer and parameter maps (#3538)
XuJian229024780230
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.javanew file mode 100644index 0000000000..a7a582f514--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayVtlCompatibilityTest.java@@ -0,0 +1,95 @@+package com.floci.test;++import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.apigateway.ApiGatewayClient;+import software.amazon.awssdk.services.apigateway.model.IntegrationType;+import software.amazon.awssdk.services.apigateway.model.Resource;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.util.Map;++import static org.assertj.core.api.Assertions.assertThat;++@DisplayName("API Gateway REST VTL")+class ApiGatewayVtlCompatibilityTest {++ @Test+ @DisplayName("Header map get and keySet work in the native image")+ void headerMapMethodsWorkInNativeImage() 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();++ 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("headers")).id();++ apiGateway.putMethod(request -> request+ .restApiId(apiId)+ .resourceId(resourceId)+ .httpMethod("POST")+ .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")+ .type(IntegrationType.MOCK)+ .requestTemplates(Map.of("application/json", requestTemplate)));+ apiGateway.putMethodResponse(request -> request+ .restApiId(apiId)+ .resourceId(resourceId)+ .httpMethod("POST")+ .statusCode("201"));+ apiGateway.putIntegrationResponse(request -> request+ .restApiId(apiId)+ .resourceId(resourceId)+ .httpMethod("POST")+ .statusCode("201"));++ 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/headers");+ HttpRequest request = HttpRequest.newBuilder(uri)+ .header("Content-Type", "application/json")+ .header("x-repro-header", "repro-header-value")+ .POST(HttpRequest.BodyPublishers.ofString("{}"))+ .build();+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());++ assertThat(response.statusCode()).isEqualTo(201);+ } finally {+ apiGateway.deleteRestApi(request -> request.restApiId(apiId));+ apiGateway.close();+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.javaindex 1c00ff1baf..3a3a608849 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java@@ -413,8 +413,9 @@ public class ApiGatewayExecuteController {matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey,iamIdentity);case "AWS" -> invokeAwsIntegration(region, httpMethod, path, stageName,- matched, integration, headers, uriInfo, body);- case "MOCK" -> invokeMock(region, httpMethod, path, stageName, matched, integration, headers, uriInfo, body);+ matched, integration, headers, uriInfo, body, authorizerResult);+ case "MOCK" -> invokeMock(region, httpMethod, path, stageName,+ matched, integration, headers, uriInfo, body, authorizerResult);default -> Response.status(500).entity(jsonMessage("Unsupported integration type: " + integration.getType())).type(MediaType.APPLICATION_JSON).build();@@ -993,10 +994,27 @@ public class ApiGatewayExecuteController {return params;}+ static Map<String, Object> vtlAuthorizerContext(+ String principalId, Map<String, Object> authorizerContext) {+ Map<String, Object> result = new HashMap<>();+ if (authorizerContext != null) {+ authorizerContext.forEach((key, value) -> {+ if (value != null) {+ result.put(key, value.toString());+ }+ });+ }+ if (principalId != null) {+ result.put("principalId", principalId);+ }+ return result.isEmpty() ? null : result;+ }+private Response invokeAwsIntegration(String region, String httpMethod, String path,String stageName, ApiGatewayResource resource,Integration integration, HttpHeaders headers,- UriInfo uriInfo, byte[] body) {+ UriInfo uriInfo, byte[] body,+ AuthorizerResult authorizerResult) {AwsServiceRouter.IntegrationTarget target = serviceRouter.parseIntegrationUri(integration.getUri());if (target == null) {return Response.status(500)@@ -1022,10 +1040,13 @@ public class ApiGatewayExecuteController {String incomingContentType = headerMap.getOrDefault("Content-Type",headerMap.getOrDefault("content-type", "application/json"));+ Map<String, Object> vtlAuthorizerContext = vtlAuthorizerContext(+ authorizerResult.principalId(), authorizerResult.context());VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,- resource.getPath(), requestId, regionResolver.getAccountId(), null);+ resource.getPath(), requestId, regionResolver.getAccountId(), null,+ vtlAuthorizerContext);// AWS selects the request template by the *incoming* request Content-Type. Capture it// before parameter mapping runs, since an integration.request.header.Content-Type@@ -1244,7 +1265,8 @@ public class ApiGatewayExecuteController {if (responseTemplate != null && !responseTemplate.isEmpty()) {VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,- resource.getPath(), requestId, regionResolver.getAccountId(), null);+ resource.getPath(), requestId, regionResolver.getAccountId(), null,+ vtlAuthorizerContext);templateResult = vtlEngine.evaluate(responseTemplate, responseMappingCtx);finalBody = templateResult.body();} else {@@ -1359,7 +1381,8 @@ public class ApiGatewayExecuteController {private Response invokeMock(String region, String httpMethod, String path, String stageName,ApiGatewayResource resource, Integration integration,- HttpHeaders headers, UriInfo uriInfo, byte[] body) {+ HttpHeaders headers, UriInfo uriInfo, byte[] body,+ AuthorizerResult authorizerResult) {String requestId = UUID.randomUUID().toString();String bodyStr = body != null && body.length > 0 ? new String(body) : null;@@ -1380,7 +1403,8 @@ public class ApiGatewayExecuteController {VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,- resource.getPath(), requestId, regionResolver.getAccountId(), null);+ resource.getPath(), requestId, regionResolver.getAccountId(), null,+ vtlAuthorizerContext(authorizerResult.principalId(), authorizerResult.context()));// A MOCK has no backend: the request template *is* the integration response, and the// "statusCode" it renders is what the integration responses' selectionPatterns arediff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.javaindex df657dbb8e..d9ca54cf85 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java@@ -31,9 +31,11 @@ import java.io.StringWriter;import java.net.URLDecoder;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;+import java.util.AbstractMap;import java.util.Base64;import java.util.HashMap;import java.util.Map;+import java.util.Set;/*** Evaluates AWS API Gateway VTL (Velocity Template Language) mapping templates.@@ -44,6 +46,7 @@ import java.util.Map;@ApplicationScoped@RegisterForReflection(targets = {VtlTemplateEngine.InputVariable.class,+ VtlTemplateEngine.ParameterMap.class,VtlTemplateEngine.UtilVariable.class,VtlTemplateEngine.ResponseOverride.class,UberspectImpl.class,@@ -131,6 +134,10 @@ public class VtlTemplateEngine {identity.put("sourceIp", "127.0.0.1");map.put("identity", identity);+ if (ctx.authorizer() != null) {+ map.put("authorizer", ctx.authorizer());+ }+map.put("responseOverride", responseOverride);return map;@@ -181,7 +188,8 @@ public class VtlTemplateEngine {String resourcePath,String requestId,String accountId,- Map<String, String> stageVariables+ Map<String, String> stageVariables,+ Map<String, Object> authorizer) {}/**@@ -252,9 +260,9 @@ public class VtlTemplateEngine {/** Returns request parameters organized by type. */public Map<String, Map<String, String>> params() {Map<String, Map<String, String>> params = new HashMap<>();- params.put("querystring", ctx.queryParams() != null ? ctx.queryParams() : Map.of());- params.put("path", ctx.pathParams() != null ? ctx.pathParams() : Map.of());- params.put("header", ctx.headers() != null ? ctx.headers() : Map.of());+ params.put("querystring", new ParameterMap(ctx.queryParams()));+ params.put("path", new ParameterMap(ctx.pathParams()));+ params.put("header", new ParameterMap(ctx.headers()));return params;}@@ -289,6 +297,31 @@ public class VtlTemplateEngine {}}+ /** Reflection-safe map exposed to Velocity templates in native images. */+ public static class ParameterMap extends AbstractMap<String, String> {++ private final Map<String, String> values;++ public ParameterMap(Map<String, String> values) {+ this.values = values != null ? values : Map.of();+ }++ @Override+ public String get(Object key) {+ return values.get(key);+ }++ @Override+ public Set<String> keySet() {+ return values.keySet();+ }++ @Override+ public Set<Entry<String, String>> entrySet() {+ return values.entrySet();+ }+ }+/*** The {@code $util} variable available in API Gateway VTL templates.*/diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.javaindex 923e1f1e02..7e9839cb60 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java@@ -410,7 +410,7 @@ public class WebSocketIntegrationInvoker {VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(eventJson, Map.of(), Map.of(), Map.of(), "", "", "", "", "000000000000",- stageVariables != null ? stageVariables : Map.of());+ stageVariables != null ? stageVariables : Map.of(), null);VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);return result.body();@@ -450,7 +450,7 @@ public class WebSocketIntegrationInvoker {VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(responseBody, Map.of(), Map.of(), Map.of(), "", "", "", "", "000000000000",- stageVariables != null ? stageVariables : Map.of());+ stageVariables != null ? stageVariables : Map.of(), null);VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);return result.body();diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAuthorizerContextIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAuthorizerContextIntegrationTest.javaindex 180abbe726..95d9b34cc8 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAuthorizerContextIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAuthorizerContextIntegrationTest.java@@ -35,6 +35,7 @@ class ApiGatewayAuthorizerContextIntegrationTest {private static String rootId;private static String securedResourceId;private static String plainResourceId;+ private static String mappedResourceId;private static String authorizerId;private static String deploymentId;@@ -56,6 +57,10 @@ class ApiGatewayAuthorizerContextIntegrationTest {org_id: "ORG001",sub: "test-user",client_id: "my-client",+ key_id: "KEY-123",+ numKey: 1,+ boolKey: true,+ identity: JSON.stringify({key_id: "KEY-123", tenant: "t-9"}),methodArn: event.methodArn}});@@ -66,13 +71,18 @@ class ApiGatewayAuthorizerContextIntegrationTest {@Order(2)void createProxyLambda() throws Exception {createNodeLambda(PROXY_FUNCTION, """- exports.handler = async (event) => ({- statusCode: 200,- body: JSON.stringify({- authorizer: event.requestContext?.authorizer ?? null,- hasAuthorizer: Object.prototype.hasOwnProperty.call(event.requestContext ?? {}, "authorizer")- })- });+ exports.handler = async (event) => {+ if (!event.requestContext) {+ return event;+ }+ return {+ statusCode: 200,+ body: JSON.stringify({+ authorizer: event.requestContext.authorizer ?? null,+ hasAuthorizer: Object.prototype.hasOwnProperty.call(event.requestContext, "authorizer")+ })+ };+ };""");}@@ -118,6 +128,14 @@ class ApiGatewayAuthorizerContextIntegrationTest {.then().statusCode(201).extract().path("id");++ mappedResourceId = given()+ .contentType(ContentType.JSON)+ .body("{\"pathPart\":\"mapped\"}")+ .when().post("/restapis/" + apiId + "/resources/" + rootId)+ .then()+ .statusCode(201)+ .extract().path("id");}@Test@@ -158,6 +176,19 @@ class ApiGatewayAuthorizerContextIntegrationTest {.then().statusCode(201);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {+ "authorizationType":"CUSTOM",+ "authorizerId":"%s",+ "requestParameters":{"method.request.header.Authorization":true}+ }+ """.formatted(authorizerId))+ .when().put("/restapis/" + apiId + "/resources/" + mappedResourceId + "/methods/PUT")+ .then()+ .statusCode(201);+given().contentType(ContentType.JSON).body("""@@ -190,6 +221,37 @@ class ApiGatewayAuthorizerContextIntegrationTest {.when().put("/restapis/" + apiId + "/resources/" + plainResourceId + "/methods/PUT/integration").then().statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {+ "type":"AWS",+ "httpMethod":"POST",+ "uri":"%s",+ "requestTemplates":{+ "application/json":"#set($identity = $util.parseJson($context.authorizer.identity))#set($numberIsString = $context.authorizer.numKey == \\\"1\\\")#set($booleanIsString = $context.authorizer.boolKey == \\\"true\\\"){\\\"principalId\\\":\\\"$context.authorizer.principalId\\\",\\\"numberIsString\\\":$numberIsString,\\\"booleanIsString\\\":$booleanIsString,\\\"keyId\\\":\\\"$context.authorizer.key_id\\\",\\\"tenant\\\":\\\"$identity.tenant\\\"}"+ }+ }+ """.formatted(proxyUri))+ .when().put("/restapis/" + apiId + "/resources/" + mappedResourceId + "/methods/PUT/integration")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {+ "selectionPattern":"",+ "responseTemplates":{+ "application/json":"#set($numberIsString = $context.authorizer.numKey == \\\"1\\\")#set($booleanIsString = $context.authorizer.boolKey == \\\"true\\\"){\\\"request\\\":$input.json('$'),\\\"principalId\\\":\\\"$context.authorizer.principalId\\\",\\\"numberIsString\\\":$numberIsString,\\\"booleanIsString\\\":$booleanIsString}"+ }+ }+ """)+ .when().put("/restapis/" + apiId + "/resources/" + mappedResourceId+ + "/methods/PUT/integration/responses/200")+ .then()+ .statusCode(201);}@Test@@ -240,6 +302,29 @@ class ApiGatewayAuthorizerContextIntegrationTest {@Test@Order(10)+ void executeMappedRoute_propagatesAuthorizerContextToRequestTemplate() throws Exception {+ String response = given()+ .contentType(ContentType.JSON)+ .header("Authorization", "Bearer allow")+ .body("{\"ok\":true}")+ .when().put("/execute-api/" + apiId + "/test/mapped")+ .then()+ .statusCode(200)+ .extract().asString();++ JsonNode payload = OBJECT_MAPPER.readTree(response);+ assertEquals("test-user", payload.path("principalId").asText());+ assertTrue(payload.path("numberIsString").asBoolean());+ assertTrue(payload.path("booleanIsString").asBoolean());+ assertEquals("test-user", payload.path("request").path("principalId").asText());+ assertTrue(payload.path("request").path("numberIsString").asBoolean());+ assertTrue(payload.path("request").path("booleanIsString").asBoolean());+ assertEquals("KEY-123", payload.path("request").path("keyId").asText());+ assertEquals("t-9", payload.path("request").path("tenant").asText());+ }++ @Test+ @Order(11)void executePlainRoute_doesNotInjectAuthorizerContext() throws Exception {String response = given().contentType(ContentType.JSON)@@ -255,7 +340,7 @@ class ApiGatewayAuthorizerContextIntegrationTest {}@Test- @Order(11)+ @Order(12)void executeSecuredRoute_denyStillReturns403() {given().contentType(ContentType.JSON)diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.javaindex 1d5012a6e4..34351de491 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java@@ -18,6 +18,7 @@ import java.util.List;import java.util.Map;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.atLeastOnce;@@ -136,6 +137,29 @@ class ApiGatewayExecuteControllerTest {event.path("multiValueHeaders").path("X-Dup"));}+ @Test+ void convertsAuthorizerValuesToAwsVtlStringShape() {+ Map<String, Object> result = ApiGatewayExecuteController.vtlAuthorizerContext(+ "real-principal",+ Map.of(+ "principalId", "context-principal",+ "stringKey", "value",+ "numberKey", 1,+ "booleanKey", true));++ assertEquals(Map.of(+ "principalId", "real-principal",+ "stringKey", "value",+ "numberKey", "1",+ "booleanKey", "true"), result);+ }++ @Test+ void omitsEmptyAuthorizerVtlContext() {+ assertNull(ApiGatewayExecuteController.vtlAuthorizerContext(null, null));+ assertNull(ApiGatewayExecuteController.vtlAuthorizerContext(null, Map.of()));+ }+// ── Lambda proxy response Content-Type header matching ──────private static InvokeResult proxyPayload(String payloadJson) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayMockAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayMockAuthorizerIntegrationTest.javanew file mode 100644index 0000000000..83397e2ace--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayMockAuthorizerIntegrationTest.java@@ -0,0 +1,168 @@+package io.github.hectorvent.floci.services.apigateway;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.lambda.LambdaService;+import io.github.hectorvent.floci.services.lambda.model.InvocationType;+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;+import io.quarkus.test.InjectMock;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+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.util.List;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++@QuarkusTest+class ApiGatewayMockAuthorizerIntegrationTest {++ private static final String FUNCTION = "mock-vtl-authorizer";+ private static final String AUTHORIZER_URI = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"+ + "arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION + "/invocations";+ private static final String RESPONSE_TEMPLATE = """+ {"principalId":"$context.authorizer.principalId",+ "role":"$context.authorizer.role",+ "numberIsString":$context.authorizer.numberKey.equals('1'),+ "booleanIsString":$context.authorizer.booleanKey.equals('true')}+ """;++ @InjectMock+ LambdaService lambdaService;++ private String apiId;+ private String methodPath;++ @BeforeEach+ void createApi() {+ apiId = given().contentType(ContentType.JSON)+ .body(Map.of("name", "mock-authorizer-vtl"))+ .post("/restapis").then().statusCode(201).extract().path("id");+ String rootId = given().get("/restapis/" + apiId + "/resources")+ .then().statusCode(200).extract().path("item[0].id");+ String resourceId = given().contentType(ContentType.JSON)+ .body(Map.of("pathPart", "claims"))+ .post("/restapis/" + apiId + "/resources/" + rootId)+ .then().statusCode(201).extract().path("id");+ methodPath = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";+ }++ @AfterEach+ void deleteApi() {+ if (apiId != null) {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"TOKEN", "REQUEST"})+ void requestTemplateSelectsResponseUsingAuthorizerClaims(String type) throws Exception {+ configureAuthorizer(type, "Allow");+ configureMock("""+ #if($context.authorizer.principalId == 'test-user'+ && $context.authorizer.role == 'admin'+ && $context.authorizer.numberKey.equals('1')+ && $context.authorizer.booleanKey.equals('true'))+ {"statusCode":201}+ #else+ {"statusCode":500}+ #end+ """, RESPONSE_TEMPLATE);++ assertAuthorizerResponse();+ }++ @ParameterizedTest+ @ValueSource(strings = {"TOKEN", "REQUEST"})+ void responseTemplateReceivesAuthorizerClaims(String type) throws Exception {+ configureAuthorizer(type, "Allow");+ configureMock("{\"statusCode\":201}", RESPONSE_TEMPLATE);++ assertAuthorizerResponse();+ }++ @Test+ void deniedAuthorizerStillRejectsMockRequest() throws Exception {+ configureAuthorizer("TOKEN", "Deny");+ configureMock("{\"statusCode\":201}", "{\"mock\":true}");++ given().header("Authorization", "Bearer denied")+ .get("/execute-api/" + apiId + "/test/claims")+ .then().statusCode(403)+ .body(equalTo("{\"message\":\"User is not authorized to access this resource\"}"));+ }++ @Test+ void unauthenticatedMockDoesNotGainAnAuthorizerContext() {+ given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE"))+ .put(methodPath).then().statusCode(201);+ configureMock("{\"statusCode\":201}",+ "#if($context.authorizer){\"hasAuthorizer\":true}#else{\"hasAuthorizer\":false}#end");++ given().get("/execute-api/" + apiId + "/test/claims")+ .then().statusCode(201).body("hasAuthorizer", equalTo(false));+ verify(lambdaService, never()).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class),+ eq(InvocationType.RequestResponse));+ }++ private void configureAuthorizer(String type, String effect) throws Exception {+ String authorizerId = given().contentType(ContentType.JSON)+ .body(Map.of("name", "claims", "type", type, "authorizerUri", AUTHORIZER_URI,+ "identitySource", "method.request.header.Authorization", "authorizerResultTtlInSeconds", 0))+ .post("/restapis/" + apiId + "/authorizers")+ .then().statusCode(201).extract().path("id");+ given().contentType(ContentType.JSON)+ .body(Map.of("authorizationType", "CUSTOM", "authorizerId", authorizerId))+ .put(methodPath).then().statusCode(201);++ byte[] payload = new ObjectMapper().writeValueAsBytes(Map.of(+ "principalId", "test-user",+ "policyDocument", Map.of("Version", "2012-10-17", "Statement", List.of(Map.of(+ "Action", "execute-api:Invoke", "Effect", effect, "Resource", "*"))),+ "context", Map.of("principalId", "custom-principal", "role", "admin",+ "numberKey", 1, "booleanKey", true)));+ when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class),+ eq(InvocationType.RequestResponse)))+ .thenReturn(new InvokeResult(200, null, payload, null, "authorizer-request"));+ }++ private void configureMock(String requestTemplate, String responseTemplate) {+ given().contentType(ContentType.JSON)+ .body(Map.of("type", "MOCK", "requestTemplates", Map.of("application/json", requestTemplate)))+ .put(methodPath + "/integration").then().statusCode(201);+ for (String status : List.of("201", "500")) {+ given().contentType(ContentType.JSON).body(Map.of())+ .put(methodPath + "/responses/" + status).then().statusCode(201);+ given().contentType(ContentType.JSON)+ .body(Map.of("selectionPattern", status, "responseTemplates", Map.of(+ "application/json", "201".equals(status) ? responseTemplate : "{\"error\":\"claims missing\"}")))+ .put(methodPath + "/integration/responses/" + status).then().statusCode(201);+ }+ given().contentType(ContentType.JSON).body(Map.of("stageName", "test"))+ .post("/restapis/" + apiId + "/deployments").then().statusCode(201);+ }++ private void assertAuthorizerResponse() {+ for (String endpoint : List.of(+ "/execute-api/" + apiId + "/test/claims",+ "/restapis/" + apiId + "/test/_user_request_/claims")) {+ given().header("Authorization", "Bearer allowed")+ .get(endpoint)+ .then().statusCode(201)+ .body("principalId", equalTo("test-user"))+ .body("role", equalTo("admin"))+ .body("numberIsString", equalTo(true))+ .body("booleanIsString", equalTo(true));+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.javaindex 89627429e7..3d37728e4d 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java@@ -6,6 +6,7 @@ import jakarta.inject.Inject;import org.junit.jupiter.api.Test;import java.util.Map;+import java.util.Set;import static org.junit.jupiter.api.Assertions.*;@@ -26,6 +27,7 @@ class VtlTemplateEngineTest {"/users","req-123","000000000000",+ Map.of(),Map.of());}@@ -154,11 +156,31 @@ class VtlTemplateEngineTest {assertEquals("127.0.0.1", result);}+ @Test+ void contextAuthorizer() {+ VtlTemplateEngine.VtlContext authorizerCtx = new VtlTemplateEngine.VtlContext(+ "{}", Map.of(), Map.of(), Map.of(), "prod", "POST", "/users",+ "req-123", "000000000000", Map.of(),+ Map.of(+ "principalId", "test-user",+ "key_id", "KEY-123",+ "numberKey", "1",+ "booleanKey", "true",+ "identity", "{\"tenant\":\"t-9\"}"));+ String template = "#set($identity = $util.parseJson($context.authorizer.identity))"+ + "#set($numberIsString = $context.authorizer.numberKey == \"1\")"+ + "#set($booleanIsString = $context.authorizer.booleanKey == \"true\")"+ + "$context.authorizer.principalId|$context.authorizer.key_id|$identity.tenant"+ + "|$numberIsString|$booleanIsString";++ assertEquals("test-user|KEY-123|t-9|true|true", engine.evaluate(template, authorizerCtx).body());+ }+@Testvoid stageVariables() {VtlTemplateEngine.VtlContext svCtx = new VtlTemplateEngine.VtlContext("{}", Map.of(), Map.of(), Map.of(), "prod", "GET", "/",- "req-1", "000000000000", Map.of("tableName", "my-table"));+ "req-1", "000000000000", Map.of("tableName", "my-table"), Map.of());String result = engine.evaluate("$stageVariables.tableName", svCtx).body();assertEquals("my-table", result);}@@ -292,7 +314,7 @@ class VtlTemplateEngineTest {var queryCtx = new VtlTemplateEngine.VtlContext("{}", Map.of(), Map.of("userId", "user-42", "status", "active"),Map.of(), "prod", "GET", "/items",- "req-456", "000000000000", Map.of("tableName", "orders"));+ "req-456", "000000000000", Map.of("tableName", "orders"), Map.of());String template = """{"TableName": "$stageVariables.tableName", "KeyConditionExpression": "pk = :pk", "ExpressionAttributeValues": {":pk": {"S": "$input.params().querystring.userId"}}}""";String result = engine.evaluate(template, queryCtx).body();@@ -320,7 +342,17 @@ class VtlTemplateEngineTest {// Access all three param types in one templateString template = "$input.params().querystring.limit|$input.params().path.proxy|$input.params().header.get('Content-Type')";String result = engine.evaluate(template, ctx("{}")).body();- assertTrue(result.startsWith("10|users/123|"), "Should contain all param types: " + result);+ assertEquals("10|users/123|application/json", result);+ }++ @Test+ void inputParams_headerKeySet() {+ String template = "#foreach($header in $input.params().header.keySet())"+ + "$header=$input.params().header.get($header)#if($foreach.hasNext),#end#end";+ String result = engine.evaluate(template, ctx("{}")).body();++ assertEquals(Set.of("Content-Type=application/json", "Authorization=Bearer xyz"),+ Set.of(result.split(",")));}// ──────────── $util.parseJson in templates ────────────@@ -358,7 +390,7 @@ class VtlTemplateEngineTest {"{}", Map.of("shared", "header-val"),Map.of("shared", "query-val"),Map.of("shared", "path-val"),- "prod", "GET", "/", "req-1", "000000000000", Map.of());+ "prod", "GET", "/", "req-1", "000000000000", Map.of(), Map.of());String result = engine.evaluate("$input.params('shared')", overlapCtx).body();assertEquals("query-val", result);}