Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(logs): add AssociateKmsKey and DisassociateKmsKey for log groups (#2584)

Sam Fakhreddine4435c6284859
diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md
index 0ee7b457fd..65f051b5bb 100644
--- a/docs/services/cloudwatch.md
+++ b/docs/services/cloudwatch.md
@@ -25,6 +25,8 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics.
| `FilterLogEvents` | Search log events with a filter pattern |
| `PutRetentionPolicy` | Set log retention (days) |
| `DeleteRetentionPolicy` | Remove log retention policy |
+| `AssociateKmsKey` | Associate a KMS key with a log group (`logGroupName` or `resourceIdentifier`) |
+| `DisassociateKmsKey` | Remove a log group's KMS key association |
| `TagLogGroup` | Tag a log group |
| `UntagLogGroup` | Remove tags |
| `ListTagsLogGroup` | List tags |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
index 6136b61668..b4806531b7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
@@ -56,6 +56,8 @@ public class CloudWatchLogsHandler {
case "PutSubscriptionFilter" -> handlePutSubscriptionFilter(request, region);
case "DescribeSubscriptionFilters" -> handleDescribeSubscriptionFilters(request, region);
case "DeleteSubscriptionFilter" -> handleDeleteSubscriptionFilter(request, region);
+ case "AssociateKmsKey" -> handleAssociateKmsKey(request, region);
+ case "DisassociateKmsKey" -> handleDisassociateKmsKey(request, region);
case "PutResourcePolicy" -> handlePutResourcePolicy(request, region);
case "DescribeResourcePolicies" -> handleDescribeResourcePolicies(region);
case "GetDataProtectionPolicy" -> handleGetDataProtectionPolicy(request, region);
@@ -74,7 +76,8 @@ public class CloudWatchLogsHandler {
? request.path("retentionInDays").asInt() : null;
boolean deletionProtectionEnabled = request.path("deletionProtectionEnabled").asBoolean(false);
Map<String, String> tags = extractTags(request.path("tags"));
- logsService.createLogGroup(name, retentionInDays, tags, deletionProtectionEnabled, region);
+ String kmsKeyId = request.path("kmsKeyId").asText(null);
+ logsService.createLogGroup(name, retentionInDays, tags, deletionProtectionEnabled, kmsKeyId, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -113,6 +116,9 @@ public class CloudWatchLogsHandler {
node.put("retentionInDays", g.getRetentionInDays());
}
node.put("deletionProtectionEnabled", g.isDeletionProtectionEnabled());
+ if (g.getKmsKeyId() != null) {
+ node.put("kmsKeyId", g.getKmsKeyId());
+ }
node.put("storedBytes", 0);
node.put("metricFilterCount", 0);
groupsArray.add(node);
@@ -209,6 +215,7 @@ public class CloudWatchLogsHandler {
String streamName = request.path("logStreamName").asText();
List<Map<String, Object>> events = new ArrayList<>();
+ requireListSize(request.path("logEvents"), "logEvents", 1, 10000);
request.path("logEvents").forEach(evt -> {
Map<String, Object> event = new HashMap<>();
event.put("timestamp", evt.path("timestamp").asLong());
@@ -250,6 +257,9 @@ public class CloudWatchLogsHandler {
String nextToken = request.has("nextToken") ? request.path("nextToken").asText(null) : null;
List<String> streamNames = new ArrayList<>();
+ if (request.hasNonNull("logStreamNames")) {
+ requireListSize(request.path("logStreamNames"), "logStreamNames", 1, 100);
+ }
request.path("logStreamNames").forEach(n -> streamNames.add(resolveLogStreamName(n.asText(null))));
CloudWatchLogsService.FilteredLogEventsResult result =
@@ -352,6 +362,52 @@ public class CloudWatchLogsHandler {
return Response.ok(response).build();
}
+ private Response handleAssociateKmsKey(JsonNode request, String region) {
+ String groupName = resolveKmsTargetLogGroupName(request);
+ String kmsKeyId = request.path("kmsKeyId").asText(null);
+ logsService.associateKmsKey(groupName, kmsKeyId, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleDisassociateKmsKey(JsonNode request, String region) {
+ logsService.disassociateKmsKey(resolveKmsTargetLogGroupName(request), region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ /**
+ * Associate/DisassociateKmsKey are the odd ones out in the Logs API: their ARN
+ * alternative is {@code resourceIdentifier}, not the {@code logGroupIdentifier}
+ * the query operations take. AWS requires exactly one of logGroupName or
+ * resourceIdentifier — neither, or both, is an InvalidParameterException.
+ */
+ private String resolveKmsTargetLogGroupName(JsonNode request) {
+ // A present-but-blank member counts as PRESENT: the model pins both fields to
+ // min length 1, so blank never silently degrades to "absent" and hands the
+ // mutation to the other identifier.
+ boolean hasName = request.hasNonNull("logGroupName");
+ boolean hasResourceIdentifier = request.hasNonNull("resourceIdentifier");
+ if (hasName == hasResourceIdentifier) {
+ throw new AwsException("InvalidParameterException",
+ "Exactly one of logGroupName or resourceIdentifier is required.", 400);
+ }
+ String value = request.path(hasName ? "logGroupName" : "resourceIdentifier").asText();
+ if (value.isBlank()) {
+ throw new AwsException("InvalidParameterException",
+ (hasName ? "logGroupName" : "resourceIdentifier") + " must not be blank.", 400);
+ }
+ // resourceIdentifier also models the account-wide "arn:...:query-result:*" form,
+ // which targets encryption of future GetQueryResults output rather than a log
+ // group. That is a genuinely separate feature Floci does not implement; reject it
+ // explicitly rather than letting extractLogGroupNameFromArn (which only recognizes
+ // :log-group:) pass it through unchanged and turn it into a misleading
+ // ResourceNotFoundException naming a log group the caller never specified.
+ if (!hasName && value.contains(":query-result:")) {
+ throw new AwsException("InvalidParameterException",
+ "resourceIdentifier of the query-result form is not supported.", 400);
+ }
+ return extractLogGroupNameFromArn(value);
+ }
+
private Response handlePutRetentionPolicy(JsonNode request, String region) {
String groupName = request.path("logGroupName").asText();
int days = request.path("retentionInDays").asInt();
@@ -426,6 +482,10 @@ public class CloudWatchLogsHandler {
String filterPattern = request.path("filterPattern").asText();
String destinationArn = request.path("destinationArn").asText();
String distribution = request.has("distribution") ? request.path("distribution").asText(null) : null;
+ if (distribution != null && !"Random".equals(distribution) && !"ByLogStream".equals(distribution)) {
+ throw new AwsException("InvalidParameterException",
+ "distribution must be Random or ByLogStream.", 400);
+ }
logsService.putSubscriptionFilter(logGroupName, filterName, filterPattern, destinationArn, distribution, region);
return Response.ok(objectMapper.createObjectNode()).build();
@@ -551,4 +611,13 @@ public class CloudWatchLogsHandler {
return tags;
}
+ /** Enforces a modeled list min/max with the InvalidParameterException these operations model. */
+ private static void requireListSize(JsonNode list,
+ String member, int min, int max) {
+ int size = list == null || list.isNull() || !list.isArray() ? 0 : list.size();
+ if (size < min || size > max) {
+ throw new AwsException("InvalidParameterException",
+ member + " must contain between " + min + " and " + max + " entries.", 400);
+ }
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
index 0cf95999e3..a1f8e69132 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
@@ -167,7 +167,12 @@ public class CloudWatchLogsService implements ResourceProvider {
public void createLogGroup(String name, Integer retentionInDays, Map<String, String> tags,
boolean deletionProtectionEnabled, String region) {
- createLogGroupForAccount(null, name, retentionInDays, tags, deletionProtectionEnabled, region);
+ createLogGroup(name, retentionInDays, tags, deletionProtectionEnabled, null, region);
+ }
+
+ public void createLogGroup(String name, Integer retentionInDays, Map<String, String> tags,
+ boolean deletionProtectionEnabled, String kmsKeyId, String region) {
+ createLogGroupForAccount(null, name, retentionInDays, tags, deletionProtectionEnabled, kmsKeyId, region);
}
public void createLogGroupForAccount(
@@ -179,6 +184,12 @@ public class CloudWatchLogsService implements ResourceProvider {
public void createLogGroupForAccount(
String accountId, String name, Integer retentionInDays,
Map<String, String> tags, boolean deletionProtectionEnabled, String region) {
+ createLogGroupForAccount(accountId, name, retentionInDays, tags, deletionProtectionEnabled, null, region);
+ }
+
+ public void createLogGroupForAccount(
+ String accountId, String name, Integer retentionInDays,
+ Map<String, String> tags, boolean deletionProtectionEnabled, String kmsKeyId, String region) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterException", "logGroupName is required.", 400);
}
@@ -192,6 +203,9 @@ public class CloudWatchLogsService implements ResourceProvider {
group.setCreatedTime(System.currentTimeMillis());
group.setRetentionInDays(retentionInDays);
group.setDeletionProtectionEnabled(deletionProtectionEnabled);
+ if (kmsKeyId != null && !kmsKeyId.isBlank()) {
+ group.setKmsKeyId(kmsKeyId);
+ }
if (tags != null) {
group.setTags(new HashMap<>(tags));
}
@@ -292,6 +306,36 @@ public class CloudWatchLogsService implements ResourceProvider {
groupStore.put(key, group);
}
+ /**
+ * Associates a KMS CMK with a log group so its stored events are encrypted with it.
+ *
+ * <p>The association is a property of the group, not of each event, and it is surfaced by
+ * {@code DescribeLogGroups}: callers converge by reading {@code kmsKeyId} back and only
+ * re-associating when it differs from the key they want.
+ */
+ public void associateKmsKey(String groupName, String kmsKeyId, String region) {
+ if (kmsKeyId == null || kmsKeyId.isBlank()) {
+ throw new AwsException("InvalidParameterException", "kmsKeyId required.", 400);
+ }
+ String key = groupKey(region, groupName);
+ LogGroup group = groupStore.get(key)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "The specified log group does not exist: " + groupName, 400));
+ group.setKmsKeyId(kmsKeyId);
+ groupStore.put(key, group);
+ LOG.infov("Associated KMS key {0} with log group {1}", kmsKeyId, groupName);
+ }
+
+ public void disassociateKmsKey(String groupName, String region) {
+ String key = groupKey(region, groupName);
+ LogGroup group = groupStore.get(key)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "The specified log group does not exist: " + groupName, 400));
+ group.setKmsKeyId(null);
+ groupStore.put(key, group);
+ LOG.infov("Disassociated KMS key from log group {0}", groupName);
+ }
+
public Map<String, String> listTagsLogGroup(String groupName, String region) {
String key = groupKey(region, groupName);
LogGroup group = groupStore.get(key)
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/LogGroup.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/LogGroup.java
index eae852a095..61c5a08528 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/LogGroup.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/LogGroup.java
@@ -14,6 +14,7 @@ public class LogGroup {
private long createdTime;
private Integer retentionInDays;
private boolean deletionProtectionEnabled;
+ private String kmsKeyId;
private Map<String, String> tags = new HashMap<>();
public LogGroup() {}
@@ -32,6 +33,9 @@ public class LogGroup {
this.deletionProtectionEnabled = deletionProtectionEnabled;
}
+ public String getKmsKeyId() { return kmsKeyId; }
+ public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
+
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java
index f5cbe71877..43c79e627f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java
@@ -528,4 +528,165 @@ class CloudWatchLogsHandlerTest {
() -> handler.handle("StartQuery", request, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
+
+ // ──────────────────────────── AssociateKmsKey / DisassociateKmsKey ────────────────────────────
+
+ private static final String KEY_ARN =
+ "arn:aws:kms:" + REGION + ":" + ACCOUNT + ":key/1234abcd-12ab-34cd-56ef-1234567890ab";
+
+ @Test
+ void associateKmsKeyIsEchoedBackByDescribeLogGroups() {
+ // LZA's Custom::UpdateSubscriptionFilter Lambda reads logGroup.kmsKeyId from
+ // DescribeLogGroups and only calls AssociateKmsKey when it differs from the target
+ // key ARN. If DescribeLogGroups never surfaces the field, the association never
+ // converges and the Lambda re-associates on every deploy.
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("logGroupName", GROUP);
+ associate.put("kmsKeyId", KEY_ARN);
+
+ assertEquals(200, handler.handle("AssociateKmsKey", associate, REGION).getStatus());
+
+ JsonNode group = describeGroup();
+ assertEquals(KEY_ARN, group.path("kmsKeyId").asText());
+ }
+
+ @Test
+ void describeLogGroupsOmitsKmsKeyIdWhenNoKeyIsAssociated() {
+ assertThat(describeGroup().has("kmsKeyId"), is(false));
+ }
+
+ @Test
+ void disassociateKmsKeyClearsTheAssociation() {
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("logGroupName", GROUP);
+ associate.put("kmsKeyId", KEY_ARN);
+ handler.handle("AssociateKmsKey", associate, REGION);
+
+ ObjectNode disassociate = MAPPER.createObjectNode();
+ disassociate.put("logGroupName", GROUP);
+ assertEquals(200, handler.handle("DisassociateKmsKey", disassociate, REGION).getStatus());
+
+ assertThat(describeGroup().has("kmsKeyId"), is(false));
+ }
+
+ @Test
+ void associateKmsKeyResolvesAnArnResourceIdentifier() {
+ // The wire field for the ARN alternative on Associate/DisassociateKmsKey is
+ // resourceIdentifier (not the logGroupIdentifier the query operations use).
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("resourceIdentifier", GROUP_ARN);
+ associate.put("kmsKeyId", KEY_ARN);
+
+ assertEquals(200, handler.handle("AssociateKmsKey", associate, REGION).getStatus());
+ assertEquals(KEY_ARN, describeGroup().path("kmsKeyId").asText());
+ }
+
+ @Test
+ void associateKmsKeyWithBothIdentifiersThrowsInvalidParameter() {
+ // AWS models the two identifiers as mutually exclusive: exactly one is required.
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("logGroupName", GROUP);
+ associate.put("resourceIdentifier", GROUP_ARN);
+ associate.put("kmsKeyId", KEY_ARN);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("AssociateKmsKey", associate, REGION));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void associateKmsKeyWithBlankNameBesideValidArnThrowsInvalidParameter() {
+ // A present-but-blank identifier is not "absent": the model pins logGroupName
+ // to min length 1, so blank + a valid counterpart must reject, not silently
+ // proceed on the valid one.
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("logGroupName", "");
+ associate.put("resourceIdentifier", GROUP_ARN);
+ associate.put("kmsKeyId", KEY_ARN);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("AssociateKmsKey", associate, REGION));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void associateKmsKeyWithOnlyABlankIdentifierThrowsInvalidParameter() {
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("logGroupName", "");
+ associate.put("kmsKeyId", KEY_ARN);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("AssociateKmsKey", associate, REGION));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void associateKmsKeyWithoutAnyIdentifierThrowsInvalidParameter() {
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("kmsKeyId", KEY_ARN);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("AssociateKmsKey", associate, REGION));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void associateKmsKeyOnUnknownLogGroupThrows() {
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("logGroupName", "/nope");
+ associate.put("kmsKeyId", KEY_ARN);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("AssociateKmsKey", associate, REGION));
+ assertEquals("ResourceNotFoundException", ex.getErrorCode());
+ }
+
+ @Test
+ void createLogGroupWithKmsKeyIdIsEchoedBackByDescribeLogGroups() {
+ // CreateLogGroup models kmsKeyId (Required: No) as the normal way to create an
+ // encrypted group in one call; it must be stored and surfaced the same way
+ // AssociateKmsKey's result is.
+ String newGroup = "/aws/rds/instance/encrypted-at-creation/postgresql";
+ ObjectNode create = MAPPER.createObjectNode();
+ create.put("logGroupName", newGroup);
+ create.put("kmsKeyId", KEY_ARN);
+
+ assertEquals(200, handler.handle("CreateLogGroup", create, REGION).getStatus());
+
+ ObjectNode describeRequest = MAPPER.createObjectNode();
+ describeRequest.put("logGroupNamePrefix", newGroup);
+ Response response = handler.handle("DescribeLogGroups", describeRequest, REGION);
+ ArrayNode groups = (ArrayNode) ((ObjectNode) response.getEntity()).path("logGroups");
+ assertEquals(1, groups.size());
+ assertEquals(KEY_ARN, groups.get(0).path("kmsKeyId").asText());
+ }
+
+ @Test
+ void associateKmsKeyWithQueryResultResourceIdentifierIsRejectedAsUnsupported() {
+ // arn:...:query-result:* is a real, modeled resourceIdentifier form (account-wide
+ // GetQueryResults encryption), but it is a genuinely different feature from
+ // per-log-group encryption. extractLogGroupNameFromArn only recognizes :log-group:,
+ // so left unchecked this ARN falls through unchanged and becomes a log group NAME,
+ // producing a ResourceNotFoundException that names a log group the caller never
+ // specified. It must be rejected as unsupported instead.
+ ObjectNode associate = MAPPER.createObjectNode();
+ associate.put("resourceIdentifier",
+ "arn:aws:logs:" + REGION + ":" + ACCOUNT + ":query-result:*");
+ associate.put("kmsKeyId", KEY_ARN);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("AssociateKmsKey", associate, REGION));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ assertThat(ex.getMessage(), containsString("query-result"));
+ }
+
+ private JsonNode describeGroup() {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("logGroupNamePrefix", GROUP);
+ Response response = handler.handle("DescribeLogGroups", request, REGION);
+ assertEquals(200, response.getStatus());
+ ArrayNode groups = (ArrayNode) ((ObjectNode) response.getEntity()).path("logGroups");
+ assertEquals(1, groups.size());
+ return groups.get(0);
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInputConstraintTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInputConstraintTest.java
new file mode 100644
index 0000000000..24e8fb2782
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInputConstraintTest.java
@@ -0,0 +1,92 @@
+package io.github.hectorvent.floci.services.cloudwatch.logs;
+
+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.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * Enforcement of the input constraints the 2014-03-28 model pins on the
+ * pre-existing operations: logEvents list 1-10000 on PutLogEvents,
+ * logStreamNames list 1-100 on FilterLogEvents, and the Random/ByLogStream
+ * distribution enum on PutSubscriptionFilter. All were previously accepted
+ * verbatim.
+ */
+class CloudWatchLogsInputConstraintTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT = "000000000000";
+ private static final String GROUP = "constraint-group";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private CloudWatchLogsHandler handler;
+
+ @BeforeEach
+ void setUp() {
+ CloudWatchLogsService service = new CloudWatchLogsService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ 10_000,
+ new RegionResolver(REGION, ACCOUNT)
+ );
+ handler = new CloudWatchLogsHandler(service, MAPPER);
+ service.createLogGroup(GROUP, null, null, REGION);
+ service.createLogStream(GROUP, "s1", REGION);
+ }
+
+ private static AwsException expect400(Runnable call) {
+ AwsException e = assertThrows(AwsException.class, call::run);
+ assertEquals(400, e.getHttpStatus());
+ assertEquals("InvalidParameterException", e.getErrorCode());
+ return e;
+ }
+
+ @Test
+ void putLogEvents_emptyList_isRejected() {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("logGroupName", GROUP).put("logStreamName", "s1");
+ request.putArray("logEvents");
+ expect400(() -> handler.handle("PutLogEvents", request, REGION));
+ }
+
+ @Test
+ void filterLogEvents_tooManyStreamNames_isRejected() {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("logGroupName", GROUP);
+ ArrayNode names = request.putArray("logStreamNames");
+ for (int i = 0; i <= 100; i++) {
+ names.add("s" + i);
+ }
+ expect400(() -> handler.handle("FilterLogEvents", request, REGION));
+ }
+
+ @Test
+ void filterLogEvents_explicitNullStreamNames_isTreatedAsAbsent() {
+ // request.has("logStreamNames") is true for an explicit JSON null, and mapping
+ // NullNode to size 0 trips the min-1 bound below. AWS treats an explicit null on
+ // an optional member as absent, so this must succeed, not 400.
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("logGroupName", GROUP);
+ request.putNull("logStreamNames");
+ assertEquals(200, handler.handle("FilterLogEvents", request, REGION).getStatus());
+ }
+
+ @Test
+ void putSubscriptionFilter_unknownDistribution_isRejected() {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("logGroupName", GROUP).put("filterName", "f")
+ .put("filterPattern", "").put("destinationArn",
+ "arn:aws:lambda:us-east-1:000000000000:function:fn")
+ .put("distribution", "RoundRobin");
+ expect400(() -> handler.handle("PutSubscriptionFilter", request, REGION));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
index 210933e862..6997432b96 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
@@ -20,6 +20,8 @@ import static org.junit.jupiter.api.Assertions.*;
class CloudWatchLogsServiceTest {
private static final String REGION = "us-east-1";
+ private static final String KEY_ARN =
+ "arn:aws:kms:us-east-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab";
private CloudWatchLogsService service;
@@ -166,6 +168,48 @@ class CloudWatchLogsServiceTest {
assertNull(group.getRetentionInDays());
}
+ // ──────────────────────────── KMS key association ────────────────────────────
+
+ @Test
+ void associateAndDisassociateKmsKey() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ assertNull(service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId(),
+ "a freshly created log group has no CMK associated");
+
+ service.associateKmsKey("/app/logs", KEY_ARN, REGION);
+ assertEquals(KEY_ARN, service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId());
+
+ service.disassociateKmsKey("/app/logs", REGION);
+ assertNull(service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId());
+ }
+
+ @Test
+ void associateKmsKeyReplacesAnExistingAssociation() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ service.associateKmsKey("/app/logs", KEY_ARN, REGION);
+
+ String other = "arn:aws:kms:us-east-1:000000000000:key/99999999-9999-9999-9999-999999999999";
+ service.associateKmsKey("/app/logs", other, REGION);
+
+ assertEquals(other, service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId());
+ }
+
+ @Test
+ void associateKmsKeyOnMissingGroupThrows() {
+ assertThrows(AwsException.class, () -> service.associateKmsKey("/missing", KEY_ARN, REGION));
+ }
+
+ @Test
+ void associateKmsKeyWithoutKeyIdThrows() {
+ service.createLogGroup("/app/logs", null, null, REGION);
+ assertThrows(AwsException.class, () -> service.associateKmsKey("/app/logs", "", REGION));
+ }
+
+ @Test
+ void disassociateKmsKeyOnMissingGroupThrows() {
+ assertThrows(AwsException.class, () -> service.disassociateKmsKey("/missing", REGION));
+ }
+
@Test
void tagAndUntagLogGroup() {
service.createLogGroup("/app/logs", null, Map.of("env", "prod"), REGION);