Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(apigateway): propagate TOKEN authorizer context to AWS_PROXY Lambda (#581)

TiMe5848487aaf8
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.java
index 5ff13f0737..83848c9263 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
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
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 com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -44,6 +45,7 @@ import java.util.regex.Pattern;
public class ApiGatewayExecuteController {
private static final Logger LOG = Logger.getLogger(ApiGatewayExecuteController.class);
+ private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {};
private final ApiGatewayService apiGatewayService;
private final ApiGatewayV2Service apiGatewayV2Service;
@@ -67,6 +69,8 @@ public class ApiGatewayExecuteController {
this.serviceRouter = serviceRouter;
}
+ private record AuthorizerResult(Response errorResponse, String principalId, Map<String, Object> context) {}
+
@GET
@Path("/{proxy: .*}")
public Response handleGet(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@@ -163,8 +167,8 @@ public class ApiGatewayExecuteController {
}
// 1. Authorizer
- Response authResponse = invokeAuthorizer(region, apiId, method, headers, uriInfo);
- if (authResponse != null) return authResponse;
+ AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, method, headers, uriInfo);
+ if (authorizerResult.errorResponse() != null) return authorizerResult.errorResponse();
// 2. Request validation
Response validationResponse = validateRequest(region, apiId, method, headers, uriInfo, body);
@@ -182,7 +186,7 @@ public class ApiGatewayExecuteController {
return switch (integration.getType().toUpperCase()) {
case "AWS_PROXY" -> invokeProxy(region, httpMethod, path, proxy, stageName,
- matched, integration, headers, uriInfo, body);
+ matched, integration, headers, uriInfo, body, authorizerResult);
case "AWS" -> invokeAwsIntegration(region, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
case "MOCK" -> invokeMock(region, httpMethod, path, stageName, matched, integration, headers, uriInfo, body);
@@ -197,7 +201,8 @@ public class ApiGatewayExecuteController {
private Response invokeProxy(String region, String httpMethod, String path, String proxy,
String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
- UriInfo uriInfo, byte[] body) {
+ UriInfo uriInfo, byte[] body,
+ AuthorizerResult authorizerResult) {
String functionName = functionNameFromUri(integration.getUri());
if (functionName == null) {
return Response.status(500)
@@ -207,7 +212,8 @@ public class ApiGatewayExecuteController {
String requestId = UUID.randomUUID().toString();
String eventJson = buildProxyEvent(httpMethod, path, proxy, resource.getPath(),
- stageName, headers, uriInfo, body, requestId);
+ stageName, headers, uriInfo, body, requestId,
+ authorizerResult.principalId(), authorizerResult.context());
try {
InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(),
@@ -223,38 +229,45 @@ public class ApiGatewayExecuteController {
}
}
- private Response invokeAuthorizer(String region, String apiId, MethodConfig method,
- HttpHeaders headers, UriInfo uriInfo) {
+ private AuthorizerResult invokeAuthorizer(String region, String apiId, String stageName,
+ String httpMethod, String requestPath, MethodConfig method,
+ HttpHeaders headers, UriInfo uriInfo) {
if ("CUSTOM".equals(method.getAuthorizationType())) {
String authorizerId = method.getAuthorizerId();
if (authorizerId == null) {
- return null;
+ return new AuthorizerResult(null, null, null);
}
io.github.hectorvent.floci.services.apigateway.model.Authorizer auth = apiGatewayService.getAuthorizer(region, apiId, authorizerId);
String lambdaName = functionNameFromUri(auth.getAuthorizerUri());
if (lambdaName == null) {
- return null;
+ return new AuthorizerResult(null, null, null);
}
- String event = toAuthorizerEvent(auth, headers);
+ String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod, requestPath);
try {
InvokeResult result = lambdaService.invoke(region, lambdaName, event.getBytes(), InvocationType.RequestResponse);
if (result.getFunctionError() != null) {
- return Response.status(403).build();
+ return new AuthorizerResult(Response.status(403).build(), null, null);
}
JsonNode policy = objectMapper.readTree(result.getPayload());
String effect = policy.path("policyDocument").path("Statement").get(0).path("Effect").asText("Deny");
if ("Deny".equalsIgnoreCase(effect)) {
- return Response.status(403).entity(jsonMessage("User is not authorized to access this resource")).build();
+ return new AuthorizerResult(
+ Response.status(403).entity(jsonMessage("User is not authorized to access this resource")).build(),
+ null,
+ null);
}
+ String principalId = policy.path("principalId").asText(null);
+ Map<String, Object> context = extractAuthorizerContext(policy.path("context"));
+ return new AuthorizerResult(null, principalId, context);
} catch (Exception e) {
LOG.warnv("Authorizer failure: {0}", e.getMessage());
- return Response.status(500).build();
+ return new AuthorizerResult(Response.status(500).build(), null, null);
}
}
- return null;
+ return new AuthorizerResult(null, null, null);
}
private Response validateRequest(String region, String apiId, MethodConfig method,
@@ -348,11 +361,19 @@ public class ApiGatewayExecuteController {
return null;
}
- private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth, HttpHeaders headers) {
+ private Map<String, Object> extractAuthorizerContext(JsonNode contextNode) {
+ if (contextNode == null || contextNode.isMissingNode() || contextNode.isNull() || !contextNode.isObject()) {
+ return null;
+ }
+ return objectMapper.convertValue(contextNode, MAP_TYPE);
+ }
+
+ private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth,
+ HttpHeaders headers, String region, String apiId, String stageName,
+ String httpMethod, String requestPath) {
ObjectNode node = objectMapper.createObjectNode();
node.put("type", auth.getType());
- node.put("methodArn", "arn:aws:execute-api:" + regionResolver.getDefaultRegion()
- + ":" + regionResolver.getAccountId() + ":api/stage/METHOD/path");
+ node.put("methodArn", buildMethodArn(region, apiId, stageName, httpMethod, requestPath));
if ("TOKEN".equals(auth.getType())) {
String headerName = auth.getIdentitySource().replace("method.request.header.", "");
node.put("authorizationToken", headers.getHeaderString(headerName));
@@ -360,6 +381,14 @@ public class ApiGatewayExecuteController {
return node.toString();
}
+ private String buildMethodArn(String region, String apiId, String stageName, String httpMethod, String requestPath) {
+ String normalizedPath = requestPath == null ? "" : requestPath.replaceFirst("^/", "");
+ String arnRegion = region == null ? regionResolver.getDefaultRegion() : region;
+ return "arn:aws:execute-api:" + arnRegion
+ + ":" + regionResolver.getAccountId()
+ + ":" + apiId + "/" + stageName + "/" + httpMethod + "/" + normalizedPath;
+ }
+
/**
* Extracts function name from integration URI like
* {@code arn:aws:apigateway:...:lambda:path/2015-03-31/functions/{fnArn}/invocations}.
@@ -391,7 +420,8 @@ public class ApiGatewayExecuteController {
private String buildProxyEvent(String httpMethod, String path, String proxy,
String resourcePath, String stageName,
HttpHeaders headers, UriInfo uriInfo,
- byte[] body, String requestId) {
+ byte[] body, String requestId,
+ String principalId, Map<String, Object> authorizerContext) {
ObjectNode event = objectMapper.createObjectNode();
event.put("resource", resourcePath);
event.put("path", path);
@@ -426,6 +456,19 @@ public class ApiGatewayExecuteController {
ctx.put("requestId", requestId);
ctx.put("requestTimeEpoch", System.currentTimeMillis());
ctx.putObject("identity").put("sourceIp", "127.0.0.1");
+ if (principalId != null || (authorizerContext != null && !authorizerContext.isEmpty())) {
+ ObjectNode authorizerNode = ctx.putObject("authorizer");
+ if (principalId != null) {
+ authorizerNode.put("principalId", principalId);
+ }
+ if (authorizerContext != null) {
+ authorizerContext.forEach((key, value) -> {
+ if (value != null) {
+ authorizerNode.put(key, value.toString());
+ }
+ });
+ }
+ }
if (body != null && body.length > 0) {
event.put("body", new String(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.java
new file mode 100644
index 0000000000..180abbe726
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAuthorizerContextIntegrationTest.java
@@ -0,0 +1,320 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayAuthorizerContextIntegrationTest {
+
+ private static final String LAMBDA_BASE_PATH = "/2015-03-31/functions";
+ private static final String AUTHORIZER_FUNCTION = "apigw-authorizer-context-auth";
+ private static final String PROXY_FUNCTION = "apigw-authorizer-context-proxy";
+ private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/lambda-role";
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private static String apiId;
+ private static String rootId;
+ private static String securedResourceId;
+ private static String plainResourceId;
+ private static String authorizerId;
+ private static String deploymentId;
+
+ @Test
+ @Order(1)
+ void createAuthorizerLambda() throws Exception {
+ createNodeLambda(AUTHORIZER_FUNCTION, """
+ exports.handler = async (event) => ({
+ principalId: "test-user",
+ policyDocument: {
+ Version: "2012-10-17",
+ Statement: [{
+ Action: "execute-api:Invoke",
+ Effect: event.authorizationToken === "Bearer deny" ? "Deny" : "Allow",
+ Resource: event.methodArn
+ }]
+ },
+ context: {
+ org_id: "ORG001",
+ sub: "test-user",
+ client_id: "my-client",
+ methodArn: event.methodArn
+ }
+ });
+ """);
+ }
+
+ @Test
+ @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")
+ })
+ });
+ """);
+ }
+
+ @Test
+ @Order(3)
+ void createRestApi() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"name":"authorizer-context-api"}
+ """)
+ .when().post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ }
+
+ @Test
+ @Order(4)
+ void getRootResource() {
+ rootId = given()
+ .when().get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .extract().path("item[0].id");
+ }
+
+ @Test
+ @Order(5)
+ void createResources() {
+ securedResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"secured\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ plainResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"plain\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ }
+
+ @Test
+ @Order(6)
+ void createAuthorizer() {
+ String authorizerUri = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ + "arn:aws:lambda:us-east-1:000000000000:function:" + AUTHORIZER_FUNCTION + "/invocations";
+ authorizerId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "name":"ctx-authorizer",
+ "type":"TOKEN",
+ "authorizerUri":"%s",
+ "identitySource":"method.request.header.Authorization",
+ "authorizerResultTtlInSeconds":0
+ }
+ """.formatted(authorizerUri))
+ .when().post("/restapis/" + apiId + "/authorizers")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ }
+
+ @Test
+ @Order(7)
+ void configureMethodsAndIntegrations() {
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "authorizationType":"CUSTOM",
+ "authorizerId":"%s",
+ "requestParameters":{"method.request.header.Authorization":true}
+ }
+ """.formatted(authorizerId))
+ .when().put("/restapis/" + apiId + "/resources/" + securedResourceId + "/methods/PUT")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"authorizationType":"NONE"}
+ """)
+ .when().put("/restapis/" + apiId + "/resources/" + plainResourceId + "/methods/PUT")
+ .then()
+ .statusCode(201);
+
+ String proxyUri = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ + "arn:aws:lambda:us-east-1:000000000000:function:" + PROXY_FUNCTION + "/invocations";
+ String integrationBody = """
+ {
+ "type":"AWS_PROXY",
+ "httpMethod":"POST",
+ "uri":"%s"
+ }
+ """.formatted(proxyUri);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(integrationBody)
+ .when().put("/restapis/" + apiId + "/resources/" + securedResourceId + "/methods/PUT/integration")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(integrationBody)
+ .when().put("/restapis/" + apiId + "/resources/" + plainResourceId + "/methods/PUT/integration")
+ .then()
+ .statusCode(201);
+ }
+
+ @Test
+ @Order(8)
+ void deployApi() {
+ deploymentId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"description\":\"authorizer-context\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"stageName":"test","deploymentId":"%s"}
+ """.formatted(deploymentId))
+ .when().post("/restapis/" + apiId + "/stages")
+ .then()
+ .statusCode(201);
+ }
+
+ @Test
+ @Order(9)
+ void executeSecuredRoute_propagatesAuthorizerContextAndMethodArn() throws Exception {
+ String response = given()
+ .contentType(ContentType.JSON)
+ .header("Authorization", "Bearer allow")
+ .body("{\"ok\":true}")
+ .when().put("/execute-api/" + apiId + "/test/secured")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ JsonNode payload = OBJECT_MAPPER.readTree(response);
+ JsonNode authorizer = payload.path("authorizer");
+
+ assertTrue(payload.path("hasAuthorizer").asBoolean());
+ assertEquals("test-user", authorizer.path("principalId").asText());
+ assertEquals("ORG001", authorizer.path("org_id").asText());
+ assertEquals("test-user", authorizer.path("sub").asText());
+ assertEquals("my-client", authorizer.path("client_id").asText());
+ assertEquals(
+ "arn:aws:execute-api:us-east-1:000000000000:" + apiId + "/test/PUT/secured",
+ authorizer.path("methodArn").asText());
+ }
+
+ @Test
+ @Order(10)
+ void executePlainRoute_doesNotInjectAuthorizerContext() throws Exception {
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("{\"ok\":true}")
+ .when().put("/execute-api/" + apiId + "/test/plain")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ JsonNode payload = OBJECT_MAPPER.readTree(response);
+ assertFalse(payload.path("hasAuthorizer").asBoolean());
+ assertTrue(payload.path("authorizer").isNull());
+ }
+
+ @Test
+ @Order(11)
+ void executeSecuredRoute_denyStillReturns403() {
+ given()
+ .contentType(ContentType.JSON)
+ .header("Authorization", "Bearer deny")
+ .body("{\"ok\":true}")
+ .when().put("/execute-api/" + apiId + "/test/secured")
+ .then()
+ .statusCode(403);
+ }
+
+ @Test
+ @Order(99)
+ void cleanup() {
+ if (apiId != null) {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+ deleteFunction(AUTHORIZER_FUNCTION);
+ deleteFunction(PROXY_FUNCTION);
+ }
+
+ private static void createNodeLambda(String functionName, String handlerSource) throws Exception {
+ String zipBase64 = Base64.getEncoder().encodeToString(zipEntries(Map.of(
+ "index.js", handlerSource
+ )));
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "FunctionName":"%s",
+ "Runtime":"nodejs20.x",
+ "Role":"%s",
+ "Handler":"index.handler",
+ "Timeout":30,
+ "Code":{"ZipFile":"%s"}
+ }
+ """.formatted(functionName, ROLE_ARN, zipBase64))
+ .when().post(LAMBDA_BASE_PATH)
+ .then()
+ .statusCode(201);
+ }
+
+ private static byte[] zipEntries(Map<String, String> entries) throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {
+ for (Map.Entry<String, String> entry : entries.entrySet()) {
+ zos.putNextEntry(new ZipEntry(entry.getKey()));
+ zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
+ zos.closeEntry();
+ }
+ }
+ return baos.toByteArray();
+ }
+
+ private static void deleteFunction(String functionName) {
+ int statusCode = given()
+ .when().delete(LAMBDA_BASE_PATH + "/" + functionName)
+ .then()
+ .extract().statusCode();
+ assertTrue(statusCode == 204 || statusCode == 404);
+ }
+}