Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(sqs): implement AddPermission and RemovePermission (#781)

Stuart Lang39ef0694a4b1
diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java
index 970bce390e..321f618713 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java
@@ -57,12 +57,40 @@ public class SqsJsonHandler {
case "ListDeadLetterSourceQueues" -> handleListDeadLetterSourceQueues(request, region);
case "StartMessageMoveTask" -> handleStartMessageMoveTask(request, region);
case "ListMessageMoveTasks" -> handleListMessageMoveTasks(request, region);
+ case "AddPermission" -> handleAddPermission(request, region);
+ case "RemovePermission" -> handleRemovePermission(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
.build();
};
}
+ private Response handleAddPermission(JsonNode request, String region) {
+ String queueUrl = request.path("QueueUrl").asText(null);
+ String label = request.path("Label").asText(null);
+ List<String> accountIds = jsonNodeToList(request.path("AWSAccountIds"));
+ List<String> actions = jsonNodeToList(request.path("Actions"));
+ sqsService.addPermission(queueUrl, label, accountIds, actions, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleRemovePermission(JsonNode request, String region) {
+ String queueUrl = request.path("QueueUrl").asText(null);
+ String label = request.path("Label").asText(null);
+ sqsService.removePermission(queueUrl, label, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private List<String> jsonNodeToList(JsonNode node) {
+ List<String> values = new ArrayList<>();
+ if (node != null && node.isArray()) {
+ for (JsonNode item : node) {
+ values.add(item.asText());
+ }
+ }
+ return values;
+ }
+
private Response handleCreateQueue(JsonNode request, String region) {
String queueName = request.path("QueueName").asText(null);
Map<String, String> attributes = jsonNodeToMap(request.path("Attributes"));
diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java
index f1a0a41582..ead549aced 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java
@@ -56,11 +56,39 @@ public class SqsQueryHandler {
case "ListDeadLetterSourceQueues" -> handleListDeadLetterSourceQueues(params, region);
case "StartMessageMoveTask" -> handleStartMessageMoveTask(params, region);
case "ListMessageMoveTasks" -> handleListMessageMoveTasks(params, region);
+ case "AddPermission" -> handleAddPermission(params, region);
+ case "RemovePermission" -> handleRemovePermission(params, region);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported by SQS.", AwsNamespaces.SQS, 400);
};
}
+ private Response handleAddPermission(MultivaluedMap<String, String> params, String region) {
+ String queueUrl = getParam(params, "QueueUrl");
+ String label = getParam(params, "Label");
+ List<String> accountIds = collectIndexed(params, "AWSAccountId.");
+ List<String> actions = collectIndexed(params, "ActionName.");
+ sqsService.addPermission(queueUrl, label, accountIds, actions, region);
+ return Response.ok(AwsQueryResponse.envelopeNoResult("AddPermission", null)).build();
+ }
+
+ private Response handleRemovePermission(MultivaluedMap<String, String> params, String region) {
+ String queueUrl = getParam(params, "QueueUrl");
+ String label = getParam(params, "Label");
+ sqsService.removePermission(queueUrl, label, region);
+ return Response.ok(AwsQueryResponse.envelopeNoResult("RemovePermission", null)).build();
+ }
+
+ private List<String> collectIndexed(MultivaluedMap<String, String> params, String prefix) {
+ List<String> values = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String v = getParam(params, prefix + i);
+ if (v == null) break;
+ values.add(v);
+ }
+ return values;
+ }
+
private Response handleCreateQueue(MultivaluedMap<String, String> params, String region) {
String queueName = getParam(params, "QueueName");
Map<String, String> attributes = extractAttributes(params);
diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java
index e1ce68bfd4..f81242af94 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java
@@ -11,6 +11,10 @@ import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.Queue;
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.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -837,6 +841,132 @@ public class SqsService {
LOG.infov("Untagged queue: {0}", queueUrl);
}
+ private static final ObjectMapper POLICY_MAPPER = new ObjectMapper();
+
+ public void addPermission(String queueUrl, String label, List<String> awsAccountIds,
+ List<String> actionNames, String region) {
+ if (label == null || label.isEmpty()) {
+ throw new AwsException("InvalidParameterValue", "Value for parameter Label is invalid.", 400);
+ }
+ if (awsAccountIds == null || awsAccountIds.isEmpty()) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter AWSAccountId.", 400);
+ }
+ if (actionNames == null || actionNames.isEmpty()) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter ActionName.", 400);
+ }
+
+ String storageKey = regionKey(region, queueUrl);
+ Queue queue = queueStore.get(storageKey)
+ .orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
+ "The specified queue does not exist.", 400));
+
+ ObjectNode policy = parsePolicyOrEmpty(queue.getAttributes().get("Policy"));
+ ArrayNode statements = ensureStatementArray(policy);
+
+ for (JsonNode stmt : statements) {
+ if (label.equals(stmt.path("Sid").asText(null))) {
+ throw new AwsException("InvalidParameterValue",
+ "Value " + label + " for parameter Label is invalid. " +
+ "Reason: Already exists.", 400);
+ }
+ }
+
+ ObjectNode statement = POLICY_MAPPER.createObjectNode();
+ statement.put("Sid", label);
+ statement.put("Effect", "Allow");
+ ObjectNode principal = statement.putObject("Principal");
+ ArrayNode awsArns = principal.putArray("AWS");
+ for (String accountId : awsAccountIds) {
+ awsArns.add("arn:aws:iam::" + accountId + ":root");
+ }
+ ArrayNode actions = statement.putArray("Action");
+ for (String action : actionNames) {
+ actions.add("SQS:" + action);
+ }
+ statement.put("Resource", regionResolver.buildArn("sqs", region, queue.getQueueName()));
+ statements.add(statement);
+
+ queue.getAttributes().put("Policy", policy.toString());
+ queue.setLastModifiedTimestamp(Instant.now());
+ queueStore.put(storageKey, queue);
+ LOG.infov("Added permission {0} to queue {1}", label, queueUrl);
+ }
+
+ public void removePermission(String queueUrl, String label, String region) {
+ if (label == null || label.isEmpty()) {
+ throw new AwsException("InvalidParameterValue", "Value for parameter Label is invalid.", 400);
+ }
+
+ String storageKey = regionKey(region, queueUrl);
+ Queue queue = queueStore.get(storageKey)
+ .orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
+ "The specified queue does not exist.", 400));
+
+ ObjectNode policy = parsePolicyOrEmpty(queue.getAttributes().get("Policy"));
+ ArrayNode statements = ensureStatementArray(policy);
+
+ int removeIndex = -1;
+ for (int i = 0; i < statements.size(); i++) {
+ if (label.equals(statements.get(i).path("Sid").asText(null))) {
+ removeIndex = i;
+ break;
+ }
+ }
+ if (removeIndex < 0) {
+ throw new AwsException("InvalidParameterValue",
+ "Value " + label + " for parameter Label is invalid. " +
+ "Reason: can't find label on existing policy.", 400);
+ }
+ statements.remove(removeIndex);
+
+ if (statements.isEmpty()) {
+ queue.getAttributes().remove("Policy");
+ } else {
+ queue.getAttributes().put("Policy", policy.toString());
+ }
+ queue.setLastModifiedTimestamp(Instant.now());
+ queueStore.put(storageKey, queue);
+ LOG.infov("Removed permission {0} from queue {1}", label, queueUrl);
+ }
+
+ private static ObjectNode parsePolicyOrEmpty(String raw) {
+ if (raw == null || raw.isBlank()) {
+ ObjectNode policy = POLICY_MAPPER.createObjectNode();
+ policy.put("Version", "2012-10-17");
+ policy.putArray("Statement");
+ return policy;
+ }
+ JsonNode parsed;
+ try {
+ parsed = POLICY_MAPPER.readTree(raw);
+ } catch (Exception e) {
+ throw new AwsException("InvalidAttributeValue",
+ "Invalid value for the parameter Policy.", 400);
+ }
+ if (!(parsed instanceof ObjectNode obj)) {
+ throw new AwsException("InvalidAttributeValue",
+ "Invalid value for the parameter Policy.", 400);
+ }
+ if (!obj.has("Version")) {
+ obj.put("Version", "2012-10-17");
+ }
+ return obj;
+ }
+
+ private static ArrayNode ensureStatementArray(ObjectNode policy) {
+ JsonNode existing = policy.get("Statement");
+ if (existing instanceof ArrayNode arr) {
+ return arr;
+ }
+ ArrayNode arr = policy.putArray("Statement");
+ if (existing instanceof ObjectNode singleStatement) {
+ arr.add(singleStatement);
+ }
+ return arr;
+ }
+
public Map<String, String> listQueueTags(String queueUrl, String region) {
String storageKey = regionKey(region, queueUrl);
Queue queue = queueStore.get(storageKey)
diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java
index c0017dd929..cd390a32d4 100644
--- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java
@@ -475,6 +475,84 @@ class SqsServiceTest {
() -> sqsService.sendMessage(queue.getQueueUrl(), body, 0, null, null, attrs, "us-east-1"));
}
+ @Test
+ void addPermission_appendsLabelledStatementToPolicy() {
+ Queue queue = sqsService.createQueue("perm-queue", null);
+ sqsService.addPermission(queue.getQueueUrl(), "share",
+ List.of("111122223333"), List.of("SendMessage", "ReceiveMessage"), "us-east-1");
+
+ String policy = sqsService.getQueueAttributes(queue.getQueueUrl(),
+ List.of("Policy"), "us-east-1").get("Policy");
+ assertNotNull(policy, "Policy attribute must be set after AddPermission");
+ assertTrue(policy.contains("\"Sid\":\"share\""));
+ assertTrue(policy.contains("arn:aws:iam::111122223333:root"));
+ assertTrue(policy.contains("SQS:SendMessage"));
+ assertTrue(policy.contains("SQS:ReceiveMessage"));
+ }
+
+ @Test
+ void addPermission_duplicateLabel_throws() {
+ Queue queue = sqsService.createQueue("perm-queue", null);
+ sqsService.addPermission(queue.getQueueUrl(), "share",
+ List.of("111122223333"), List.of("SendMessage"), "us-east-1");
+ AwsException ex = assertThrows(AwsException.class, () ->
+ sqsService.addPermission(queue.getQueueUrl(), "share",
+ List.of("444455556666"), List.of("ReceiveMessage"), "us-east-1"));
+ assertEquals("InvalidParameterValue", ex.getErrorCode());
+ }
+
+ @Test
+ void addPermission_queueDoesNotExist_throws() {
+ AwsException ex = assertThrows(AwsException.class, () ->
+ sqsService.addPermission(BASE_URL + "/000000000000/missing", "share",
+ List.of("111122223333"), List.of("SendMessage"), "us-east-1"));
+ assertEquals("AWS.SimpleQueueService.NonExistentQueue", ex.getErrorCode());
+ }
+
+ @Test
+ void removePermission_removesLabelledStatement() {
+ Queue queue = sqsService.createQueue("perm-queue", null);
+ sqsService.addPermission(queue.getQueueUrl(), "a",
+ List.of("111122223333"), List.of("SendMessage"), "us-east-1");
+ sqsService.addPermission(queue.getQueueUrl(), "b",
+ List.of("444455556666"), List.of("ReceiveMessage"), "us-east-1");
+
+ sqsService.removePermission(queue.getQueueUrl(), "a", "us-east-1");
+
+ String policy = sqsService.getQueueAttributes(queue.getQueueUrl(),
+ List.of("Policy"), "us-east-1").get("Policy");
+ assertNotNull(policy);
+ assertFalse(policy.contains("\"Sid\":\"a\""));
+ assertTrue(policy.contains("\"Sid\":\"b\""));
+ }
+
+ @Test
+ void removePermission_lastStatement_removesPolicyAttribute() {
+ Queue queue = sqsService.createQueue("perm-queue", null);
+ sqsService.addPermission(queue.getQueueUrl(), "only",
+ List.of("111122223333"), List.of("SendMessage"), "us-east-1");
+ sqsService.removePermission(queue.getQueueUrl(), "only", "us-east-1");
+
+ String policy = sqsService.getQueueAttributes(queue.getQueueUrl(),
+ List.of("Policy"), "us-east-1").get("Policy");
+ assertNull(policy, "Policy must be removed when last statement is dropped");
+ }
+
+ @Test
+ void removePermission_unknownLabel_throws() {
+ Queue queue = sqsService.createQueue("perm-queue", null);
+ AwsException ex = assertThrows(AwsException.class, () ->
+ sqsService.removePermission(queue.getQueueUrl(), "ghost", "us-east-1"));
+ assertEquals("InvalidParameterValue", ex.getErrorCode());
+ }
+
+ @Test
+ void removePermission_queueDoesNotExist_throws() {
+ AwsException ex = assertThrows(AwsException.class, () ->
+ sqsService.removePermission(BASE_URL + "/000000000000/missing", "share", "us-east-1"));
+ assertEquals("AWS.SimpleQueueService.NonExistentQueue", ex.getErrorCode());
+ }
+
@Test
void purgeQueueWithClearFifoDelegatesToSnsForFifoDedupOnSubscribedTopics() {
final var sns = mock(SnsService.class);