Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambda): add AddPermission, GetPolicy, ListTags, ListLayerVersions, etc endpoints (#223)
Hector Venturac79f02f26f66
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.javaindex 4b3dd71c4a..35e9a06679 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java@@ -370,6 +370,60 @@ public class LambdaController {return Response.noContent().build();}+ // ──────────────────────────── Permissions (Policy) ────────────────────────────++ @POST+ @Path("/functions/{functionName}/policy")+ public Response addPermission(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName,+ String body) {+ String region = regionResolver.resolveRegion(headers);+ try {+ @SuppressWarnings("unchecked")+ Map<String, Object> request = objectMapper.readValue(body, Map.class);+ Map<String, Object> statement = lambdaService.addPermission(region, functionName, request);+ String statementJson = objectMapper.writeValueAsString(statement);+ ObjectNode root = objectMapper.createObjectNode();+ root.put("Statement", statementJson);+ return Response.status(201).entity(root).build();+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ throw new AwsException("InvalidParameterValueException", e.getMessage(), 400);+ }+ }++ @GET+ @Path("/functions/{functionName}/policy")+ public Response getPolicy(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName) {+ String region = regionResolver.resolveRegion(headers);+ try {+ Map<String, Object> data = lambdaService.getPolicy(region, functionName);+ @SuppressWarnings("unchecked")+ Map<String, Object> policy = (Map<String, Object>) data.get("policy");+ String policyJson = objectMapper.writeValueAsString(policy);+ ObjectNode root = objectMapper.createObjectNode();+ root.put("Policy", policyJson);+ root.put("RevisionId", (String) data.get("revisionId"));+ return Response.ok(root).build();+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ throw new AwsException("ServiceException", e.getMessage(), 500);+ }+ }++ @DELETE+ @Path("/functions/{functionName}/policy/{statementId}")+ public Response removePermission(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName,+ @PathParam("statementId") String statementId) {+ String region = regionResolver.resolveRegion(headers);+ lambdaService.removePermission(region, functionName, statementId);+ return Response.noContent().build();+ }+// ──────────────────────────── Helper ────────────────────────────private Map<String, Object> buildAliasResponse(LambdaAlias alias) {diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerController.javanew file mode 100644index 0000000000..d13b1326ec--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerController.java@@ -0,0 +1,47 @@+package io.github.hectorvent.floci.services.lambda;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import jakarta.inject.Inject;+import jakarta.ws.rs.Consumes;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++/**+ * Lambda layer endpoints — use the /2018-10-31 API version prefix.+ *+ * ListLayers: GET /2018-10-31/layers+ * ListLayerVersions: GET /2018-10-31/layers/{LayerName}/versions+ */+@Path("/2018-10-31")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class LambdaLayerController {++ private final ObjectMapper objectMapper;++ @Inject+ public LambdaLayerController(ObjectMapper objectMapper) {+ this.objectMapper = objectMapper;+ }++ @GET+ @Path("/layers")+ public Response listLayers() {+ ObjectNode root = objectMapper.createObjectNode();+ root.putArray("Layers");+ return Response.ok(root).build();+ }++ @GET+ @Path("/layers/{layerName}/versions")+ public Response listLayerVersions(@PathParam("layerName") String layerName) {+ ObjectNode root = objectMapper.createObjectNode();+ root.putArray("LayerVersions");+ return Response.ok(root).build();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.javaindex 8c2456e9db..fa0cbf0717 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java@@ -649,6 +649,100 @@ public class LambdaService {extractZipCode(fn, Base64.getEncoder().encodeToString(obj.getData()));}+ // ──────────────────────────── Permissions (Policy) ────────────────────────────++ public Map<String, Object> addPermission(String region, String functionName, Map<String, Object> request) {+ LambdaFunction fn = getFunction(region, functionName);+ String statementId = (String) request.get("StatementId");+ if (statementId == null || statementId.isBlank()) {+ throw new AwsException("InvalidParameterValueException", "StatementId is required", 400);+ }+ fn.getPolicies().stream()+ .filter(s -> statementId.equals(s.get("Sid")))+ .findFirst()+ .ifPresent(s -> {+ throw new AwsException("ResourceConflictException",+ "The statement id (" + statementId + ") already exists. Please try again with a new Statement Id.", 409);+ });++ String principal = (String) request.get("Principal");+ String action = (String) request.get("Action");+ String sourceArn = (String) request.get("SourceArn");+ String sourceAccount = (String) request.get("SourceAccount");++ Map<String, Object> statement = new java.util.LinkedHashMap<>();+ statement.put("Sid", statementId);+ statement.put("Effect", "Allow");+ if (principal != null && principal.contains(".")) {+ statement.put("Principal", Map.of("Service", principal));+ } else if (principal != null && principal.startsWith("arn:")) {+ statement.put("Principal", Map.of("AWS", principal));+ } else {+ statement.put("Principal", principal);+ }+ statement.put("Action", action);+ statement.put("Resource", fn.getFunctionArn());+ if (sourceArn != null) {+ statement.put("Condition", Map.of("ArnLike", Map.of("AWS:SourceArn", sourceArn)));+ } else if (sourceAccount != null) {+ statement.put("Condition", Map.of("StringEquals", Map.of("AWS:SourceAccount", sourceAccount)));+ }++ fn.getPolicies().add(statement);+ functionStore.save(region, fn);+ LOG.infov("Added permission {0} to function {1}", statementId, functionName);+ return statement;+ }++ public Map<String, Object> getPolicy(String region, String functionName) {+ LambdaFunction fn = getFunction(region, functionName);+ if (fn.getPolicies().isEmpty()) {+ throw new AwsException("ResourceNotFoundException",+ "Function not found: " + functionName, 404);+ }+ Map<String, Object> policy = new java.util.LinkedHashMap<>();+ policy.put("Version", "2012-10-17");+ policy.put("Id", "default");+ policy.put("Statement", fn.getPolicies());+ return Map.of("policy", policy, "revisionId", fn.getRevisionId());+ }++ public void removePermission(String region, String functionName, String statementId) {+ LambdaFunction fn = getFunction(region, functionName);+ boolean removed = fn.getPolicies().removeIf(s -> statementId.equals(s.get("Sid")));+ if (!removed) {+ throw new AwsException("ResourceNotFoundException",+ "Statement " + statementId + " not found in function " + functionName, 404);+ }+ functionStore.save(region, fn);+ LOG.infov("Removed permission {0} from function {1}", statementId, functionName);+ }++ // ──────────────────────────── Tags ────────────────────────────++ public Map<String, String> listTags(String functionArn) {+ String[] parts = functionArn.split(":");+ LambdaFunction fn = getFunction(parts[3], parts[6]);+ return fn.getTags() != null ? fn.getTags() : Map.of();+ }++ public void tagResource(String functionArn, Map<String, String> tags) {+ String[] parts = functionArn.split(":");+ LambdaFunction fn = getFunction(parts[3], parts[6]);+ if (fn.getTags() == null) fn.setTags(new java.util.HashMap<>());+ fn.getTags().putAll(tags);+ functionStore.save(parts[3], fn);+ }++ public void untagResource(String functionArn, List<String> tagKeys) {+ String[] parts = functionArn.split(":");+ LambdaFunction fn = getFunction(parts[3], parts[6]);+ if (fn.getTags() != null) {+ tagKeys.forEach(fn.getTags()::remove);+ }+ functionStore.save(parts[3], fn);+ }+private int toInt(Object value, int defaultValue) {if (value == null) return defaultValue;if (value instanceof Number n) return n.intValue();diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.javanew file mode 100644index 0000000000..69b6c6993c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java@@ -0,0 +1,79 @@+package io.github.hectorvent.floci.services.lambda;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import jakarta.inject.Inject;+import jakarta.ws.rs.Consumes;+import jakarta.ws.rs.DELETE;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.POST;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.QueryParam;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++import java.util.List;+import java.util.Map;++/**+ * Lambda tag endpoints — use the /2017-03-31 API version prefix.+ *+ * TagResource: POST /2017-03-31/tags/{ARN}+ * ListTags: GET /2017-03-31/tags/{ARN}+ * UntagResource: DELETE /2017-03-31/tags/{ARN}?tagKeys=...+ */+@Path("/2017-03-31")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class LambdaTagController {++ private final LambdaService lambdaService;+ private final ObjectMapper objectMapper;++ @Inject+ public LambdaTagController(LambdaService lambdaService, ObjectMapper objectMapper) {+ this.lambdaService = lambdaService;+ this.objectMapper = objectMapper;+ }++ @GET+ @Path("/tags/{arn}")+ public Response listTags(@PathParam("arn") String arn) {+ Map<String, String> tags = lambdaService.listTags(arn);+ ObjectNode root = objectMapper.createObjectNode();+ ObjectNode tagsNode = root.putObject("Tags");+ tags.forEach(tagsNode::put);+ return Response.ok(root).build();+ }++ @POST+ @Path("/tags/{arn}")+ public Response tagResource(@PathParam("arn") String arn, String body) {+ try {+ @SuppressWarnings("unchecked")+ Map<String, Object> request = objectMapper.readValue(body, Map.class);+ @SuppressWarnings("unchecked")+ Map<String, String> tags = (Map<String, String>) request.get("Tags");+ if (tags == null) {+ throw new AwsException("InvalidParameterValueException", "Tags is required", 400);+ }+ lambdaService.tagResource(arn, tags);+ return Response.noContent().build();+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ throw new AwsException("InvalidParameterValueException", e.getMessage(), 400);+ }+ }++ @DELETE+ @Path("/tags/{arn}")+ public Response untagResource(@PathParam("arn") String arn,+ @QueryParam("tagKeys") List<String> tagKeys) {+ lambdaService.untagResource(arn, tagKeys);+ return Response.noContent().build();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.javaindex 66b1625a86..ecb63b51b0 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java@@ -4,7 +4,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import io.quarkus.runtime.annotations.RegisterForReflection;+import java.util.ArrayList;import java.util.HashMap;+import java.util.List;import java.util.Map;@RegisterForReflection@@ -28,6 +30,7 @@ public class LambdaFunction {private String codeLocalPath;private Map<String, String> environment = new HashMap<>();private Map<String, String> tags = new HashMap<>();+ private List<Map<String, Object>> policies = new ArrayList<>();private long lastModified;private String revisionId;private String version = "$LATEST";@@ -90,6 +93,9 @@ public class LambdaFunction {public Map<String, String> getTags() { return tags; }public void setTags(Map<String, String> tags) { this.tags = tags; }+ public List<Map<String, Object>> getPolicies() { return policies; }+ public void setPolicies(List<Map<String, Object>> policies) { this.policies = policies; }+public long getLastModified() { return lastModified; }public void setLastModified(long lastModified) { this.lastModified = lastModified; }diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.javaindex 874c65c1f0..4016974815 100644--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java@@ -277,27 +277,16 @@ class EventBridgeSchedulerIntegrationTest {return new EmulatorConfig() {@Overridepublic String baseUrl() { return "http://localhost:4566"; }-@Override- public Optional<String> hostname() {- return Optional.empty();- }-+ public Optional<String> hostname() { return Optional.empty(); }@Overridepublic String defaultRegion() { return REGION; }@Overridepublic String defaultAccountId() { return ACCOUNT; }-@Override- public int maxRequestSize() {- return 0;- }-+ public int maxRequestSize() { return 512; }@Override- public String ecrBaseUri() {- return "";- }-+ public String ecrBaseUri() { return ""; }@Overridepublic StorageConfig storage() { return null; }@Override@@ -305,12 +294,6 @@ class EventBridgeSchedulerIntegrationTest {@Overridepublic ServicesConfig services() { return null; }@Override- public String ecrBaseUri() { return ""; }- @Override- public int maxRequestSize() { return 512; }- @Override- public java.util.Optional<String> hostname() { return java.util.Optional.empty(); }- @Overridepublic EmulatorConfig.InitHooksConfig initHooks() { return null; }};}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPermissionTagLayerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPermissionTagLayerIntegrationTest.javanew file mode 100644index 0000000000..3b7576fffc--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPermissionTagLayerIntegrationTest.java@@ -0,0 +1,311 @@+package io.github.hectorvent.floci.services.lambda;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.quarkus.test.junit.QuarkusTest;+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.util.zip.ZipEntry;+import java.util.zip.ZipOutputStream;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.*;++/**+ * Verifies AddPermission / GetPolicy / RemovePermission, TagResource /+ * UntagResource / ListTags, and the ListLayers / ListLayerVersions stub endpoints.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class LambdaPermissionTagLayerIntegrationTest {++ private static final String FN = "perm-test-fn";+ private static final String FN_ARN = "arn:aws:lambda:us-east-1:000000000000:function:" + FN;+ private static final String STMT_ID = "allow-apigw";+ private static final String STMT_ID2 = "allow-s3";++ // ── setup ─────────────────────────────────────────────────────────────────++ private static byte[] minimalZip() throws Exception {+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {+ zos.putNextEntry(new ZipEntry("index.js"));+ zos.write("exports.handler = async () => ({});".getBytes());+ zos.closeEntry();+ }+ return baos.toByteArray();+ }++ @Test+ @Order(1)+ void createFunction() throws Exception {+ byte[] zip = minimalZip();+ String zipBase64 = java.util.Base64.getEncoder().encodeToString(zip);++ given()+ .contentType("application/json")+ .body("""+ {+ "FunctionName": "%s",+ "Runtime": "nodejs20.x",+ "Role": "arn:aws:iam::000000000000:role/lambda-role",+ "Handler": "index.handler",+ "Code": { "ZipFile": "%s" }+ }+ """.formatted(FN, zipBase64))+ .when()+ .post("/2015-03-31/functions")+ .then()+ .statusCode(201)+ .body("FunctionName", equalTo(FN));+ }++ // ── AddPermission ─────────────────────────────────────────────────────────++ @Test+ @Order(2)+ void addPermission_returnsStatement() {+ given()+ .contentType("application/json")+ .body("""+ {+ "StatementId": "%s",+ "Action": "lambda:InvokeFunction",+ "Principal": "apigateway.amazonaws.com",+ "SourceArn": "arn:aws:execute-api:us-east-1:000000000000:api/*"+ }+ """.formatted(STMT_ID))+ .when()+ .post("/2015-03-31/functions/" + FN + "/policy")+ .then()+ .statusCode(201)+ .body("Statement", notNullValue());+ }++ @Test+ @Order(3)+ void addPermission_duplicateStatementId_returns409() {+ given()+ .contentType("application/json")+ .body("""+ {+ "StatementId": "%s",+ "Action": "lambda:InvokeFunction",+ "Principal": "apigateway.amazonaws.com"+ }+ """.formatted(STMT_ID))+ .when()+ .post("/2015-03-31/functions/" + FN + "/policy")+ .then()+ .statusCode(409);+ }++ @Test+ @Order(4)+ void addSecondPermission() {+ given()+ .contentType("application/json")+ .body("""+ {+ "StatementId": "%s",+ "Action": "lambda:InvokeFunction",+ "Principal": "s3.amazonaws.com",+ "SourceAccount": "000000000000"+ }+ """.formatted(STMT_ID2))+ .when()+ .post("/2015-03-31/functions/" + FN + "/policy")+ .then()+ .statusCode(201);+ }++ // ── GetPolicy ─────────────────────────────────────────────────────────────++ @Test+ @Order(5)+ void getPolicy_returnsBothStatements() throws Exception {+ String response = given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/policy")+ .then()+ .statusCode(200)+ .body("Policy", notNullValue())+ .body("RevisionId", notNullValue())+ .extract().body().asString();++ // Policy is a JSON string — parse it and verify statements+ ObjectMapper om = new ObjectMapper();+ String policyJson = om.readTree(response).get("Policy").asText();+ var policy = om.readTree(policyJson);+ assert policy.get("Statement").size() == 2;+ }++ @Test+ @Order(6)+ void getPolicy_nonExistentFunction_returns404() {+ given()+ .when()+ .get("/2015-03-31/functions/does-not-exist/policy")+ .then()+ .statusCode(404);+ }++ // ── RemovePermission ──────────────────────────────────────────────────────++ @Test+ @Order(7)+ void removePermission_removesStatement() {+ given()+ .when()+ .delete("/2015-03-31/functions/" + FN + "/policy/" + STMT_ID)+ .then()+ .statusCode(204);+ }++ @Test+ @Order(8)+ void getPolicy_afterRemove_showsOneStatement() throws Exception {+ String response = given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/policy")+ .then()+ .statusCode(200)+ .extract().body().asString();++ ObjectMapper om = new ObjectMapper();+ String policyJson = om.readTree(response).get("Policy").asText();+ var policy = om.readTree(policyJson);+ assert policy.get("Statement").size() == 1;+ }++ @Test+ @Order(9)+ void removePermission_nonExistentStatement_returns404() {+ given()+ .when()+ .delete("/2015-03-31/functions/" + FN + "/policy/nonexistent-stmt")+ .then()+ .statusCode(404);+ }++ @Test+ @Order(10)+ void removeLastPermission() {+ given()+ .when()+ .delete("/2015-03-31/functions/" + FN + "/policy/" + STMT_ID2)+ .then()+ .statusCode(204);+ }++ @Test+ @Order(11)+ void getPolicy_noStatements_returns404() {+ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/policy")+ .then()+ .statusCode(404);+ }++ // ── TagResource / UntagResource / ListTags ────────────────────────────────++ @Test+ @Order(12)+ void listTags_initiallyEmpty() {+ given()+ .when()+ .get("/2017-03-31/tags/" + FN_ARN)+ .then()+ .statusCode(200)+ .body("Tags", anEmptyMap());+ }++ @Test+ @Order(13)+ void tagResource_addsTags() {+ given()+ .contentType("application/json")+ .body("""+ {"Tags": {"env": "test", "team": "platform"}}+ """)+ .when()+ .post("/2017-03-31/tags/" + FN_ARN)+ .then()+ .statusCode(204);+ }++ @Test+ @Order(14)+ void listTags_showsAddedTags() {+ given()+ .when()+ .get("/2017-03-31/tags/" + FN_ARN)+ .then()+ .statusCode(200)+ .body("Tags.env", equalTo("test"))+ .body("Tags.team", equalTo("platform"));+ }++ @Test+ @Order(15)+ void untagResource_removesOneTag() {+ given()+ .queryParam("tagKeys", "env")+ .when()+ .delete("/2017-03-31/tags/" + FN_ARN)+ .then()+ .statusCode(204);+ }++ @Test+ @Order(16)+ void listTags_afterUntag_showsRemainingTag() {+ given()+ .when()+ .get("/2017-03-31/tags/" + FN_ARN)+ .then()+ .statusCode(200)+ .body("Tags.env", nullValue())+ .body("Tags.team", equalTo("platform"));+ }++ // ── ListLayers / ListLayerVersions ────────────────────────────────────────++ @Test+ @Order(17)+ void listLayers_returnsEmptyList() {+ given()+ .when()+ .get("/2018-10-31/layers")+ .then()+ .statusCode(200)+ .body("Layers", empty());+ }++ @Test+ @Order(18)+ void listLayerVersions_returnsEmptyList() {+ given()+ .when()+ .get("/2018-10-31/layers/my-layer/versions")+ .then()+ .statusCode(200)+ .body("LayerVersions", empty());+ }++ // ── cleanup ───────────────────────────────────────────────────────────────++ @Test+ @Order(20)+ void deleteFunction() {+ given()+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(204);+ }+}