fix(autoscaling): match DescribeTags input validation (#5894)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-17 16:39:21 -04:00
1 parent ae7e6d1240
commit 4e47507a7b
4 files changed
+185 -28

No files matched your search

@@ -0,0 +1,72 @@
"""DescribeTags validation observed on AWS, 2026-10-17."""
import uuid
from contextlib import ExitStack, closing
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
def test_describe_tags_filter_validation(ec2_client, aws_config, client_config):
name = "tag-validation-" + uuid.uuid4().hex[:12]
with closing(boto3.client("autoscaling", config=client_config, **aws_config)) as autoscaling:
with ExitStack() as cleanup:
image = ec2_client.register_image(
Name=name, Architecture="x86_64", RootDeviceName="/dev/sda1"
)["ImageId"]
cleanup.callback(ec2_client.deregister_image, ImageId=image)
template = ec2_client.create_launch_template(
LaunchTemplateName=name,
LaunchTemplateData={"ImageId": image, "InstanceType": "t3.micro"},
)["LaunchTemplate"]["LaunchTemplateId"]
cleanup.callback(ec2_client.delete_launch_template, LaunchTemplateId=template)
autoscaling.create_auto_scaling_group(
AutoScalingGroupName=name, MinSize=0, MaxSize=0, DesiredCapacity=0,
AvailabilityZones=[aws_config["region_name"] + "a"],
LaunchTemplate={"LaunchTemplateId": template},
Tags=[
{"Key": "propagated", "Value": "Yes", "PropagateAtLaunch": True},
{"Key": "not-propagated", "Value": "No", "PropagateAtLaunch": False},
],
)
cleanup.callback(autoscaling.delete_auto_scaling_group,
AutoScalingGroupName=name, ForceDelete=True)
group_filter = {"Name": "auto-scaling-group", "Values": [name]}
for filter_name, values, expected in [
("KEY", ["propagated"], ["propagated"]),
("\u212Aey", ["propagated"], ["propagated"]),
("key", ["PROPAGATED"], []),
("propagate-at-launch", ["TrUe"], ["propagated"]),
("propagate-at-launch", [" false "], ["not-propagated"]),
("propagate-at-launch", ["\tTRUE\n"], ["propagated"]),
("propagate-at-launch", [], ["not-propagated", "propagated"]),
]:
tags = autoscaling.describe_tags(Filters=[
group_filter, {"Name": filter_name, "Values": values},
])["Tags"]
assert sorted(tag["Key"] for tag in tags) == expected
for filter_value in [
{"Name": "key"}, {"Values": ["propagated"]},
{"Name": "unknown", "Values": []},
{"Name": "propagate-at-launch", "Values": ["1"]},
{"Name": "propagate-at-launch", "Values": ["tru e"]},
]:
with pytest.raises(ClientError) as failure:
autoscaling.describe_tags(Filters=[group_filter, filter_value])
assert failure.value.response["Error"]["Code"] == "ValidationError"
def test_describe_tags_pagination_validation(aws_config):
config = Config(parameter_validation=False, retries={"max_attempts": 1})
with closing(boto3.client("autoscaling", config=config, **aws_config)) as autoscaling:
for value in [0, -1, 101, "abc", "", "1.5"]:
with pytest.raises(ClientError) as failure:
autoscaling.describe_tags(MaxRecords=value)
expected = "ValidationError" if isinstance(value, int) else "MalformedInput"
assert failure.value.response["Error"]["Code"] == expected
for token in ["invalid", ""]:
with pytest.raises(ClientError) as failure:
autoscaling.describe_tags(NextToken=token)
assert failure.value.response["Error"]["Code"] == "ValidationError"
@@ -496,17 +496,20 @@ public class AutoScalingQueryHandler {
private Response handleDescribeTags(MultivaluedMap<String, String> p, String region) {
List<Map.Entry<String, List<String>>> filters = new ArrayList<>();
for (int i = 1; ; i++) {
String name = p.getFirst("Filters.member." + i + ".Name");
if (name == null) { break; }
filters.add(Map.entry(name, memberList(p, "Filters.member." + i + ".Values")));
String prefix = "Filters.member." + i;
String name = p.getFirst(prefix + ".Name");
boolean hasValues = p.containsKey(prefix + ".Values") || p.containsKey(prefix + ".Values.member.1");
if (name == null && !hasValues) { break; }
filters.add(new AbstractMap.SimpleImmutableEntry<>(name,
hasValues ? memberList(p, prefix + ".Values") : null));
}
String maxRecords = p.getFirst("MaxRecords");
Integer limit = null;
if (maxRecords != null && !maxRecords.isBlank()) {
if (maxRecords != null) {
try {
limit = Integer.parseInt(maxRecords);
} catch (NumberFormatException e) {
throw new AwsException("ValidationError", "MaxRecords '" + maxRecords + "' is not a valid integer.", 400);
throw new AwsException("MalformedInput", "MaxRecords '" + maxRecords + "' is not a valid integer.", 400);
}
}
PaginatedResult<AutoScalingService.TagDescription> page = service.describeTags(region, filters,
@@ -585,31 +585,49 @@ public class AutoScalingService {
// AWS: values inside one filter are ORed, separate filters are ANDed; only these four
// filter names exist. Ordered by (group, key); NextToken is the last pair returned, so tags
// added or removed between pages neither skip nor repeat an entry. Values match exactly
// (the Filter model says they are case-sensitive).
// added or removed between pages neither skip nor repeat an entry.
public PaginatedResult<TagDescription> describeTags(String region, List<Map.Entry<String, List<String>>> filters,
Integer maxRecords, String nextToken) {
List<Map.Entry<String, List<String>>> normalizedFilters = new ArrayList<>();
for (Map.Entry<String, List<String>> filter : filters) {
if (!Set.of("auto-scaling-group", "key", "value", "propagate-at-launch").contains(filter.getKey())) {
String name = filter.getKey() == null ? "" : filter.getKey().toLowerCase(Locale.ROOT);
if (!Set.of("auto-scaling-group", "key", "value", "propagate-at-launch").contains(name)) {
throw new AwsException("ValidationError", "Filter name '" + filter.getKey() + "' is not valid.", 400);
}
if (filter.getValue() == null) {
throw new AwsException("ValidationError", "The Values attribute and one or more filter values are required.", 400);
}
List<String> values = filter.getValue();
if ("propagate-at-launch".equals(name)) {
values = values.stream().map(value -> value.trim().toLowerCase(Locale.ROOT)).toList();
if (values.stream().anyMatch(value -> !Set.of("true", "false").contains(value))) {
throw new AwsException("ValidationError", "The propagate-at-launch filter requires true or false.", 400);
}
}
normalizedFilters.add(Map.entry(name, values));
}
int limit = maxRecords != null ? Math.min(Math.max(maxRecords, 1), 100) : 50;
if (maxRecords != null && (maxRecords < 1 || maxRecords > 100)) {
throw new AwsException("ValidationError", "MaxRecords must be between 1 and 100.", 400);
}
if (nextToken != null && nextToken.isBlank()) {
throw new AwsException("ValidationError", "The NextToken value is not valid.", 400);
}
int limit = maxRecords != null ? maxRecords : 50;
List<TagDescription> matches = groups.values().stream()
.filter(Objects::nonNull) // group deleted between key snapshot and value read
.filter(g -> region.equals(g.getRegion()))
.flatMap(g -> g.getTags().entrySet().stream()
.map(t -> new TagDescription(g.getAutoScalingGroupName(), t.getKey(), t.getValue(),
g.getTagPropagateAtLaunch().getOrDefault(t.getKey(), false))))
.filter(t -> matchesFilter(filters, "auto-scaling-group", t.resourceId())
&& matchesFilter(filters, "key", t.key())
&& matchesFilter(filters, "value", t.value())
&& matchesFilter(filters, "propagate-at-launch", String.valueOf(t.propagateAtLaunch())))
.filter(t -> matchesFilter(normalizedFilters, "auto-scaling-group", t.resourceId())
&& matchesFilter(normalizedFilters, "key", t.key())
&& matchesFilter(normalizedFilters, "value", t.value())
&& matchesFilter(normalizedFilters, "propagate-at-launch", String.valueOf(t.propagateAtLaunch())))
.collect(Collectors.toList());
// "\0" sorts below every other character, so the cursor orders as the (group, key) pair.
return Pagination.paginate(matches,
t -> t.resourceId() + "\0" + t.key(), limit, nextToken, "autoscaling-tags",
token -> new AwsException("InvalidNextToken", "The NextToken value is not valid.", 400));
token -> new AwsException("ValidationError", "The NextToken value is not valid.", 400));
}
// Every filter of this name must match (a repeated name is a second filter, ANDed).
@@ -5,6 +5,8 @@ import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@@ -158,13 +160,14 @@ class AutoScalingDescribeTagsIntegrationTest {
.body(containsString("ValidationError"));
}
@Test
void nonNumericMaxRecordsIsAValidationError() {
@ParameterizedTest
@ValueSource(strings = {"abc", "", "1.5"})
void nonNumericMaxRecordsIsMalformedInput(String count) {
describe()
.formParam("MaxRecords", "abc")
.formParam("MaxRecords", count)
.when().post("/")
.then().statusCode(400)
.body(containsString("ValidationError"));
.body(containsString("MalformedInput"));
}
// Like every other member list in this handler, filters are read up to the first missing index.
@@ -181,18 +184,78 @@ class AutoScalingDescribeTagsIntegrationTest {
assertEquals(List.of("AsgId"), xml.getList(ROOT + ".Key"));
}
// Filter values are case-sensitive (AWS Filter model), propagate-at-launch included.
@Test
void propagateAtLaunchFilterIsCaseSensitive() {
@ParameterizedTest
@ValueSource(strings = {"True", " TRUE ", "\tTrUe\n"})
void propagateAtLaunchFilterNormalizesBooleanValues(String value) {
XmlPath xml = describe()
.formParam("Filters.member.1.Name", "auto-scaling-group")
.formParam("Filters.member.1.Values.member.1", GROUP_A)
.formParam("Filters.member.2.Name", "propagate-at-launch")
.formParam("Filters.member.2.Values.member.1", "True")
.formParam("Filters.member.2.Values.member.1", value)
.when().post("/")
.then().statusCode(200).extract().xmlPath();
assertEquals(List.of(), xml.getList(ROOT + ".Key"));
assertEquals(List.of("AsgId"), xml.getList(ROOT + ".Key"));
}
@ParameterizedTest
@ValueSource(strings = {"KEY", "\u212Aey"})
void filterNamesAreCaseInsensitive(String name) {
XmlPath xml = describe()
.formParam("Filters.member.1.Name", "auto-scaling-group")
.formParam("Filters.member.1.Values.member.1", GROUP_A)
.formParam("Filters.member.2.Name", name)
.formParam("Filters.member.2.Values.member.1", "AsgId")
.when().post("/")
.then().statusCode(200).extract().xmlPath();
assertEquals(List.of("AsgId"), xml.getList(ROOT + ".Key"));
}
@ParameterizedTest
@ValueSource(strings = {"1", "tru e", ""})
void invalidBooleanFiltersAreRejected(String value) {
describe().formParam("Filters.member.1.Name", "propagate-at-launch")
.formParam("Filters.member.1.Values.member.1", value)
.when().post("/")
.then().statusCode(400).body(containsString("ValidationError"));
}
@Test
void missingValuesAreRejectedButAnEmptyListIsIgnored() {
describe().formParam("Filters.member.1.Name", "key")
.when().post("/")
.then().statusCode(400).body(containsString("ValidationError"));
XmlPath xml = describe()
.formParam("Filters.member.1.Name", "auto-scaling-group")
.formParam("Filters.member.1.Values.member.1", GROUP_A)
.formParam("Filters.member.2.Name", "key")
.formParam("Filters.member.2.Values", "")
.when().post("/")
.then().statusCode(200).extract().xmlPath();
assertEquals(List.of("AsgId", "team"), xml.getList(ROOT + ".Key"));
}
@Test
void missingFilterNameIsRejected() {
describe().formParam("Filters.member.1.Values.member.1", "AsgId")
.when().post("/")
.then().statusCode(400).body(containsString("ValidationError"));
}
@ParameterizedTest
@ValueSource(ints = {-1, 0, 101})
void outOfRangeMaxRecordsIsRejected(int count) {
describe().formParam("MaxRecords", count)
.when().post("/")
.then().statusCode(400).body(containsString("ValidationError"));
}
@ParameterizedTest
@ValueSource(strings = {"invalid", ""})
void invalidNextTokenIsAValidationError(String token) {
describe().formParam("NextToken", token)
.when().post("/")
.then().statusCode(400).body(containsString("ValidationError"));
}
// A tag deleted from an already-returned page must not shift the next page past an unread tag.
@@ -254,18 +317,18 @@ class AutoScalingDescribeTagsIntegrationTest {
}
@Test
void garbageNextTokenIsInvalidNextToken() {
void garbageNextTokenIsAValidationError() {
describe()
.formParam("NextToken", "!!not-a-token!!")
.when().post("/")
.then().statusCode(400)
.body(containsString("InvalidNextToken"));
.body(containsString("ValidationError"));
}
// A token that decodes to a plausible (group, key) but lacks this list's namespace was not
// minted here.
@Test
void tokenWithoutTheNamespaceIsInvalidNextToken() {
void tokenWithoutTheNamespaceIsAValidationError() {
assertInvalidNextToken(Base64.getUrlEncoder().encodeToString(
(GROUP_A + "\0AsgId").getBytes(StandardCharsets.UTF_8)));
}
@@ -275,11 +338,12 @@ class AutoScalingDescribeTagsIntegrationTest {
.formParam("NextToken", token)
.when().post("/")
.then().statusCode(400)
.body(containsString("InvalidNextToken"));
.body(containsString("ValidationError"));
}
private static RequestSpecification describe() {
return given().formParam("Action", "DescribeTags").header("Authorization", AUTH);
return given().contentType("application/x-www-form-urlencoded; charset=UTF-8")
.formParam("Action", "DescribeTags").header("Authorization", AUTH);
}
private static void createGroup(String name, String key, String value, boolean propagate) {