From c5ac8e8ad037b6867ebc5fc34d17ae13bfc52a4c Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:13:43 -0600 Subject: [PATCH] feat(cloudwatch): support alarm action controls (#8383) EnableAlarmActions and DisableAlarmActions now work over the Query and JSON APIs. They change only whether an alarm's actions run, keeping its state and configuration. AlarmNames is required, up to 100 names of 1 to 255 characters, and the whole list is validated before any alarm changes. The evaluator reads the alarm's current setting before it dispatches, so a disabled alarm sends nothing. SDK, validation, notification and IAM tests cover both operations, and the alarm action, composite alarm, DescribeAlarms filter and alarm history tests share CloudWatchTestRequests for their Query and JSON requests. Signed-off-by: Jackson Price Co-authored-by: Andre Kurait --- docs/services/cloudwatch.md | 17 +- pom.xml | 6 + .../cloudwatch/metrics/AlarmEvaluator.java | 8 +- .../metrics/CloudWatchMetricsJsonHandler.java | 21 ++ .../CloudWatchMetricsQueryHandler.java | 15 ++ .../metrics/CloudWatchMetricsService.java | 39 ++++ .../metrics/AlarmEvaluatorTest.java | 63 +++++- .../metrics/AlarmSnsNotifierTest.java | 12 + ...CloudWatchAlarmActionsIntegrationTest.java | 214 ++++++++++++++++++ ...CloudWatchAlarmHistoryIntegrationTest.java | 31 +-- ...hDescribeAlarmsFiltersIntegrationTest.java | 23 +- ...tchJsonTargetSignatureIntegrationTest.java | 50 ++++ .../metrics/CloudWatchTestRequests.java | 52 +++++ .../CompositeAlarmIntegrationTest.java | 36 +-- 14 files changed, 508 insertions(+), 79 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmActionsIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchTestRequests.java diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 19974cb14e..421489f88e 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -506,6 +506,8 @@ returns HTTP 404. | `PutCompositeAlarm` | Create or update a composite alarm rule | | `DescribeAlarms` | List alarms | | `DeleteAlarms` | Delete alarms | +| `DisableAlarmActions` | Disable actions for named metric and composite alarms | +| `EnableAlarmActions` | Re-enable actions for named metric and composite alarms | | `SetAlarmState` | Manually set alarm state | | `DescribeAlarmHistory` | List alarm state transitions and configuration changes (see [Alarm history](#alarm-history)) | | `PutMetricStream` | Create or update a metric stream definition | @@ -582,7 +584,15 @@ alarms before their children. Names that match no alarm are ignored. State transitions publish to same-account standard SNS topics in `AlarmActions`, `OKActions`, or `InsufficientDataActions`, including transitions from `SetAlarmState`. Unchanged states and -`ActionsEnabled=false` suppress notifications. Scaling action retries remain independent. +`ActionsEnabled=false` suppress notifications. `DisableAlarmActions` and `EnableAlarmActions` +update this setting through the Query and current JSON APIs, preserving the alarm's state, +actions, tags, and other configuration. They accept up to 100 names, ignore nonexistent +alarms, and validate the whole request before updating any alarm. Enabling actions does not +replay notifications for transitions that occurred while disabled. +Query requests validate all supplied numeric member indexes, including names after a gap. +The metric evaluator checks current stored action settings before dispatch; disabling does +not cancel actions that have already passed that check. +Scaling action retries remain independent. Failures are logged per target without blocking other targets. Notifications include a single-metric `Trigger`; durable retries, FIFO topics, and metric-math payloads are not covered. @@ -622,8 +632,9 @@ empty or over-long `ActionPrefix`, and an empty or over-long alarm name in eithe evaluator or a composite alarm's rule. Setting an alarm to the state it already has records nothing. `HistoryData` carries the old and new state with their reasons and reason data. - `ConfigurationUpdate` when `PutMetricAlarm` or `PutCompositeAlarm` creates or updates an alarm, - and when `DeleteAlarms` deletes one. An update lists the previous value of each changed field - under `originalUpdatedFields`. + when `EnableAlarmActions` or `DisableAlarmActions` changes its action setting, and when + `DeleteAlarms` deletes one. An update lists the previous value of each changed field under + `originalUpdatedFields`. History survives the deletion of its alarm and is kept for 30 days. Without `AlarmTypes` only metric alarm history is listed; request `CompositeAlarm` to include composite alarms. `Action`, diff --git a/pom.xml b/pom.xml index e4b4c5d9e1..45a291f078 100644 --- a/pom.xml +++ b/pom.xml @@ -458,6 +458,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + cloudwatch + ${aws.sdk.version} + test + software.amazon.awssdk cloudwatchlogs diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java index b4b09dea1c..a68ef4cff8 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java @@ -14,6 +14,7 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -184,8 +185,11 @@ public class AlarmEvaluator { metricsService.setAlarmState(alarm.getAlarmName(), newState, reason, null, region); } - if ("ALARM".equals(newState) && alarm.isActionsEnabled()) { - dispatch(alarm, latestValue, region); + if ("ALARM".equals(newState)) { + Optional current = metricsService.enabledMetricAlarm(alarm.getAlarmName(), region); + if (current.isPresent()) { + dispatch(current.get(), latestValue, region); + } } } diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java index 9811c47632..dfe5a6e7f8 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java @@ -85,6 +85,8 @@ public class CloudWatchMetricsJsonHandler { case "PutCompositeAlarm" -> handlePutCompositeAlarm(request, region); case "DescribeAlarms" -> handleDescribeAlarms(request, region); case "DeleteAlarms" -> handleDeleteAlarms(request, region); + case "DisableAlarmActions" -> handleAlarmActions(request, region, false); + case "EnableAlarmActions" -> handleAlarmActions(request, region, true); case "SetAlarmState" -> handleSetAlarmState(request, region); case "DescribeAlarmHistory" -> handleDescribeAlarmHistory(request, region); case "ListTagsForResource" -> handleListTagsForResource(request, region); @@ -440,6 +442,25 @@ public class CloudWatchMetricsJsonHandler { return Response.ok(objectMapper.createObjectNode()).build(); } + private Response handleAlarmActions(JsonNode request, String region, boolean enabled) { + JsonNode names = request.get("AlarmNames"); + List alarmNames = null; + if (names != null && !names.isNull()) { + if (!names.isArray()) { + throw new AwsException("SerializationException", "AlarmNames must be an array", 400); + } + alarmNames = new ArrayList<>(); + for (JsonNode name : names) { + if (!name.isTextual() && !name.isNull()) { + throw new AwsException("SerializationException", "AlarmNames members must be strings", 400); + } + alarmNames.add(name.asText(null)); + } + } + metricsService.setAlarmActionsEnabled(alarmNames, enabled, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + private Response handleSetAlarmState(JsonNode request, String region) { String name = request.path("AlarmName").asText(); String state = request.path("StateValue").asText(); diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java index e13948be9e..d433c06d52 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java @@ -2,6 +2,7 @@ package io.floci.aws.services.cloudwatch.metrics; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsNamespaces; +import io.floci.aws.core.common.AwsQueryLists; import io.floci.aws.core.common.AwsQueryResponse; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; @@ -66,6 +67,8 @@ public class CloudWatchMetricsQueryHandler { case "PutCompositeAlarm" -> handlePutCompositeAlarm(params, region); case "DescribeAlarms" -> handleDescribeAlarms(params, region); case "DeleteAlarms" -> handleDeleteAlarms(params, region); + case "DisableAlarmActions" -> handleAlarmActions(params, region, false); + case "EnableAlarmActions" -> handleAlarmActions(params, region, true); case "SetAlarmState" -> handleSetAlarmState(params, region); case "DescribeAlarmHistory" -> handleDescribeAlarmHistory(params, region); case "ListTagsForResource" -> handleListTagsForResource(params, region); @@ -335,6 +338,18 @@ public class CloudWatchMetricsQueryHandler { return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteAlarms", null)).build(); } + private Response handleAlarmActions(MultivaluedMap params, String region, boolean enabled) { + List members = AwsQueryLists.members(params, "AlarmNames", null); + List names = new ArrayList<>(); + for (AwsQueryLists.IndexedMember member : members) { + names.add(params.getFirst(member.prefix())); + } + boolean supplied = params.containsKey("AlarmNames") || !members.isEmpty(); + metricsService.setAlarmActionsEnabled(supplied ? names : null, enabled, region); + String action = enabled ? "EnableAlarmActions" : "DisableAlarmActions"; + return Response.ok(AwsQueryResponse.envelopeNoResult(action, null)).build(); + } + private Response handleSetAlarmState(MultivaluedMap params, String region) { String name = params.getFirst("AlarmName"); String state = params.getFirst("StateValue"); diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java index e9fb6febb0..efbfa4c018 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java @@ -48,6 +48,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Function; @@ -536,6 +537,18 @@ public class CloudWatchMetricsService { .map(MetricAlarm.class::cast).toList(); } + /** + * Reads current action settings after metric evaluation. Handlers run outside this monitor; + * disabling actions does not cancel work already admitted by this lookup. + */ + public synchronized Optional enabledMetricAlarm(String name, String region) { + Alarm current = alarmStore.get(region + "::" + name).orElse(null); + if (current instanceof MetricAlarm alarm && alarm.isActionsEnabled()) { + return Optional.of(alarm); + } + return Optional.empty(); + } + public List describeAlarms(List names, String prefix, String region) { return matchingAlarms(names, prefix, region).stream().filter(MetricAlarm.class::isInstance) .map(MetricAlarm.class::cast).toList(); @@ -833,6 +846,32 @@ public class CloudWatchMetricsService { return "Alarm \"" + name + "\" created"; } + /** Changes action execution for metric and composite alarms while preserving their state and other configuration. */ + public synchronized void setAlarmActionsEnabled(List alarmNames, boolean enabled, String region) { + String violation = alarmNames == null ? SmithyValidationErrors.notNull("alarmNames") + : SmithyValidationErrors.sizeOutOfRange("alarmNames", alarmNames.size(), 0, 100); + if (violation != null) { + throw SmithyValidationErrors.validationError(violation); + } + for (int i = 0; i < alarmNames.size(); i++) { + String name = alarmNames.get(i); + String path = "alarmNames.member." + (i + 1); + violation = name == null ? SmithyValidationErrors.notNull(path) + : SmithyValidationErrors.lengthOutOfRange(path, name, 1, 255); + if (violation != null) { + throw SmithyValidationErrors.validationError(violation); + } + } + for (String name : new LinkedHashSet<>(alarmNames)) { + Alarm alarm = alarmStore.get(region + "::" + name).orElse(null); + if (alarm != null && alarm.isActionsEnabled() != enabled) { + Alarm updated = MAPPER.convertValue(alarm, alarm.getClass()); + updated.setActionsEnabled(enabled); + putAlarm(updated, region); + } + } + } + /** * Deletes the named alarms, or none of them: CloudWatch refuses a request that names more than one * composite alarm, or an alarm that a composite alarm's rule names, even when the request deletes diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java index 675db45bfc..e045d7e06e 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java @@ -1,5 +1,7 @@ package io.floci.aws.services.cloudwatch.metrics; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm; import jakarta.enterprise.inject.Instance; import org.junit.jupiter.api.Test; @@ -8,16 +10,25 @@ import org.mockito.ArgumentCaptor; import java.time.Instant; import java.util.ArrayList; import java.util.List; +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.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -27,13 +38,14 @@ class AlarmEvaluatorTest { private static final String POLICY_ARN = "arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:x:resource/ecs/y:policyName/z"; - private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class); + private final CloudWatchMetricsService metricsService = spy(new CloudWatchMetricsService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"))); @SuppressWarnings("unchecked") private final Instance handlers = mock(Instance.class); private final AlarmActionHandler handler = mock(AlarmActionHandler.class); private final AlarmEvaluator evaluator = new AlarmEvaluator(metricsService, handlers); - private static MetricAlarm alarm() { + private MetricAlarm alarm() { MetricAlarm alarm = new MetricAlarm(); alarm.setAlarmName("TargetTracking-svc-AlarmHigh-abc"); alarm.setRegion(REGION); @@ -46,6 +58,7 @@ class AlarmEvaluatorTest { alarm.setComparisonOperator("GreaterThanThreshold"); alarm.setActionsEnabled(true); alarm.setAlarmActions(List.of(POLICY_ARN)); + metricsService.putMetricAlarm(alarm, REGION); return alarm; } @@ -61,9 +74,8 @@ class AlarmEvaluatorTest { } private void stubMetrics(List points) { - when(metricsService.getMetricStatistics( - any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString())) - .thenReturn(points); + doReturn(points).when(metricsService).getMetricStatistics( + any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString()); } @Test @@ -153,6 +165,47 @@ class AlarmEvaluatorTest { verify(handler, never()).handle(anyString(), any(), anyDouble(), anyString()); } + @Test + void disableDuringMetricEvaluationPreventsDispatchFromTheCapturedAlarm() throws Exception { + MetricAlarm alarm = alarm(); + CountDownLatch evaluationStarted = new CountDownLatch(1); + CountDownLatch continueEvaluation = new CountDownLatch(1); + when(handlers.iterator()).thenAnswer(invocation -> List.of(handler).iterator()); + when(handler.supports(POLICY_ARN)).thenReturn(true); + doAnswer(invocation -> { + evaluationStarted.countDown(); + assertTrue(continueEvaluation.await(10, TimeUnit.SECONDS), "Evaluation was not released"); + Instant end = invocation.getArgument(4); + List points = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + points.add(new CloudWatchMetricsService.Datapoint( + end.minusSeconds(60L * i), 1, 80, 80, 80, 80, "Percent")); + } + return points; + }).when(metricsService).getMetricStatistics( + any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString()); + + try (ExecutorService worker = Executors.newSingleThreadExecutor()) { + try { + Future evaluation = worker.submit(evaluator::evaluateAll); + assertTrue(evaluationStarted.await(10, TimeUnit.SECONDS), "Evaluation did not read the alarm"); + metricsService.setAlarmActionsEnabled(List.of(alarm.getAlarmName()), false, REGION); + continueEvaluation.countDown(); + evaluation.get(10, TimeUnit.SECONDS); + + assertEquals("ALARM", metricsService.allAlarms().getFirst().getStateValue()); + verify(handler, never()).handle(anyString(), any(), anyDouble(), anyString()); + metricsService.setAlarmActionsEnabled(List.of(alarm.getAlarmName()), true, REGION); + evaluator.evaluateAll(); + verify(handler).handle(eq(POLICY_ARN), any(), eq(80.0), eq(REGION)); + } finally { + continueEvaluation.countDown(); + } + } finally { + evaluator.stop(); + } + } + @Test void dispatchesTheMostRecentBreachingValueEvenWhenTheLatestDatapointDoesNot() { stubMetrics(datapoints(90, 85, 20)); diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmSnsNotifierTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmSnsNotifierTest.java index a280a390d2..d0831ecf6e 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmSnsNotifierTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmSnsNotifierTest.java @@ -111,6 +111,18 @@ class AlarmSnsNotifierTest { assertEquals("ALARM", alarm.getStateValue()); } + @Test + void disablingAndReenablingActionsControlsSubsequentNotifications() { + service.setAlarmActionsEnabled(List.of("test-alarm"), false, REGION); + service.setAlarmState("test-alarm", "ALARM", "breached while disabled", null, REGION); + verifyNoInteractions(sns); + assertEquals("ALARM", service.describeAlarms(List.of("test-alarm"), null, REGION).getFirst().getStateValue()); + service.setAlarmActionsEnabled(List.of("test-alarm"), true, REGION); + verifyNoInteractions(sns); + service.setAlarmState("test-alarm", "OK", "recovered after enabling", null, REGION); + verify(sns).publish(eq(TOPIC), isNull(), contains("recovered after enabling"), anyString(), eq(REGION)); + } + @Test void failedTargetDoesNotPreventOtherTargetsOrStateChange() { String missing = "arn:aws:sns:us-east-1:000000000000:missing"; diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmActionsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmActionsIntegrationTest.java new file mode 100644 index 0000000000..ff0526f196 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmActionsIntegrationTest.java @@ -0,0 +1,214 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.fasterxml.jackson.core.JsonProcessingException; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; +import software.amazon.awssdk.services.cloudwatch.model.AlarmType; +import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsResponse; +import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm; +import software.amazon.awssdk.services.cloudwatch.model.Tag; + +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class CloudWatchAlarmActionsIntegrationTest { + private static final String SCOPE = + "AWS4-HMAC-SHA256 Credential=test/20261110/cn-north-1/monitoring/aws4_request"; + + @TestHTTPResource("/") + URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void togglesBothAlarmTypesAndPreservesStateAndMetricConfiguration(boolean json) throws Exception { + String prefix = "alarm-actions-" + Long.toString(System.nanoTime(), 36); + String metric = prefix + "-metric"; + String composite = prefix + "-composite"; + Map definition = new LinkedHashMap<>(); + definition.put("AlarmName", metric); + definition.put("Namespace", "Custom/AlarmActions"); + definition.put("MetricName", "Load"); + definition.put("Statistic", "Average"); + definition.put("Period", 60); + definition.put("EvaluationPeriods", 3); + definition.put("Threshold", 70); + definition.put("ComparisonOperator", "GreaterThanThreshold"); + definition.put("TreatMissingData", "ignore"); + call(json, "PutMetricAlarm", definition).then().statusCode(200); + registerAlarmCleanup(metric); + call(json, "PutCompositeAlarm", Map.of("AlarmName", composite, "AlarmRule", "FALSE")) + .then().statusCode(200); + registerAlarmCleanup(composite); + call(json, "SetAlarmState", Map.of("AlarmName", metric, "StateValue", "ALARM", + "StateReason", "preserve this state")).then().statusCode(200); + Map selection = Map.of("AlarmNames", List.of(metric, composite), + "AlarmTypes", List.of("MetricAlarm", "CompositeAlarm")); + Map actions = Map.of("AlarmNames", List.of(metric, composite, prefix + "-absent", metric)); + for (boolean enabled : List.of(false, true, false)) { + call(json, enabled ? "EnableAlarmActions" : "DisableAlarmActions", actions).then().statusCode(200); + Response alarms = call(json, "DescribeAlarms", selection).then().statusCode(200).extract().response(); + assertEquals(Boolean.toString(enabled), field(json, alarms, "MetricAlarms", "ActionsEnabled")); + assertEquals(Boolean.toString(enabled), field(json, alarms, "CompositeAlarms", "ActionsEnabled")); + assertEquals("ALARM", field(json, alarms, "MetricAlarms", "StateValue")); + assertEquals("preserve this state", field(json, alarms, "MetricAlarms", "StateReason")); + assertEquals("Load", field(json, alarms, "MetricAlarms", "MetricName")); + assertEquals("3", field(json, alarms, "MetricAlarms", "EvaluationPeriods")); + assertEquals("FALSE", field(json, alarms, "CompositeAlarms", "AlarmRule")); + } + call(json, "DeleteAlarms", Map.of("AlarmNames", List.of(composite, metric))).then().statusCode(200); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void invalidBatchDoesNotChangeAnEarlierValidAlarm(boolean json) throws Exception { + String name = "alarm-actions-validation-" + Long.toString(System.nanoTime(), 36); + call(json, "PutCompositeAlarm", Map.of("AlarmName", name, "AlarmRule", "FALSE")).then().statusCode(200); + registerAlarmCleanup(name); + call(json, "DisableAlarmActions", Map.of()).then().statusCode(400); + List tooMany = new ArrayList<>(); + tooMany.add(name); + for (int i = 0; i < 100; i++) { + tooMany.add(name + "-" + i); + } + for (List names : List.of(tooMany, List.of(name, ""), List.of(name, "x".repeat(256)))) { + call(json, "DisableAlarmActions", Map.of("AlarmNames", names)).then().statusCode(400); + } + Response result = call(json, "DescribeAlarms", Map.of("AlarmNames", List.of(name), + "AlarmTypes", List.of("CompositeAlarm"))).then().statusCode(200).extract().response(); + assertEquals("true", field(json, result, "CompositeAlarms", "ActionsEnabled")); + call(json, "DisableAlarmActions", Map.of("AlarmNames", List.of())).then().statusCode(200); + call(json, "DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200); + assertFalse(call(json, "DescribeAlarms", Map.of("AlarmNames", List.of(name), + "AlarmTypes", List.of("CompositeAlarm"))).asString().contains(name)); + } + + @ParameterizedTest + @ValueSource(strings = {"EnableAlarmActions", "DisableAlarmActions"}) + void queryValidatesEveryNameAfterAnIndexGapBeforeChangingActions(String action) throws Exception { + String name = "alarm-actions-gap-" + Long.toString(System.nanoTime(), 36); + boolean enabled = "EnableAlarmActions".equals(action); + call(false, "PutCompositeAlarm", Map.of("AlarmName", name, "AlarmRule", "FALSE", + "ActionsEnabled", !enabled)).then().statusCode(200); + registerAlarmCleanup(name); + + call(false, action, Map.of("AlarmNames.member.1", name, "AlarmNames.member.3", "")) + .then().statusCode(400).body(containsString("ValidationError")); + Response unchanged = call(false, "DescribeAlarms", Map.of("AlarmNames", List.of(name), + "AlarmTypes", List.of("CompositeAlarm"))).then().statusCode(200).extract().response(); + assertEquals(Boolean.toString(!enabled), field(false, unchanged, "CompositeAlarms", "ActionsEnabled")); + + call(false, action, Map.of("AlarmNames.member.1", name + "-missing", "AlarmNames.member.3", name)) + .then().statusCode(200); + Response changed = call(false, "DescribeAlarms", Map.of("AlarmNames", List.of(name), + "AlarmTypes", List.of("CompositeAlarm"))).then().statusCode(200).extract().response(); + assertEquals(Boolean.toString(enabled), field(false, changed, "CompositeAlarms", "ActionsEnabled")); + + call(false, enabled ? "DisableAlarmActions" : "EnableAlarmActions", Map.of("AlarmNames.member.3", name)) + .then().statusCode(200); + Response withoutFirst = call(false, "DescribeAlarms", Map.of("AlarmNames", List.of(name), + "AlarmTypes", List.of("CompositeAlarm"))).then().statusCode(200).extract().response(); + assertEquals(Boolean.toString(!enabled), field(false, withoutFirst, "CompositeAlarms", "ActionsEnabled")); + } + + @ParameterizedTest + @ValueSource(strings = {"us-east-1", "us-gov-west-1"}) + void sdkTogglesActionsWithoutChangingStateConfigurationOrTags(String region) { + String prefix = "sdk-alarm-actions-" + Long.toString(System.nanoTime(), 36); + String metric = prefix + "-metric"; + String composite = prefix + "-composite"; + try (CloudWatchClient client = AwsTestClients.create( + CloudWatchClient.builder(), "000000000356", Region.of(region))) { + try { + client.putMetricAlarm(request -> request.alarmName(metric).namespace("Custom/AlarmActions") + .metricName("Load").statistic("Average").period(60).evaluationPeriods(3) + .threshold(70.0).comparisonOperator("GreaterThanThreshold").treatMissingData("ignore") + .tags(Tag.builder().key("purpose").value("alarm-actions").build())); + client.putCompositeAlarm(request -> request.alarmName(composite).alarmRule("FALSE")); + client.setAlarmState(request -> request.alarmName(metric).stateValue("ALARM") + .stateReason("state must survive action changes")); + for (boolean enabled : List.of(false, false, true)) { + assertDoesNotThrow(() -> { + if (enabled) { + client.enableAlarmActions(request -> request.alarmNames( + metric, composite, prefix + "-missing", metric)); + } else { + client.disableAlarmActions(request -> request.alarmNames( + metric, composite, prefix + "-missing", metric)); + } + }); + DescribeAlarmsResponse alarms = client.describeAlarms(request -> request + .alarmNames(metric, composite).alarmTypes(AlarmType.METRIC_ALARM, AlarmType.COMPOSITE_ALARM)); + assertEquals(1, alarms.metricAlarms().size()); + assertEquals(1, alarms.compositeAlarms().size()); + MetricAlarm current = alarms.metricAlarms().getFirst(); + assertEquals(enabled, current.actionsEnabled()); + assertEquals(enabled, alarms.compositeAlarms().getFirst().actionsEnabled()); + assertEquals("ALARM", current.stateValueAsString()); + assertEquals("state must survive action changes", current.stateReason()); + assertEquals("Load", current.metricName()); + assertEquals(3, current.evaluationPeriods()); + assertEquals(70.0, current.threshold()); + assertEquals("FALSE", alarms.compositeAlarms().getFirst().alarmRule()); + assertEquals(List.of(Tag.builder().key("purpose").value("alarm-actions").build()), + client.listTagsForResource(request -> request.resourceARN(current.alarmArn())).tags()); + } + } finally { + client.deleteAlarms(request -> request.alarmNames(composite, metric)); + } + DescribeAlarmsResponse remaining = client.describeAlarms(request -> request.alarmNames(metric, composite) + .alarmTypes(AlarmType.METRIC_ALARM, AlarmType.COMPOSITE_ALARM)); + assertTrue(remaining.metricAlarms().isEmpty()); + assertTrue(remaining.compositeAlarms().isEmpty()); + } + } + + private void registerAlarmCleanup(String name) { + cleanup.register(() -> { + try (CloudWatchClient client = AwsTestClients.create( + CloudWatchClient.builder(), "000000000000", Region.CN_NORTH_1, endpoint)) { + client.deleteAlarms(request -> request.alarmNames(name)); + } + }); + } + + private static String field(boolean json, Response result, String type, String name) { + return json ? result.jsonPath().getString(type + "[0]." + name) + : result.xmlPath().getString("DescribeAlarmsResponse.DescribeAlarmsResult." + type + ".member." + name); + } + + private Response call(boolean json, String action, Map body) throws JsonProcessingException { + Response response = CloudWatchTestRequests.call(endpoint, SCOPE, json, action, body); + if (!json && response.statusCode() == 200) { + assertTrue(response.asString().contains(action + "Response")); + } + return response; + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmHistoryIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmHistoryIntegrationTest.java index 1faaee37d1..8715521c89 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmHistoryIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmHistoryIntegrationTest.java @@ -1,7 +1,6 @@ package io.floci.aws.services.cloudwatch.metrics; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.common.http.TestHTTPResource; @@ -14,16 +13,13 @@ import org.junit.jupiter.params.provider.ValueSource; import java.net.URI; import java.time.Instant; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.*; @QuarkusTest class CloudWatchAlarmHistoryIntegrationTest { - private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String SCOPE = "AWS4-HMAC-SHA256 Credential=test/20261026/us-east-1/monitoring/aws4_request"; private static final String RESULT = "DescribeAlarmHistoryResponse.DescribeAlarmHistoryResult."; @@ -112,25 +108,18 @@ class CloudWatchAlarmHistoryIntegrationTest { return json ? response.jsonPath().getString("message") : response.xmlPath().getString("ErrorResponse.Error.Message"); } - private Response call(boolean json, String operation, Map body) - throws JsonProcessingException { + private Response call(boolean json, String operation, Map body) throws JsonProcessingException { if ("PutMetricAlarm".equals(operation)) { String name = body.get("AlarmName").toString(); - cleanup.register(() -> given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0") - .header("Authorization", SCOPE) - .header("X-Amz-Target", "GraniteServiceVersion20100801.DeleteAlarms") - .body(MAPPER.valueToTree(Map.of("AlarmNames", List.of(name))).toString()) - .post("/").then().statusCode(200)); + cleanup.register(() -> { + try { + CloudWatchTestRequests.call(baseUri, SCOPE, true, "DeleteAlarms", + Map.of("AlarmNames", List.of(name))).then().statusCode(200); + } catch (JsonProcessingException e) { + throw new IllegalStateException(e); + } + }); } - if (json) { - return given().contentType("application/x-amz-json-1.0").header("Authorization", SCOPE) - .header("X-Amz-Target", "GraniteServiceVersion20100801." + operation) - .body(MAPPER.writeValueAsString(body)).post("/"); - } - Map form = new LinkedHashMap<>(); - form.put("Action", operation); - form.putAll(body); - return given().contentType("application/x-www-form-urlencoded").header("Authorization", SCOPE) - .formParams(form).post("/"); + return CloudWatchTestRequests.call(baseUri, SCOPE, json, operation, body); } } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersIntegrationTest.java index 156e5140f4..769e9052c5 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersIntegrationTest.java @@ -1,7 +1,6 @@ package io.floci.aws.services.cloudwatch.metrics; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.common.http.TestHTTPResource; @@ -19,14 +18,12 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** DescribeAlarms' StateValue, ActionPrefix, ChildrenOfAlarmName and ParentsOfAlarmName over Query and JSON. */ @QuarkusTest class CloudWatchDescribeAlarmsFiltersIntegrationTest { - private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String SCOPE = "AWS4-HMAC-SHA256 Credential=test/20261027/us-east-1/monitoring/aws4_request"; private static final List BOTH_KINDS = List.of("MetricAlarm", "CompositeAlarm"); @@ -271,24 +268,6 @@ class CloudWatchDescribeAlarmsFiltersIntegrationTest { } private Response call(boolean json, String operation, Map body) throws JsonProcessingException { - if (json) { - return given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0") - .header("Authorization", SCOPE) - .header("X-Amz-Target", "GraniteServiceVersion20100801." + operation) - .body(MAPPER.writeValueAsString(body)).post("/"); - } - Map form = new LinkedHashMap<>(); - form.put("Action", operation); - body.forEach((key, value) -> { - if (value instanceof List values) { - for (int index = 0; index < values.size(); index++) { - form.put(key + ".member." + (index + 1), values.get(index)); - } - } else { - form.put(key, value); - } - }); - return given().port(baseUri.getPort()).contentType("application/x-www-form-urlencoded") - .header("Authorization", SCOPE).formParams(form).post("/"); + return CloudWatchTestRequests.call(baseUri, SCOPE, json, operation, body); } } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java index 3a7dd707aa..8379d91dbf 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchJsonTargetSignatureIntegrationTest.java @@ -9,6 +9,7 @@ import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -89,6 +90,55 @@ class CloudWatchJsonTargetSignatureIntegrationTest { } } + @Test + void alarmActionPermissionsAreCheckedBeforeChangingTheAlarm() throws Exception { + String name = "cw-action-permissions-" + Long.toString(System.nanoTime(), 36); + AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "monitoring"); + json(CURRENT_TARGET, "PutCompositeAlarm").filter(root) + .body(""" + { + "AlarmName": "%s", + "AlarmRule": "FALSE", + "ActionsEnabled": false + } + """.formatted(name)) + .post("/").then().statusCode(200); + String selected = """ + { + "AlarmNames": ["%s"] + } + """.formatted(name); + String describe = """ + { + "AlarmNames": ["%s"], + "AlarmTypes": ["CompositeAlarm"] + } + """.formatted(name); + try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "cw-action-permissions-", "enable-only", """ + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "cloudwatch:EnableAlarmActions", + "Resource": "*" + } + ] + } + """)) { + AwsRequestSigner signer = user.signer("monitoring"); + json(CURRENT_TARGET, "EnableAlarmActions").filter(signer).body(selected).post("/") + .then().statusCode(200); + json(CURRENT_TARGET, "DisableAlarmActions").filter(signer).body(selected).post("/") + .then().statusCode(400).body("__type", equalTo("AccessDeniedException")); + json(CURRENT_TARGET, "DescribeAlarms").filter(root).body(describe).post("/") + .then().statusCode(200).body("CompositeAlarms[0].ActionsEnabled", equalTo(true)); + } finally { + json(CURRENT_TARGET, "DeleteAlarms").filter(root).body(selected).post("/") + .then().statusCode(200); + } + } + private static RequestSpecification json(String prefix, String operation) { return given().contentType("application/x-amz-json-1.0") .header("X-Amz-Target", prefix + operation) diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchTestRequests.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchTestRequests.java new file mode 100644 index 0000000000..64f080a36b --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchTestRequests.java @@ -0,0 +1,52 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.restassured.response.Response; + +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; + +final class CloudWatchTestRequests { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private CloudWatchTestRequests() { + } + + static Response call(URI endpoint, String scope, boolean json, String operation, Map body) + throws JsonProcessingException { + if (json) { + return given().port(endpoint.getPort()).header("Authorization", scope) + .contentType("application/x-amz-json-1.0") + .header("X-Amz-Target", "GraniteServiceVersion20100801." + operation) + .body(MAPPER.writeValueAsString(body)).post("/"); + } + return given().port(endpoint.getPort()).header("Authorization", scope) + .contentType("application/x-www-form-urlencoded") + .formParams(queryParameters(operation, body)).post("/"); + } + + private static Map queryParameters(String operation, Map body) { + Map parameters = new LinkedHashMap<>(); + parameters.put("Action", operation); + parameters.put("Version", "2010-08-01"); + for (Map.Entry member : body.entrySet()) { + if (member.getValue() instanceof List items) { + if (items.isEmpty()) { + parameters.put(member.getKey(), ""); + } + for (int index = 0; index < items.size(); index++) { + parameters.put(member.getKey() + ".member." + (index + 1), items.get(index)); + } + } else { + parameters.put(member.getKey(), member.getValue()); + } + } + return parameters; + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java index 820b790982..b9b8c260b8 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java @@ -18,7 +18,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.*; @QuarkusTest @@ -283,33 +282,18 @@ class CompositeAlarmIntegrationTest { return json ? response.jsonPath().getString("message") : response.xmlPath().getString("ErrorResponse.Error.Message"); } - private Response call(boolean json, String operation, Map body) - throws JsonProcessingException { + private Response call(boolean json, String operation, Map body) throws JsonProcessingException { if ("PutCompositeAlarm".equals(operation) || "PutMetricAlarm".equals(operation)) { String name = body.get("AlarmName").toString(); - cleanup.register(() -> given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0") - .header("Authorization", SCOPE) - .header("X-Amz-Target", "GraniteServiceVersion20100801.DeleteAlarms") - .body(MAPPER.valueToTree(Map.of("AlarmNames", List.of(name))).toString()) - .post("/").then().statusCode(200)); - } - if (json) { - return given().contentType("application/x-amz-json-1.0").header("Authorization", SCOPE) - .header("X-Amz-Target", "GraniteServiceVersion20100801." + operation) - .body(MAPPER.writeValueAsString(body)).post("/"); - } - Map form = new LinkedHashMap<>(); - form.put("Action", operation); - body.forEach((key, value) -> { - if (value instanceof List values) { - for (int index = 0; index < values.size(); index++) { - form.put(key + ".member." + (index + 1), values.get(index)); + cleanup.register(() -> { + try { + CloudWatchTestRequests.call(baseUri, SCOPE, true, "DeleteAlarms", + Map.of("AlarmNames", List.of(name))).then().statusCode(200); + } catch (JsonProcessingException e) { + throw new IllegalStateException(e); } - } else { - form.put(key, value); - } - }); - return given().contentType("application/x-www-form-urlencoded").header("Authorization", SCOPE) - .formParams(form).post("/"); + }); + } + return CloudWatchTestRequests.call(baseUri, SCOPE, json, operation, body); } }