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 <jxnprice@amazon.com>
Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-14 21:13:43 -04:00
1 parent 029f6d1a61
commit c5ac8e8ad0
14 files changed
+508 -79

No files matched your search

@@ -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<AlarmActionHandler> 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<CloudWatchMetricsService.Datapoint> 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<CloudWatchMetricsService.Datapoint> 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));
@@ -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";
@@ -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<String, Object> 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<String, Object> selection = Map.of("AlarmNames", List.of(metric, composite),
"AlarmTypes", List.of("MetricAlarm", "CompositeAlarm"));
Map<String, Object> 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<String> tooMany = new ArrayList<>();
tooMany.add(name);
for (int i = 0; i < 100; i++) {
tooMany.add(name + "-" + i);
}
for (List<String> 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<String, ?> 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;
}
}
@@ -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<String, ?> body)
throws JsonProcessingException {
private Response call(boolean json, String operation, Map<String, ?> 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<String, Object> 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);
}
}
@@ -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<String> BOTH_KINDS = List.of("MetricAlarm", "CompositeAlarm");
@@ -271,24 +268,6 @@ class CloudWatchDescribeAlarmsFiltersIntegrationTest {
}
private Response call(boolean json, String operation, Map<String, ?> 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<String, Object> 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);
}
}
@@ -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)
@@ -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<String, ?> 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<String, Object> queryParameters(String operation, Map<String, ?> body) {
Map<String, Object> parameters = new LinkedHashMap<>();
parameters.put("Action", operation);
parameters.put("Version", "2010-08-01");
for (Map.Entry<String, ?> 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;
}
}
@@ -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<String, ?> body)
throws JsonProcessingException {
private Response call(boolean json, String operation, Map<String, ?> 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<String, Object> 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);
}
}