Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(lambda): serialize resource policy mutations (#2430)

Saatvik Arya2314c85b620b
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaPermissionConcurrencyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaPermissionConcurrencyTest.java
new file mode 100644
index 0000000000..3c285858af
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaPermissionConcurrencyTest.java
@@ -0,0 +1,120 @@
+package com.floci.test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.AddPermissionRequest;
+import software.amazon.awssdk.services.lambda.model.AddPermissionResponse;
+import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.FunctionCode;
+import software.amazon.awssdk.services.lambda.model.GetPolicyRequest;
+import software.amazon.awssdk.services.lambda.model.Runtime;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@DisplayName("Lambda - Permission concurrency")
+class LambdaPermissionConcurrencyTest {
+
+ private static final int PERMISSION_COUNT = 16;
+ private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private static LambdaClient lambda;
+ private static String functionName;
+
+ @BeforeAll
+ static void setup() {
+ lambda = TestFixtures.lambdaClient();
+ functionName = TestFixtures.uniqueName("sdk-test-permission-concurrency");
+ lambda.createFunction(CreateFunctionRequest.builder()
+ .functionName(functionName)
+ .runtime(Runtime.NODEJS20_X)
+ .role(ROLE)
+ .handler("index.handler")
+ .code(FunctionCode.builder()
+ .zipFile(SdkBytes.fromByteArray(LambdaUtils.minimalZip()))
+ .build())
+ .build());
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (lambda != null) {
+ try {
+ lambda.deleteFunction(DeleteFunctionRequest.builder()
+ .functionName(functionName)
+ .build());
+ } catch (Exception cleanupError) {
+ System.err.println("Could not delete function " + functionName + ": "
+ + cleanupError.getMessage());
+ }
+ lambda.close();
+ }
+ }
+
+ @Test
+ void concurrentDistinctStatementsAreAllStoredAndSdkResponsesParse() throws Exception {
+ ExecutorService executor = Executors.newFixedThreadPool(PERMISSION_COUNT);
+ CountDownLatch ready = new CountDownLatch(PERMISSION_COUNT);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<AddPermissionResponse>> futures = new ArrayList<>();
+ Set<String> expectedStatementIds = new HashSet<>();
+
+ try {
+ for (int i = 0; i < PERMISSION_COUNT; i++) {
+ String statementId = "ConcurrentPermission" + i;
+ expectedStatementIds.add(statementId);
+ futures.add(executor.submit(() -> {
+ ready.countDown();
+ assertThat(start.await(10, TimeUnit.SECONDS)).isTrue();
+ return lambda.addPermission(AddPermissionRequest.builder()
+ .functionName(functionName)
+ .statementId(statementId)
+ .action("lambda:InvokeFunction")
+ .principal("events.amazonaws.com")
+ .sourceArn("arn:aws:events:us-east-1:000000000000:rule/" + statementId)
+ .build());
+ }));
+ }
+
+ assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
+ start.countDown();
+
+ Set<String> responseStatementIds = new HashSet<>();
+ for (Future<AddPermissionResponse> future : futures) {
+ AddPermissionResponse response = future.get(30, TimeUnit.SECONDS);
+ assertThat(response.statement()).isNotBlank();
+ JsonNode statement = OBJECT_MAPPER.readTree(response.statement());
+ responseStatementIds.add(statement.path("Sid").asText());
+ }
+ assertThat(responseStatementIds).containsExactlyInAnyOrderElementsOf(expectedStatementIds);
+
+ JsonNode policy = OBJECT_MAPPER.readTree(lambda.getPolicy(GetPolicyRequest.builder()
+ .functionName(functionName)
+ .build()).policy());
+ Set<String> storedStatementIds = new HashSet<>();
+ policy.path("Statement").forEach(statement ->
+ storedStatementIds.add(statement.path("Sid").asText()));
+ assertThat(storedStatementIds).containsExactlyInAnyOrderElementsOf(expectedStatementIds);
+ } finally {
+ start.countDown();
+ executor.shutdownNow();
+ }
+ }
+}
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.java
index b1dd4b13a6..c4cd479e42 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
@@ -89,6 +89,7 @@ public class LambdaService {
* emulator workload.
*/
private final ConcurrentHashMap<String, Object> concurrencyOpLocks = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, Object> policyMutationLocks = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Object> versionCounterLocks = new ConcurrentHashMap<>();
/**
@@ -1721,66 +1722,73 @@ public class LambdaService {
public Map<String, Object> addPermission(String region, String functionName, String qualifier, Map<String, Object> request) {
LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier);
- LambdaFunction fn = getFunction(region, ref.name());
- String resourceArn = policyResourceArn(fn, ref.qualifier());
- String statementId = (String) request.get("StatementId");
- if (statementId == null || statementId.isBlank()) {
- throw new AwsException("InvalidParameterValueException", "StatementId is required", 400);
- }
- fn.getPolicies().stream()
- .filter(s -> scopedTo(s, resourceArn))
- .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", resourceArn);
- 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)));
- }
+ LambdaFunction observed = getFunction(region, ref.name());
+ synchronized (lockForPolicyMutation(observed.getFunctionArn())) {
+ LambdaFunction fn = getFunction(region, ref.name());
+ String resourceArn = policyResourceArn(fn, ref.qualifier());
+ String statementId = (String) request.get("StatementId");
+ if (statementId == null || statementId.isBlank()) {
+ throw new AwsException("InvalidParameterValueException", "StatementId is required", 400);
+ }
+ fn.getPolicies().stream()
+ .filter(s -> scopedTo(s, resourceArn))
+ .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", resourceArn);
+ 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;
+ 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, String qualifier) {
LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier);
- LambdaFunction fn = getFunction(region, ref.name());
- String resourceArn = policyResourceArn(fn, ref.qualifier());
- List<Map<String, Object>> statements = fn.getPolicies().stream()
- .filter(s -> scopedTo(s, resourceArn))
- .toList();
- if (statements.isEmpty()) {
- throw new AwsException("ResourceNotFoundException",
- "The resource you requested does not exist.", 404);
+ LambdaFunction observed = getFunction(region, ref.name());
+ synchronized (lockForPolicyMutation(observed.getFunctionArn())) {
+ LambdaFunction fn = getFunction(region, ref.name());
+ String resourceArn = policyResourceArn(fn, ref.qualifier());
+ List<Map<String, Object>> statements = fn.getPolicies().stream()
+ .filter(statement -> scopedTo(statement, resourceArn))
+ .<Map<String, Object>>map(java.util.LinkedHashMap::new)
+ .toList();
+ if (statements.isEmpty()) {
+ throw new AwsException("ResourceNotFoundException",
+ "The resource you requested does not exist.", 404);
+ }
+ Map<String, Object> policy = new java.util.LinkedHashMap<>();
+ policy.put("Version", "2012-10-17");
+ policy.put("Id", "default");
+ policy.put("Statement", statements);
+ return Map.of("policy", policy, "revisionId", fn.getRevisionId());
}
- Map<String, Object> policy = new java.util.LinkedHashMap<>();
- policy.put("Version", "2012-10-17");
- policy.put("Id", "default");
- policy.put("Statement", statements);
- return Map.of("policy", policy, "revisionId", fn.getRevisionId());
}
/**
@@ -1793,29 +1801,41 @@ public class LambdaService {
* identically named statement on an alias or version and leave that one lost.
*/
public void restorePermissionStatement(String region, String functionName, Map<String, Object> statement) {
- LambdaFunction fn = getFunction(region, functionName);
- String statementId = (String) statement.get("Sid");
- String resourceArn = policyResourceArn(fn, null);
- if (statementId != null) {
- fn.getPolicies().removeIf(s -> statementId.equals(s.get("Sid")) && scopedTo(s, resourceArn));
+ LambdaFunction observed = getFunction(region, functionName);
+ synchronized (lockForPolicyMutation(observed.getFunctionArn())) {
+ LambdaFunction fn = getFunction(region, functionName);
+ String statementId = (String) statement.get("Sid");
+ String resourceArn = policyResourceArn(fn, null);
+ if (statementId != null) {
+ fn.getPolicies().removeIf(existing -> statementId.equals(existing.get("Sid"))
+ && scopedTo(existing, resourceArn));
+ }
+ fn.getPolicies().add(statement);
+ functionStore.save(region, fn);
+ LOG.infov("Restored permission {0} on function {1}", statementId, functionName);
}
- fn.getPolicies().add(statement);
- functionStore.save(region, fn);
- LOG.infov("Restored permission {0} on function {1}", statementId, functionName);
}
public void removePermission(String region, String functionName, String qualifier, String statementId) {
LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier);
- LambdaFunction fn = getFunction(region, ref.name());
- String resourceArn = policyResourceArn(fn, ref.qualifier());
- boolean removed = fn.getPolicies()
- .removeIf(s -> statementId.equals(s.get("Sid")) && scopedTo(s, resourceArn));
- if (!removed) {
- throw new AwsException("ResourceNotFoundException",
- "Statement " + statementId + " not found in function " + functionName, 404);
+ LambdaFunction observed = getFunction(region, ref.name());
+ synchronized (lockForPolicyMutation(observed.getFunctionArn())) {
+ LambdaFunction fn = getFunction(region, ref.name());
+ String resourceArn = policyResourceArn(fn, ref.qualifier());
+ boolean removed = fn.getPolicies()
+ .removeIf(statement -> statementId.equals(statement.get("Sid"))
+ && scopedTo(statement, resourceArn));
+ 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);
}
- functionStore.save(region, fn);
- LOG.infov("Removed permission {0} from function {1}", statementId, functionName);
+ }
+
+ private Object lockForPolicyMutation(String functionArn) {
+ return policyMutationLocks.computeIfAbsent(functionArn, key -> new Object());
}
// ──────────────────────────── Tags ────────────────────────────
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
index ed3ba357fd..b63a8349ba 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
@@ -14,9 +14,15 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.file.Path;
import java.util.Base64;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -808,4 +814,75 @@ class LambdaServiceTest {
pool.shutdownNow();
}
}
+
+ @Test
+ void concurrentPolicyRestoreAddAndReadPreserveAllStatements() throws Exception {
+ LambdaFunction function = service.createFunction(REGION, baseRequest("policy-race-fn"));
+ service.addPermission(REGION, function.getFunctionName(), null, Map.of(
+ "StatementId", "baseline",
+ "Action", "lambda:InvokeFunction",
+ "Principal", "events.amazonaws.com"));
+
+ int mutationCount = 16;
+ CountDownLatch start = new CountDownLatch(1);
+ ExecutorService pool = Executors.newFixedThreadPool(8);
+ List<Future<?>> futures = new java.util.ArrayList<>();
+ Set<String> expectedStatementIds = new HashSet<>();
+ expectedStatementIds.add("baseline");
+
+ try {
+ for (int i = 0; i < mutationCount; i++) {
+ String addedId = "added-" + i;
+ String restoredId = "restored-" + i;
+ expectedStatementIds.add(addedId);
+ expectedStatementIds.add(restoredId);
+
+ futures.add(pool.submit(() -> {
+ start.await();
+ service.addPermission(REGION, function.getFunctionName(), null, Map.of(
+ "StatementId", addedId,
+ "Action", "lambda:InvokeFunction",
+ "Principal", "events.amazonaws.com"));
+ return null;
+ }));
+ futures.add(pool.submit(() -> {
+ start.await();
+ service.restorePermissionStatement(REGION, function.getFunctionName(), Map.of(
+ "Sid", restoredId,
+ "Effect", "Allow",
+ "Principal", Map.of("Service", "events.amazonaws.com"),
+ "Action", "lambda:InvokeFunction",
+ "Resource", function.getFunctionArn()));
+ return null;
+ }));
+ }
+ futures.add(pool.submit(() -> {
+ start.await();
+ for (int i = 0; i < mutationCount; i++) {
+ service.getPolicy(REGION, function.getFunctionName(), null);
+ }
+ return null;
+ }));
+
+ start.countDown();
+ for (Future<?> future : futures) {
+ future.get();
+ }
+ } finally {
+ start.countDown();
+ pool.shutdownNow();
+ }
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> policy = (Map<String, Object>) service
+ .getPolicy(REGION, function.getFunctionName(), null)
+ .get("policy");
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> statements = (List<Map<String, Object>>) policy.get("Statement");
+ Set<String> actualStatementIds = statements.stream()
+ .map(statement -> (String) statement.get("Sid"))
+ .collect(java.util.stream.Collectors.toSet());
+
+ assertEquals(expectedStatementIds, actualStatementIds);
+ }
}