Light, fluffy, and always free - The AWS Local Emulator alternative
fix(logs): preserve and filter log group classes (#6312)
Aniket Shukla33620a59c06b
diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.mdindex ba2b301b00..231577a8ef 100644--- a/docs/services/cloudwatch.md+++ b/docs/services/cloudwatch.md@@ -55,6 +55,12 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics.Set `limit` to an integer from 1 to 50 and pass the returned `nextToken` with the same regionand name prefix to continue. The final page omits `nextToken`.+`CreateLogGroup` stores `logGroupClass` as `STANDARD` (the default), `INFREQUENT_ACCESS`, or+`DELIVERY`. `DescribeLogGroups` returns the stored class and applies an optional `logGroupClass`+filter before pagination. Continue with the same class filter when using `nextToken`.+Stored groups without a class default to `STANDARD`. Class metadata does not change retention,+delivery behavior, or the features available on a group.+Log group deletion protection defaults to disabled and is persisted with the log group. When it isenabled, `DeleteLogGroup` returns `ValidationException` until protection is explicitly disabledwith `PutLogGroupDeletionProtection`.diff --git a/pom.xml b/pom.xmlindex 6dfbb29038..8122ae4669 100644--- a/pom.xml+++ b/pom.xml@@ -330,6 +330,12 @@</dependency><!-- Testing -->+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>cloudwatchlogs</artifactId>+ <version>${aws.sdk.version}</version>+ <scope>test</scope>+ </dependency><dependency><groupId>software.amazon.awssdk</groupId><artifactId>organizations</artifactId>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.javaindex 00a91100b9..bcefa42495 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@@ -101,7 +101,8 @@ public class CloudWatchLogsHandler {boolean deletionProtectionEnabled = request.path("deletionProtectionEnabled").asBoolean(false);Map<String, String> tags = extractTags(request.path("tags"));String kmsKeyId = request.path("kmsKeyId").asText(null);- logsService.createLogGroup(name, retentionInDays, tags, deletionProtectionEnabled, kmsKeyId, region);+ logsService.createLogGroup(name, retentionInDays, tags, deletionProtectionEnabled, kmsKeyId,+ logGroupClass(request), region);return Response.ok(objectMapper.createObjectNode()).build();}@@ -140,13 +141,14 @@ public class CloudWatchLogsHandler {if (request.hasNonNull("nextToken") && !request.get("nextToken").isTextual()) {throw CloudWatchLogsService.invalidNextToken();}- PaginatedResult<LogGroup> page = logsService.describeLogGroups(prefix, region, limit, nextToken);+ PaginatedResult<LogGroup> page = logsService.describeLogGroups(prefix, logGroupClass(request), region, limit, nextToken);ObjectNode response = objectMapper.createObjectNode();ArrayNode groupsArray = objectMapper.createArrayNode();for (LogGroup g : page.items()) {ObjectNode node = objectMapper.createObjectNode();node.put("logGroupName", g.getLogGroupName());+ node.put("logGroupClass", g.getLogGroupClass());node.put("creationTime", g.getCreatedTime());String logGroupArn = logsService.buildArn(g.getLogGroupName(), region);node.put("arn", logGroupArn + ":*");@@ -169,6 +171,17 @@ public class CloudWatchLogsHandler {return Response.ok(response).build();}+ private static String logGroupClass(JsonNode request) {+ JsonNode value = request.get("logGroupClass");+ if (value == null || value.isNull()) {+ return null;+ }+ if (!value.isTextual()) {+ throw new AwsException("InvalidParameterException", "logGroupClass must be a string.", 400);+ }+ return value.textValue();+ }+private Response handlePutResourcePolicy(JsonNode request, String region) {String policyName = request.path("policyName").asText(null);if (policyName == null || policyName.isBlank()) {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.javaindex 07a2382a80..b9cf11d26e 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@@ -56,6 +56,7 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {private static final Logger LOG = Logger.getLogger(CloudWatchLogsService.class);private static final int MAX_REGEX_FILTERS_PER_LOG_GROUP = 5;private static final int MAX_FILTER_PATTERN_LENGTH = 1024;+ private static final Set<String> LOG_GROUP_CLASSES = Set.of("STANDARD", "INFREQUENT_ACCESS", "DELIVERY");/*** Orders events by timestamp, then by ingestion sequence so that events sharing the same@@ -273,6 +274,11 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {createLogGroupForAccount(null, name, retentionInDays, tags, deletionProtectionEnabled, kmsKeyId, region);}+ public void createLogGroup(String name, Integer retentionInDays, Map<String, String> tags,+ boolean deletionProtectionEnabled, String kmsKeyId, String logGroupClass, String region) {+ createLogGroupForAccount(null, name, retentionInDays, tags, deletionProtectionEnabled, kmsKeyId, logGroupClass, region);+ }+public void createLogGroupForAccount(String accountId, String name, Integer retentionInDays,Map<String, String> tags, String region) {@@ -288,10 +294,17 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {public void createLogGroupForAccount(String accountId, String name, Integer retentionInDays,Map<String, String> tags, boolean deletionProtectionEnabled, String kmsKeyId, String region) {+ createLogGroupForAccount(accountId, name, retentionInDays, tags, deletionProtectionEnabled, kmsKeyId, null, region);+ }++ public void createLogGroupForAccount(+ String accountId, String name, Integer retentionInDays,+ Map<String, String> tags, boolean deletionProtectionEnabled, String kmsKeyId, String logGroupClass, String region) {synchronized (metricFilterStore) {if (name == null || name.isBlank()) {throw new AwsException("InvalidParameterException", "logGroupName is required.", 400);}+ validateLogGroupClass(logGroupClass);String key = groupKey(region, name);if (getForAccount(groupStore, accountId, key).isPresent()) {throw new AwsException("ResourceAlreadyExistsException",@@ -299,6 +312,7 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {}LogGroup group = new LogGroup();group.setLogGroupName(name);+ group.setLogGroupClass(logGroupClass == null ? "STANDARD" : logGroupClass);group.setCreatedTime(System.currentTimeMillis());group.setRetentionInDays(retentionInDays);group.setDeletionProtectionEnabled(deletionProtectionEnabled);@@ -369,6 +383,12 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {}PaginatedResult<LogGroup> describeLogGroups(String prefix, String region, int limit, String nextToken) {+ return describeLogGroups(prefix, null, region, limit, nextToken);+ }++ PaginatedResult<LogGroup> describeLogGroups(String prefix, String logGroupClass, String region,+ int limit, String nextToken) {+ validateLogGroupClass(logGroupClass);if (limit < 1 || limit > 50) {String constraint = limit < 1 ? "greater than or equal to 1" : "less than or equal to 50";throw SmithyValidationErrors.exception("InvalidParameterException",@@ -377,11 +397,23 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {if (nextToken != null && nextToken.isEmpty()) {throw invalidNextToken();}- return Pagination.paginate(matchingLogGroups(prefix, region), LogGroup::getLogGroupName, limit, nextToken,- "DescribeLogGroups:" + region + ":" + (prefix == null ? "" : prefix),+ List<LogGroup> groups = matchingLogGroups(prefix, region).stream()+ .filter(group -> logGroupClass == null || logGroupClass.equals(group.getLogGroupClass()))+ .toList();+ return Pagination.paginate(groups, LogGroup::getLogGroupName, limit, nextToken,+ "DescribeLogGroups" + (logGroupClass == null ? "" : "/" + logGroupClass)+ + ":" + region + ":" + (prefix == null ? "" : prefix),token -> invalidNextToken());}+ private static void validateLogGroupClass(String logGroupClass) {+ if (logGroupClass != null && !LOG_GROUP_CLASSES.contains(logGroupClass)) {+ throw SmithyValidationErrors.exception("InvalidParameterException",+ "Value '" + logGroupClass + "' at 'logGroupClass' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [STANDARD, INFREQUENT_ACCESS, DELIVERY]");+ }+ }+private List<LogGroup> matchingLogGroups(String prefix, String region) {String storagePrefix = groupKeyPrefix(region);return groupStore.scan(k -> {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.javaindex 61c5a08528..9e64df724e 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@@ -11,6 +11,7 @@ import java.util.Map;public class LogGroup {private String logGroupName;+ private String logGroupClass = "STANDARD";private long createdTime;private Integer retentionInDays;private boolean deletionProtectionEnabled;@@ -22,6 +23,9 @@ public class LogGroup {public String getLogGroupName() { return logGroupName; }public void setLogGroupName(String logGroupName) { this.logGroupName = logGroupName; }+ public String getLogGroupClass() { return logGroupClass; }+ public void setLogGroupClass(String logGroupClass) { this.logGroupClass = logGroupClass; }+public long getCreatedTime() { return createdTime; }public void setCreatedTime(long createdTime) { this.createdTime = createdTime; }diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupClassIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupClassIntegrationTest.javanew file mode 100644index 0000000000..3b20c0c92f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupClassIntegrationTest.java@@ -0,0 +1,158 @@+package io.github.hectorvent.floci.services.cloudwatch.logs;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.RestAssured;+import io.restassured.response.Response;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;+import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;+import software.amazon.awssdk.regions.Region;+import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;+import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException;+import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsResponse;+import software.amazon.awssdk.services.cloudwatchlogs.model.LogGroup;++import java.net.URI;+import java.util.List;+import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++@QuarkusTest+class CloudWatchLogsGroupClassIntegrationTest {++ @BeforeAll+ static void configureContentTypes() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @ParameterizedTest+ @CsvSource({"CreateLogGroup,7", "CreateLogGroup,true", "CreateLogGroup,[]", "CreateLogGroup,{}",+ "DescribeLogGroups,7", "DescribeLogGroups,true", "DescribeLogGroups,[]", "DescribeLogGroups,{}"})+ void rejectsNonStringClasses(String action, String jsonValue) {+ String name = "/class-shape-6232/" + UUID.randomUUID();+ Response response = given().contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "Logs_20140328." + action)+ .body("{\"logGroupName\":\"" + name + "\",\"logGroupClass\":" + jsonValue + "}").post("/");+ try {+ response.then().statusCode(400).body("__type", equalTo("InvalidParameterException"));+ } finally {+ if ("CreateLogGroup".equals(action) && response.statusCode() == 200) {+ given().contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "Logs_20140328.DeleteLogGroup")+ .body("{\"logGroupName\":\"" + name + "\"}").post("/").then().statusCode(200);+ }+ }+ }++ @ParameterizedTest+ @CsvSource(value = {"OMITTED,STANDARD", "STANDARD,STANDARD", "INFREQUENT_ACCESS,INFREQUENT_ACCESS",+ "DELIVERY,DELIVERY"}, nullValues = "OMITTED")+ void sdkReturnsTheCreatedClassAndFiltersIt(String requestedClass, String expectedClass) {+ String group = "/class-6232/" + UUID.randomUUID();+ try (CloudWatchLogsClient client = client()) {+ client.createLogGroup(request -> request.logGroupName(group).logGroupClass(requestedClass));+ try {+ List<LogGroup> groups = client.describeLogGroups(request -> request.logGroupNamePrefix(group)).logGroups();+ assertEquals(1, groups.size());+ assertEquals(expectedClass, groups.getFirst().logGroupClassAsString());+ assertEquals(groups, client.describeLogGroups(request -> request.logGroupNamePrefix(group)+ .logGroupClass(expectedClass)).logGroups());+ String otherClass = "STANDARD".equals(expectedClass) ? "DELIVERY" : "STANDARD";+ assertEquals(List.of(), client.describeLogGroups(request -> request.logGroupNamePrefix(group)+ .logGroupClass(otherClass)).logGroups());+ } finally {+ client.deleteLogGroup(request -> request.logGroupName(group));+ }+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"FOO", "COLD", "", "standard"})+ void sdkRejectsAnInvalidClassOnCreate(String invalidClass) {+ String group = "/class-invalid-6232/" + UUID.randomUUID();+ try (CloudWatchLogsClient client = client()) {+ try {+ CloudWatchLogsException invalid = assertThrows(CloudWatchLogsException.class,+ () -> client.createLogGroup(request -> request.logGroupName(group).logGroupClass(invalidClass)));+ assertEquals("InvalidParameterException", invalid.awsErrorDetails().errorCode());+ assertEquals(400, invalid.statusCode());+ assertEquals("1 validation error detected: Value '" + invalidClass+ + "' at 'logGroupClass' failed to satisfy constraint: Member must satisfy enum value set: "+ + "[STANDARD, INFREQUENT_ACCESS, DELIVERY]", invalid.awsErrorDetails().errorMessage());+ } finally {+ if (!client.describeLogGroups(request -> request.logGroupNamePrefix(group)).logGroups().isEmpty()) {+ client.deleteLogGroup(request -> request.logGroupName(group));+ }+ }+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"FOO", "COLD", "", "standard"})+ void sdkRejectsAnInvalidClassOnDescribe(String invalidClass) {+ try (CloudWatchLogsClient client = client()) {+ CloudWatchLogsException invalid = assertThrows(CloudWatchLogsException.class,+ () -> client.describeLogGroups(request -> request.logGroupClass(invalidClass)));+ assertEquals("InvalidParameterException", invalid.awsErrorDetails().errorCode());+ assertEquals(400, invalid.statusCode());+ assertEquals("1 validation error detected: Value '" + invalidClass+ + "' at 'logGroupClass' failed to satisfy constraint: Member must satisfy enum value set: "+ + "[STANDARD, INFREQUENT_ACCESS, DELIVERY]", invalid.awsErrorDetails().errorMessage());+ }+ }++ @Test+ void sdkFiltersBeforePaginationAndBindsTheCursorToTheClass() {+ String prefix = "/class-pages-6232/" + UUID.randomUUID() + "/";+ List<String> names = List.of("a", "b", "c", "d", "e");+ try (CloudWatchLogsClient client = client()) {+ try {+ for (String name : names) {+ String groupClass = List.of("b", "d").contains(name) ? "INFREQUENT_ACCESS" : "STANDARD";+ client.createLogGroup(request -> request.logGroupName(prefix + name).logGroupClass(groupClass));+ }+ DescribeLogGroupsResponse first = client.describeLogGroups(request -> request.logGroupNamePrefix(prefix)+ .logGroupClass("INFREQUENT_ACCESS").limit(1));+ assertEquals(List.of(prefix + "b"), first.logGroups().stream().map(LogGroup::logGroupName).toList());+ assertNotNull(first.nextToken());+ DescribeLogGroupsResponse second = client.describeLogGroups(request -> request.logGroupNamePrefix(prefix)+ .logGroupClass("INFREQUENT_ACCESS").limit(1).nextToken(first.nextToken()));+ assertEquals(List.of(prefix + "d"), second.logGroups().stream().map(LogGroup::logGroupName).toList());+ assertNull(second.nextToken());+ CloudWatchLogsException invalid = assertThrows(CloudWatchLogsException.class,+ () -> client.describeLogGroups(request -> request.logGroupNamePrefix(prefix)+ .logGroupClass("STANDARD").nextToken(first.nextToken())));+ assertEquals("InvalidParameterException", invalid.awsErrorDetails().errorCode());+ CloudWatchLogsException omitted = assertThrows(CloudWatchLogsException.class,+ () -> client.describeLogGroups(request -> request.logGroupNamePrefix(prefix)+ .nextToken(first.nextToken())));+ assertEquals("InvalidParameterException", omitted.awsErrorDetails().errorCode());+ } finally {+ for (LogGroup group : client.describeLogGroups(request -> request.logGroupNamePrefix(prefix)).logGroups()) {+ client.deleteLogGroup(request -> request.logGroupName(group.logGroupName()));+ }+ }+ }+ }++ private static CloudWatchLogsClient client() {+ return CloudWatchLogsClient.builder()+ .endpointOverride(URI.create("http://localhost:" + RestAssured.port))+ .httpClientBuilder(UrlConnectionHttpClient.builder())+ .region(Region.US_EAST_1)+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("741623200001", "test")))+ .build();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupClassStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupClassStorageTest.javanew file mode 100644index 0000000000..b7f366bb91--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupClassStorageTest.java@@ -0,0 +1,23 @@+package io.github.hectorvent.floci.services.cloudwatch.logs;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;++import static org.junit.jupiter.api.Assertions.assertEquals;++class CloudWatchLogsGroupClassStorageTest {++ @ParameterizedTest+ @CsvSource(value = {"OMITTED,STANDARD", "STANDARD,STANDARD", "INFREQUENT_ACCESS,INFREQUENT_ACCESS",+ "DELIVERY,DELIVERY"}, nullValues = "OMITTED")+ void storedGroupsRetainTheirClassAndLegacyGroupsDefaultToStandard(String storedClass, String expectedClass)+ throws Exception {+ ObjectMapper mapper = new ObjectMapper();+ String json = storedClass == null ? "{\"logGroupName\":\"legacy\"}"+ : "{\"logGroupName\":\"group\",\"logGroupClass\":\"" + storedClass + "\"}";+ LogGroup reloaded = mapper.readValue(json, LogGroup.class);+ assertEquals(expectedClass, mapper.readTree(mapper.writeValueAsString(reloaded)).path("logGroupClass").asText());+ }+}