From bbc80c9b5166a763a612afa3a2a103d1948aed6f Mon Sep 17 00:00:00 2001 From: glorfindel33 <217200047+glorfindel33@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:50:31 +0200 Subject: [PATCH] fix(cloudwatch): refuse EvaluationInterval on MetricName and Metrics alarms (#8863) PutMetricAlarm now refuses EvaluationInterval on an alarm configured with MetricName or Metrics with InvalidParameterCombination, as the API reference documents, and refuses an integer outside 10 to 3600 or a value that is not an integer. AWS::CloudWatch::Alarm applies the same refusal on create and update, including a template that sets Metrics, which the provisioner reads only to detect it. ProvisionContext gains resolveOptionalBigInteger, sharing resolveOptionalInt's rule for what counts as absent. Closes #8894 --- docs/services/cloudwatch.md | 9 + .../CloudWatchCfnProvisioner.java | 12 +- .../provisioners/ProvisionContext.java | 34 +++- .../metrics/CloudWatchMetricsJsonHandler.java | 15 +- .../CloudWatchMetricsQueryHandler.java | 17 +- .../metrics/CloudWatchMetricsService.java | 51 ++++- .../CloudWatchCfnProvisionerTest.java | 69 ++++++- .../provisioners/ProvisionContextTest.java | 27 ++- .../CloudWatchMetricsJsonHandlerTest.java | 33 ++++ .../CloudWatchMetricsQueryHandlerTest.java | 47 ++++- .../metrics/CloudWatchMetricsServiceTest.java | 49 +++++ ...larmEvaluationIntervalIntegrationTest.java | 179 ++++++++++++++++++ .../cloudformation/writable-property-gaps.tsv | 2 - 13 files changed, 527 insertions(+), 17 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPutMetricAlarmEvaluationIntervalIntegrationTest.java diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index c059306317..78e44d2068 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -561,6 +561,15 @@ Tags supplied to `PutMetricAlarm` apply only when creating an alarm; use `TagRes `UntagResource` to change existing tags. `SetAlarmState` requires `StateReason` and rejects missing or unknown state values before changing the alarm. +`PutMetricAlarm` refuses an `EvaluationInterval` on an alarm configured with `MetricName` or `Metrics` +with `InvalidParameterCombination`: the API reference allows it only with `EvaluationCriteria`, which +Floci does not model and accepts without keeping the interval. Over Query and through CloudFormation an +integer outside 10 to 3600, of any size, is a `ValidationError`; a value that is not an integer is an +`InvalidParameterValue` over Query, a `SerializationException` over JSON and CBOR (as is a number beyond +32 bits) and a failed resource through CloudFormation. AWS documents none of these answers. An +`AWS::CloudWatch::Alarm` fails the same way on create and on update, so a stack that sets the property +cannot change that alarm until its template drops it. + `StateTransitionedTimestamp` records when an alarm's `StateValue` last changed, while `StateUpdatedTimestamp` moves on every state update, including one that keeps the value. Alarms stored before Floci recorded it report their last state update. diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java index 1608473919..416e450edb 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java @@ -7,6 +7,7 @@ import io.floci.aws.services.cloudwatch.metrics.model.Dimension; import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm; import jakarta.enterprise.context.ApplicationScoped; +import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -77,12 +78,21 @@ public class CloudWatchCfnProvisioner implements CfnResourceProvisioner { addAlarmActions(props, "OKActions", ctx, alarm.getOkActions()); addAlarmActions(props, "InsufficientDataActions", ctx, alarm.getInsufficientDataActions()); - cloudWatchMetricsService.putMetricAlarm(alarm, ctx.region()); + BigInteger interval = ctx.resolveOptionalBigInteger(props, "EvaluationInterval"); + if (interval != null && declaresMetrics(props)) { + CloudWatchMetricsService.rejectEvaluationInterval(name, interval, true); + } + cloudWatchMetricsService.putMetricAlarm(alarm, ctx.region(), interval); // Ref returns the alarm name; Fn::GetAtt Arn returns the alarm ARN. r.setPhysicalId(name); r.getAttributes().put("Arn", alarm.getAlarmArn()); } + /** Whether the template sets a non-empty {@code Metrics} (the engine has dropped {@code AWS::NoValue} by now). */ + private static boolean declaresMetrics(JsonNode props) { + return props != null && props.path("Metrics").size() > 0; + } + private void addAlarmActions(JsonNode props, String field, ProvisionContext ctx, List target) { if (props != null && props.has(field) && props.get(field).isArray()) { for (JsonNode action : props.get(field)) { diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java index 3eef99f6c2..02891e73ad 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java @@ -2,9 +2,11 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.QueryConstraintCheck; import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; import io.floci.aws.services.cloudformation.model.StackEvent; +import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -204,17 +206,43 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio * apart from {@code AWS::NoValue} here, so it stays null as well. */ public Integer resolveOptionalInt(JsonNode props, String name) { - String value = resolveOptional(props, name); - if (value == null || (value.isBlank() && !props.get(name).isTextual())) { + String value = resolveOptionalNumber(props, name); + if (value == null) { return null; } try { return Integer.valueOf(value.trim()); } catch (NumberFormatException e) { - throw new AwsException("ValidationError", "Value of property " + name + " must be an integer.", 400); + throw notAnInteger(name); } } + /** + * Like {@link #resolveOptionalInt}, for an integer of any size: a value beyond an {@code int} is + * the service's to answer, not the reader's. What counts as absent and the refusal of a value that + * is no integer are the same. + */ + public BigInteger resolveOptionalBigInteger(JsonNode props, String name) { + String value = resolveOptionalNumber(props, name); + if (value == null) { + return null; + } + if (!QueryConstraintCheck.isInteger(value)) { + throw notAnInteger(name); + } + return new BigInteger(value.trim()); + } + + /** The text of an optional numeric property, or null when it counts as absent. */ + private String resolveOptionalNumber(JsonNode props, String name) { + String value = resolveOptional(props, name); + return value == null || (value.isBlank() && !props.get(name).isTextual()) ? null : value; + } + + private static AwsException notAnInteger(String name) { + return new AwsException("ValidationError", "Value of property " + name + " must be an integer.", 400); + } + /** * Resolves an optional boolean property, or null when it is absent or explicitly null. An intrinsic * that resolves to empty ({@code AWS::NoValue}) stays null too. Any other value has to be true or 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 40be2b503c..e61d7dce50 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 @@ -28,6 +28,7 @@ import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; import java.math.BigDecimal; +import java.math.BigInteger; import java.time.DateTimeException; import java.time.Instant; import java.util.ArrayList; @@ -350,10 +351,22 @@ public class CloudWatchMetricsJsonHandler { alarm.setTreatMissingData(request.path("TreatMissingData").asText(null)); alarm.setDimensions(parseDimensionsJson(request.path("Dimensions"))); - metricsService.putMetricAlarm(alarm, region); + metricsService.putMetricAlarm(alarm, region, evaluationInterval(request)); return Response.ok(objectMapper.createObjectNode()).build(); } + /** The EvaluationInterval of a PutMetricAlarm request: null when absent or null, an integer otherwise. */ + private static BigInteger evaluationInterval(JsonNode request) { + JsonNode node = request.get("EvaluationInterval"); + if (node == null || node.isNull()) { + return null; + } + if (!node.isIntegralNumber() || !node.canConvertToInt()) { + throw new AwsException("SerializationException", "EvaluationInterval must be an integer", 400); + } + return node.bigIntegerValue(); + } + private Response handlePutCompositeAlarm(JsonNode request, String region) { rejectSuppressor(request); CompositeAlarm alarm = new CompositeAlarm(); 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 64e187a13b..c969752ae4 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 @@ -6,6 +6,7 @@ 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; +import io.floci.aws.core.common.QueryConstraintCheck; import io.floci.aws.core.common.XmlBuilder; import io.floci.aws.services.cloudwatch.dashboards.CloudWatchDashboardsService; import io.floci.aws.services.cloudwatch.dashboards.model.Dashboard; @@ -26,6 +27,7 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; +import java.math.BigInteger; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.ArrayList; @@ -260,7 +262,7 @@ public class CloudWatchMetricsQueryHandler { private Response handlePutMetricAlarm(MultivaluedMap params, String region) { MetricAlarm alarm = parseAlarm(params); - metricsService.putMetricAlarm(alarm, region); + metricsService.putMetricAlarm(alarm, region, parseEvaluationInterval(params)); return Response.ok(AwsQueryResponse.envelopeNoResult("PutMetricAlarm", null)).build(); } @@ -1013,6 +1015,19 @@ public class CloudWatchMetricsQueryHandler { } } + /** None if absent or empty; a value that is no integer is an InvalidParameterValue, as in PutMetricData. */ + private BigInteger parseEvaluationInterval(MultivaluedMap params) { + String value = params.getFirst("EvaluationInterval"); + if (value == null || value.isEmpty()) { + return null; + } + if (!QueryConstraintCheck.isInteger(value)) { + throw CloudWatchMetricsException.invalidParameterValue( + "EvaluationInterval must be an integer between 10 and 3600."); + } + return new BigInteger(value.trim()); + } + private double parseDouble(String value, double defaultValue) { if (value == null) { return defaultValue; 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 aefb33d45e..05b73cd2b5 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 @@ -32,6 +32,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.math.BigInteger; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; @@ -422,6 +423,19 @@ public class CloudWatchMetricsService { * a child changes state. */ public synchronized void putMetricAlarm(MetricAlarm alarm, String region) { + putMetricAlarm(alarm, region, null); + } + + /** + * Creates or updates a metric alarm. An {@code evaluationInterval}, an integer of any size, is checked after + * the alarm name and against its range of 10 to 3600, then against the alarm: the PutMetricAlarm reference + * says it "cannot be specified" for an alarm configured with MetricName or Metrics. + */ + public synchronized void putMetricAlarm(MetricAlarm alarm, String region, BigInteger evaluationInterval) { + if (evaluationInterval != null) { + rejectEvaluationInterval(alarm.getAlarmName(), evaluationInterval, + alarm.getMetricName() != null || !alarm.getMetrics().isEmpty()); + } boolean created = alarmStore.get(region + "::" + alarm.getAlarmName()).isEmpty(); putAlarm(alarm, region); if (created) { @@ -429,6 +443,33 @@ public class CloudWatchMetricsService { } } + /** + * Refuses an {@code EvaluationInterval} as {@code PutMetricAlarm} does: by the alarm name, then the range, then + * the alarm's configuration. Public for the CloudFormation provisioner, which does not keep a template's + * {@code Metrics} on the alarm it passes to {@link #putMetricAlarm(MetricAlarm, String, BigInteger)}. + */ + public static void rejectEvaluationInterval(String alarmName, BigInteger interval, boolean metricConfigured) { + List violations = Stream.of(alarmNameViolation(alarmName), rangeViolation(interval)) + .filter(Objects::nonNull).toList(); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationError(violations); + } + if (metricConfigured) { + throw CloudWatchMetricsException.invalidParameterCombination( + "EvaluationInterval cannot be specified for alarms configured with MetricName or Metrics."); + } + } + + private static String rangeViolation(BigInteger interval) { + if (interval.compareTo(BigInteger.valueOf(10)) < 0) { + return SmithyValidationErrors.valueTooSmall("evaluationInterval", interval.toString(), 10); + } + if (interval.compareTo(BigInteger.valueOf(3600)) > 0) { + return SmithyValidationErrors.valueTooLarge("evaluationInterval", interval.toString(), 3600); + } + return null; + } + public void putCompositeAlarm(CompositeAlarm alarm, String region) { putCompositeAlarm(alarm, region, true); } @@ -469,13 +510,19 @@ public class CloudWatchMetricsService { .collect(Collectors.toCollection(LinkedHashSet::new)); } - private void putAlarm(Alarm alarm, String region) { - String name = alarm.getAlarmName(); + /** The violation of the alarm name's constraints, or null for a name that meets them. */ + private static String alarmNameViolation(String name) { String violation = name == null ? SmithyValidationErrors.notNull("alarmName") : SmithyValidationErrors.lengthOutOfRange("alarmName", name, 1, 255); if (violation == null && name.isBlank()) { violation = SmithyValidationErrors.lengthTooShort("alarmName", name, 1); } + return violation; + } + + private void putAlarm(Alarm alarm, String region) { + String name = alarm.getAlarmName(); + String violation = alarmNameViolation(name); if (violation != null) { throw SmithyValidationErrors.validationError(violation); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java index 36ede0d7d8..bf2d250f7a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java @@ -2,14 +2,18 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService; import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentCaptor; +import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -17,10 +21,14 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -62,7 +70,7 @@ class CloudWatchCfnProvisionerTest { r.setAttributes(new HashMap<>()); provisioner.provision(r, props(json), ctx); ArgumentCaptor alarm = ArgumentCaptor.forClass(MetricAlarm.class); - verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION)); + verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION), isNull()); return alarm.getValue(); } @@ -82,7 +90,7 @@ class CloudWatchCfnProvisionerTest { assertTrue(r.getAttributes().containsKey("Arn"), "aws-cloudwatch-alarm.json declares Arn read-only"); ArgumentCaptor alarm = ArgumentCaptor.forClass(MetricAlarm.class); - verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION)); + verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION), isNull()); assertEquals("CPUUtilization", alarm.getValue().getMetricName()); assertEquals("AWS/EC2", alarm.getValue().getNamespace()); assertEquals(80.5, alarm.getValue().getThreshold()); @@ -175,6 +183,63 @@ class CloudWatchCfnProvisionerTest { assertEquals(0.0, alarm.getThreshold()); } + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "60|60", "\"60\"|60", "\" 60 \"|60", "99999999999|99999999999", + "\"99999999999999999999\"|99999999999999999999", + "{\"Fn::If\": [\"C\", 60, {\"Ref\": \"AWS::NoValue\"}]}|NONE", "\"abc\"|FAIL", "60.0|FAIL", "\"\"|FAIL"}) + void evaluationIntervalIsReadAsAnIntegerOfAnySize(String literal, String expected) { + StackResource r = new StackResource(); + r.setLogicalId("Alarm"); + r.setResourceType("AWS::CloudWatch::Alarm"); + r.setAttributes(new HashMap<>()); + JsonNode props = props(""" + {"AlarmName": "a", "MetricName": "Errors", "Namespace": "MyApp", "EvaluationInterval": %s} + """.formatted(literal)); + + if ("FAIL".equals(expected)) { + AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx)); + assertEquals("Value of property EvaluationInterval must be an integer.", refused.getMessage()); + verify(metrics, never()).putMetricAlarm(any(), anyString(), any()); + return; + } + provisioner.provision(r, props, ctx); + + verify(metrics).putMetricAlarm(any(MetricAlarm.class), eq(REGION), + "NONE".equals(expected) ? isNull() : eq(new BigInteger(expected))); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "[{\"Id\": \"m1\", \"Expression\": \"1 + 1\"}]|60|REFUSED", + "[{\"Id\": \"m1\", \"Expression\": \"1 + 1\"}]|NONE|STORED", + "[]|60|STORED"}) + void anIntervalWithMetricsInTheTemplateIsRefusedOnCreateAndUpdate(String metricsJson, String interval, + String expected) { + StackResource r = new StackResource(); + r.setLogicalId("Alarm"); + r.setResourceType("AWS::CloudWatch::Alarm"); + r.setAttributes(new HashMap<>()); + JsonNode props = props(""" + {"AlarmName": "a", "Metrics": %s%s} + """.formatted(metricsJson, "NONE".equals(interval) ? "" : ", \"EvaluationInterval\": " + interval)); + + if ("REFUSED".equals(expected)) { + for (ProvisionContext context : List.of(ctx, ctx.withPriorPhysicalId("a"))) { + AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(r, props, context)); + assertEquals("InvalidParameterCombination", refused.getErrorCode()); + assertEquals("EvaluationInterval cannot be specified for alarms configured with MetricName or " + + "Metrics.", refused.getMessage()); + } + verify(metrics, never()).putMetricAlarm(any(), anyString(), any()); + return; + } + provisioner.provision(r, props, ctx); + + verify(metrics).putMetricAlarm(any(MetricAlarm.class), eq(REGION), + "NONE".equals(interval) ? isNull() : eq(new BigInteger(interval))); + } + @Test void deleteReachesTheService() { provisioner.delete("AWS::CloudWatch::Alarm", "cpu-high", REGION); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java index 8a45b4637c..fc47bf0ade 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java @@ -10,10 +10,12 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.lang.reflect.RecordComponent; +import java.math.BigInteger; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Function; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -283,7 +285,7 @@ class ProvisionContextTest { assertNull(ctx.resolveOptionalInt(null, "Port"), "no properties at all"); assertNull(ctx.resolveOptionalInt(props("{\"Port\": {\"Ref\": \"AWS::NoValue\"}}"), "Port"), "an intrinsic that resolves to blank, as AWS::NoValue does"); - for (String literal : List.of("\"\"", "\"ten\"", "\"4.5\"", "4.5", "true")) { + for (String literal : List.of("\"\"", "\"ten\"", "\"4.5\"", "4.5", "true", "99999999999")) { AwsException e = assertThrows(AwsException.class, () -> ctx.resolveOptionalInt(props("{\"Port\": " + literal + "}"), "Port"), literal); assertEquals("ValidationError", e.getErrorCode(), literal); @@ -291,6 +293,29 @@ class ProvisionContextTest { } } + @Test + void resolveOptionalBigIntegerReadsAnyWidthAndTakesTheAbsentRuleOfResolveOptionalInt() { + ProvisionContext ctx = context(null); + JsonNode size = props("{\"Ref\": \"Size\"}"); + when(engine.resolve(size)).thenReturn("3"); + Function read = json -> ctx.resolveOptionalBigInteger(props(json), "Port"); + + assertEquals(BigInteger.valueOf(42), read.apply("{\"Port\": 42}"), "a number"); + assertEquals(new BigInteger("99999999999999999999"), read.apply("{\"Port\": \" 99999999999999999999 \"}"), + "any width, trimmed"); + assertEquals(BigInteger.valueOf(3), read.apply("{\"Port\": {\"Ref\": \"Size\"}}"), "an intrinsic's result"); + assertNull(read.apply("{}"), "absent"); + assertNull(read.apply("{\"Port\": null}"), "explicitly null"); + assertNull(ctx.resolveOptionalBigInteger(null, "Port"), "no properties at all"); + assertNull(read.apply("{\"Port\": {\"Ref\": \"AWS::NoValue\"}}"), + "an intrinsic that resolves to blank, as AWS::NoValue does"); + for (String literal : List.of("\"\"", "\"ten\"", "\"4.5\"", "4.5", "true")) { + AwsException e = assertThrows(AwsException.class, () -> read.apply("{\"Port\": " + literal + "}"), literal); + assertEquals("ValidationError", e.getErrorCode(), literal); + assertEquals("Value of property Port must be an integer.", e.getMessage(), literal); + } + } + @Test void resolveOptionalBooleanReadsABooleanAndRefusesAnythingElse() { ProvisionContext ctx = context(null); diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java index 7bf7113d6e..a0b80e5711 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java @@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.math.BigDecimal; import java.time.Instant; @@ -372,6 +373,38 @@ class CloudWatchMetricsJsonHandlerTest { return ((ObjectNode) describeResp.getEntity()).get("MetricAlarms").get(0); } + @ParameterizedTest + @ValueSource(strings = {"\"60\"", "60.5", "true", "[60]", "4294967356"}) + void putMetricAlarm_refusesAnIntervalThatIsNoIntegerOrBeyondAnInt(String interval) throws Exception { + ObjectNode request = alarmRequest("NoInteger"); + request.set("EvaluationInterval", MAPPER.readTree(interval)); + + AwsException refused = assertThrows(AwsException.class, + () -> handler.handle("PutMetricAlarm", request, REGION)); + + assertEquals("SerializationException", refused.getErrorCode()); + assertEquals(400, refused.getHttpStatus()); + assertTrue(service.describeAlarms(List.of("NoInteger"), null, REGION).isEmpty()); + } + + @Test + void putMetricAlarm_takesANullIntervalAsNone() { + ObjectNode request = alarmRequest("NullInterval"); + request.putNull("EvaluationInterval"); + + assertEquals(200, handler.handle("PutMetricAlarm", request, REGION).getStatus()); + } + + @Test + void putMetricAlarm_passesTheIntervalToTheService() { + ObjectNode request = alarmRequest("WithInterval").put("EvaluationInterval", 60); + + AwsException refused = assertThrows(AwsException.class, + () -> handler.handle("PutMetricAlarm", request, REGION)); + + assertEquals("InvalidParameterCombinationException", refused.jsonType()); + } + private static ObjectNode alarmRequest(String name) { ObjectNode req = MAPPER.createObjectNode(); req.put("AlarmName", name); diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java index 420cb5e0c3..dd9e3bad49 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java @@ -9,9 +9,11 @@ import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; 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 org.mockito.ArgumentCaptor; +import java.math.BigInteger; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -23,6 +25,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -226,7 +229,7 @@ class CloudWatchMetricsQueryHandlerTest { handler.handle("PutMetricAlarm", params, REGION); ArgumentCaptor captor = ArgumentCaptor.forClass(MetricAlarm.class); - verify(metricsService).putMetricAlarm(captor.capture(), anyString()); + verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull()); assertTrue(captor.getValue().isActionsEnabled()); } @@ -241,7 +244,7 @@ class CloudWatchMetricsQueryHandlerTest { handler.handle("PutMetricAlarm", params, REGION); ArgumentCaptor captor = ArgumentCaptor.forClass(MetricAlarm.class); - verify(metricsService).putMetricAlarm(captor.capture(), anyString()); + verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull()); assertFalse(captor.getValue().isActionsEnabled()); } @@ -259,7 +262,7 @@ class CloudWatchMetricsQueryHandlerTest { handler.handle("PutMetricAlarm", params, REGION); ArgumentCaptor captor = ArgumentCaptor.forClass(MetricAlarm.class); - verify(metricsService).putMetricAlarm(captor.capture(), anyString()); + verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull()); assertEquals(3, captor.getValue().getEvaluationPeriods()); assertNull(captor.getValue().getDatapointsToAlarm()); } @@ -276,10 +279,46 @@ class CloudWatchMetricsQueryHandlerTest { handler.handle("PutMetricAlarm", params, REGION); ArgumentCaptor captor = ArgumentCaptor.forClass(MetricAlarm.class); - verify(metricsService).putMetricAlarm(captor.capture(), anyString()); + verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull()); assertEquals(2, captor.getValue().getDatapointsToAlarm()); } + @ParameterizedTest + @CsvSource(nullValues = "-", value = {"abc, TestAlarm", "60.0, TestAlarm", "' ', TestAlarm", "abc, -"}) + void aValueThatIsNoIntegerIsAnInvalidParameterValue(String interval, String name) { + MultivaluedMap params = alarmParams(name, interval); + + AwsException refused = assertThrows(AwsException.class, + () -> handler.handle("PutMetricAlarm", params, REGION)); + + assertEquals("InvalidParameterValue", refused.getErrorCode()); + assertEquals(400, refused.getHttpStatus()); + verify(metricsService, never()).putMetricAlarm(any(), anyString(), any()); + } + + @ParameterizedTest + @CsvSource(nullValues = "-", value = {"-, -", "'', -", "60, 60", "' 60 ', 60", + "99999999999999999999, 99999999999999999999"}) + void anIntegerReachesTheServiceAndAnEmptyValueIsNone(String interval, String expected) { + handler.handle("PutMetricAlarm", alarmParams("TestAlarm", interval), REGION); + + verify(metricsService).putMetricAlarm(any(MetricAlarm.class), eq(REGION), + expected == null ? isNull() : eq(new BigInteger(expected))); + } + + private static MultivaluedMap alarmParams(String name, String interval) { + MultivaluedMap params = new MultivaluedHashMap<>(); + if (name != null) { + params.putSingle("AlarmName", name); + } + params.putSingle("MetricName", "M"); + params.putSingle("Namespace", "NS"); + if (interval != null) { + params.putSingle("EvaluationInterval", interval); + } + return params; + } + // The JSON handler forwards the Unit filter now; this pins the Query path to the same // contract so the two protocols cannot drift apart again. @Test diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java index 0e4267db69..56851bcfe9 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java @@ -9,6 +9,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.cloudwatch.metrics.model.Alarm; import io.floci.aws.services.cloudwatch.metrics.model.AlarmHistoryItem; +import io.floci.aws.services.cloudwatch.metrics.model.AlarmMetricDataQuery; import io.floci.aws.services.cloudwatch.metrics.model.CompositeAlarm; import io.floci.aws.services.cloudwatch.metrics.model.Dimension; import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm; @@ -16,9 +17,11 @@ import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum; import org.junit.jupiter.api.BeforeEach; 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.NullSource; import org.junit.jupiter.params.provider.ValueSource; +import java.math.BigInteger; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; @@ -914,4 +917,50 @@ class CloudWatchMetricsServiceTest { assertEquals(1, store.scan(k -> true).size(), "the default partition holds only the ambient put"); assertEquals(2.0, store.scan(k -> true).getFirst().getValue()); } + + // M: MetricName, X: Metrics, C: neither (an EvaluationCriteria alarm); "-" is no interval + @ParameterizedTest + @CsvSource(nullValues = "-", value = { + "5, M, true, LOW", "9, M, true, LOW", "9, C, true, LOW", "-99999999999999999999, C, true, LOW", + "10, M, true, COMBINATION", "45, M, true, COMBINATION", "60, X, true, COMBINATION", + "3600, M, true, COMBINATION", "3601, M, true, HIGH", "99999999999999999999, M, true, HIGH", + "60, C, true, STORED", "3600, C, true, STORED", "-, M, true, STORED", + "60, M, false, NAME", "60, C, false, NAME", "-, M, false, NAME", + "5, M, false, NAME_LOW", "99999999999999999999, M, false, NAME_HIGH"}) + void evaluationIntervalIsCheckedAfterTheNameThenItsRangeThenTheAlarmKind(String interval, String kind, + boolean named, String expected) { + MetricAlarm alarm = new MetricAlarm(); + alarm.setAlarmName(named ? "a" : null); + if ("M".equals(kind)) { + alarm.setMetricName("Errors"); + } else if ("X".equals(kind)) { + alarm.getMetrics().add(new AlarmMetricDataQuery("m1", "1 + 1", null, true, null, null, null)); + } + BigInteger value = interval == null ? null : new BigInteger(interval); + if ("STORED".equals(expected)) { + service.putMetricAlarm(alarm, REGION, value); + assertEquals(1, service.describeAlarms(List.of("a"), null, REGION).size()); + return; + } + + AwsException refused = assertThrows(AwsException.class, () -> service.putMetricAlarm(alarm, REGION, value)); + + String nameOnly = named ? null + : assertThrows(AwsException.class, () -> service.putMetricAlarm(alarm, REGION)).getMessage(); + String bound = expected.endsWith("LOW") ? "greater than or equal to 10" : "less than or equal to 3600"; + String range = "Value '" + interval + "' at 'evaluationInterval' failed to satisfy constraint: Member must " + + "have value " + bound; + switch (expected) { + case "COMBINATION" -> { + assertEquals("InvalidParameterCombination", refused.getErrorCode()); + assertEquals("EvaluationInterval cannot be specified for alarms configured with MetricName or " + + "Metrics.", refused.getMessage()); + } + case "NAME" -> assertEquals(nameOnly, refused.getMessage()); + case "LOW", "HIGH" -> assertEquals("1 validation error detected: " + range, refused.getMessage()); + default -> assertEquals("2 validation errors detected: " + nameOnly.substring(nameOnly.indexOf(": ") + 2) + + "; " + range, refused.getMessage()); + } + assertTrue(service.describeAlarms(List.of("a"), null, REGION).isEmpty()); + } } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPutMetricAlarmEvaluationIntervalIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPutMetricAlarmEvaluationIntervalIntegrationTest.java new file mode 100644 index 0000000000..1337d1b0aa --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchPutMetricAlarmEvaluationIntervalIntegrationTest.java @@ -0,0 +1,179 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; +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.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; +import software.amazon.awssdk.services.cloudwatch.model.InvalidParameterCombinationException; +import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm; + +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** An {@code EvaluationInterval} on a MetricName or Metrics alarm is refused, so a stack that sets it rolls back. */ +@QuarkusTest +class CloudWatchPutMetricAlarmEvaluationIntervalIntegrationTest { + + private static final String SCOPE = + "AWS4-HMAC-SHA256 Credential=test/20261117/us-east-1/monitoring/aws4_request"; + private static final String COMBINATION = + "EvaluationInterval cannot be specified for alarms configured with MetricName or Metrics."; + + @TestHTTPResource + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private CloudWatchClient cloudWatch; + private CloudFormationClient cfn; + private String suffix; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void setUp() { + cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), "test", Region.US_EAST_1); + cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + suffix = Long.toString(System.nanoTime(), 36); + } + + @AfterEach + void closeClients() { + cloudWatch.close(); + cfn.close(); + } + + @ParameterizedTest + @CsvSource({"false, InvalidParameterCombination", "true, InvalidParameterCombinationException"}) + void bothProtocolsRefuseTheIntervalOnAMetricNameAlarm(boolean json, String code) throws Exception { + String name = "wire-interval-" + suffix; + cleanup.register(() -> cloudWatch.deleteAlarms(r -> r.alarmNames(name))); + Map body = new LinkedHashMap<>(Map.of("AlarmName", name, "Namespace", "MyApp", + "MetricName", "MyMetric", "Statistic", "Sum", "Period", 60, "EvaluationPeriods", 1, "Threshold", 1, + "ComparisonOperator", "GreaterThanOrEqualToThreshold", "EvaluationInterval", 60)); + + Response refused = CloudWatchTestRequests.call(baseUri, SCOPE, json, "PutMetricAlarm", body); + + refused.then().statusCode(400); + assertEquals(code, json ? refused.jsonPath().getString("__type") + : refused.xmlPath().getString("ErrorResponse.Error.Code")); + assertEquals(COMBINATION, json ? refused.jsonPath().getString("message") + : refused.xmlPath().getString("ErrorResponse.Error.Message")); + assertEquals(0, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().size()); + } + + @Test + void theSdkRaisesTheTypedExceptionForTheIntervalOnAMetricNameAlarm() { + InvalidParameterCombinationException refused = assertThrows(InvalidParameterCombinationException.class, + () -> cloudWatch.putMetricAlarm(r -> r.alarmName("sdk-interval-" + suffix).metricName("MyMetric") + .evaluationInterval(60))); + + assertEquals(COMBINATION, refused.awsErrorDetails().errorMessage()); + } + + @Test + void anAlarmWithEvaluationCriteriaTakesAnIntervalAndDoesNotReturnIt() { + String name = "sdk-interval-criteria-" + suffix; + cleanup.register(() -> cloudWatch.deleteAlarms(r -> r.alarmNames(name))); + + cloudWatch.putMetricAlarm(r -> r.alarmName(name).evaluationInterval(60) + .evaluationCriteria(c -> c.promQLCriteria(p -> p.query("up")))); + + MetricAlarm stored = cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().getFirst(); + assertEquals(name, stored.alarmName()); + assertNull(stored.evaluationInterval()); + } + + @ParameterizedTest + @ValueSource(strings = {"60", "99999999999"}) + void aStackWhoseAlarmSetsTheIntervalRollsBackWithTheReason(String interval) { + String name = "stack-interval-" + suffix; + String stack = "interval-create-" + suffix; + String reason = "60".equals(interval) ? COMBINATION : "Value '" + interval + "' at 'evaluationInterval' " + + "failed to satisfy constraint: Member must have value less than or equal to 3600"; + + CfnStackWaits.StackState state = deploy(stack, alarmTemplate(name, 1, interval)); + + assertEquals("ROLLBACK_COMPLETE", state.status()); + assertEquals(0, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().size()); + assertTrue(cfn.describeStackEvents(r -> r.stackName(stack)).stackEvents().stream() + .anyMatch(e -> "CREATE_FAILED".equals(e.resourceStatusAsString()) + && e.resourceStatusReason().contains(reason)), "no CREATE_FAILED event with: " + reason); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "[{\"Id\":\"e1\",\"Expression\":\"1\"}]|ROLLBACK_COMPLETE", + "{\"Fn::If\":[\"On\",[{\"Id\":\"e1\",\"Expression\":\"1\"}],{\"Ref\":\"AWS::NoValue\"}]}|ROLLBACK_COMPLETE", + "{\"Fn::If\":[\"Off\",[{\"Id\":\"e1\",\"Expression\":\"1\"}],{\"Ref\":\"AWS::NoValue\"}]}|CREATE_COMPLETE"}) + void anIntervalWithMetricsRollsTheStackBackUnlessTheMetricsResolveToNoValue(String metrics, String expected) { + String name = "stack-metrics-interval-" + suffix; + String stack = "metrics-interval-" + suffix; + boolean refused = "ROLLBACK_COMPLETE".equals(expected); + + CfnStackWaits.StackState state = deploy(stack, """ + {"Conditions": {"On": {"Fn::Equals": ["a", "a"]}, "Off": {"Fn::Equals": ["a", "b"]}}, + "Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": { + "AlarmName": "%s", "EvaluationPeriods": 1, "Threshold": 1, "EvaluationInterval": 60, + "ComparisonOperator": "GreaterThanOrEqualToThreshold", + "Metrics": %s}}}}""".formatted(name, metrics)); + + assertEquals(expected, state.status(), state.reason()); + assertEquals(refused ? 0 : 1, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().size()); + if (refused) { + assertTrue(CfnStackWaits.failedResourceReason(stack).contains(COMBINATION)); + } + } + + @Test + void anUpdateThatAddsTheIntervalRollsBackAndLeavesTheAlarmAsItWas() { + String name = "stack-interval-update-" + suffix; + String stack = "interval-update-" + suffix; + CfnStackWaits.StackState created = deploy(stack, alarmTemplate(name, 1, null)); + assertEquals("CREATE_COMPLETE", created.status(), created.reason()); + + CfnStackWaits.updateStack(cfn, stack, alarmTemplate(name, 5, "60"), "UPDATE_ROLLBACK_COMPLETE"); + + assertTrue(CfnStackWaits.failedResourceReason(stack).contains(COMBINATION)); + assertEquals(1.0, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().getFirst().threshold()); + } + + private CfnStackWaits.StackState deploy(String stack, String template) { + cleanup.register(() -> cfn.deleteStack(r -> r.stackName(stack))); + cfn.createStack(r -> r.stackName(stack).templateBody(template)); + return CfnStackWaits.awaitTerminal(stack); + } + + private static String alarmTemplate(String name, int threshold, String interval) { + return """ + {"Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": { + "AlarmName": "%s", "Namespace": "MyApp", "MetricName": "MyMetric", + "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1, "Threshold": %d, + "ComparisonOperator": "GreaterThanOrEqualToThreshold"%s}}}}""".formatted(name, threshold, + interval == null ? "" : ", \"EvaluationInterval\": " + interval); + } +} diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 299ad8d68e..b6bf7d440e 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -144,10 +144,8 @@ AWS::CloudTrail::Trail Tags accepted and ignored AWS::CloudWatch::Alarm ActionConfiguration accepted and ignored AWS::CloudWatch::Alarm EvaluateLowSampleCountPercentile accepted and ignored AWS::CloudWatch::Alarm EvaluationCriteria accepted and ignored -AWS::CloudWatch::Alarm EvaluationInterval accepted and ignored AWS::CloudWatch::Alarm EvaluationWindow accepted and ignored AWS::CloudWatch::Alarm ExtendedStatistic accepted and ignored -AWS::CloudWatch::Alarm Metrics accepted and ignored AWS::CloudWatch::Alarm Tags accepted and ignored AWS::CloudWatch::Alarm ThresholdMetricId accepted and ignored AWS::CloudWatch::Alarm WarmUpConfiguration accepted and ignored