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
This commit is contained in:
glorfindel33 authored and GitHub committed 2026-11-18 17:50:31 -04:00
1 parent c4d7499ca2
commit bbc80c9b51
13 files changed
+527 -17

No files matched your search

@@ -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<String> target) {
if (props != null && props.has(field) && props.get(field).isArray()) {
for (JsonNode action : props.get(field)) {
@@ -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
@@ -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();
@@ -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<String, String> 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<String, String> 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;
@@ -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<String> 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);
}