feat(ec2): page and filter DescribeTags as AWS does (#6109)

* feat(ec2): page and filter DescribeTags as AWS does

DescribeTags ignored MaxResults and NextToken, so SDK paginators got a
single page, and matched filter values exactly: tag:<key> was dropped,
the * and ? wildcards matched literally, and a filter name given twice
kept only the last one.

It now pages with MaxResults (5 to 1000, InvalidMaxResults otherwise)
and NextToken, takes tag:<key> as the documented alternate spelling of
a key filter plus a value filter, honours wildcards, ORs the values of
one filter and ANDs separate filters. Results are ordered by resource id
so a page boundary stays put while no tags change.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(ec2): bound filter wildcards and refuse every out-of-range MaxResults

EC2 filter wildcards were translated to a regex, so a caller-supplied
pattern of many stars backtracked for seconds against a long value and
`*` skipped line terminators. They now use the two-pointer glob IAM and
S3 already share, which every EC2 Describe filter goes through.

DescribeTags treated MaxResults=0 and negative values as unpaged; any
value sent outside 5 to 1000 now answers InvalidMaxResults, and only a
missing MaxResults is unpaged. A NextToken whose offset is at or past the
end returns an empty last page instead of overflowing into a token that
fails on the next call. The compat case moves to its own @Order.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-20 23:42:14 -04:00
1 parent 3baa38a346
commit e5591dda32
6 files changed
+300 -77

No files matched your search

@@ -860,6 +860,40 @@ class Ec2Tests {
.build());
}
@Test
@Order(52)
@DisplayName("DescribeTags - paginator pages with MaxResults and honours tag:<key>")
void describeTagsPaginatesAndFiltersByTagKey() {
String pagedVpcId = ec2.createVpc(CreateVpcRequest.builder().cidrBlock("10.98.0.0/16").build())
.vpc().vpcId();
try {
List<Tag> tags = new ArrayList<>();
for (int i = 1; i <= 12; i++) {
tags.add(Tag.builder().key(String.format("Page%02d", i)).value(i == 1 ? "TeamA" : "v").build());
}
ec2.createTags(CreateTagsRequest.builder().resources(pagedVpcId).tags(tags).build());
Filter byId = Filter.builder().name("resource-id").values(pagedVpcId).build();
List<DescribeTagsResponse> pages = ec2.describeTagsPaginator(DescribeTagsRequest.builder()
.filters(byId).maxResults(5).build()).stream().toList();
assertThat(pages).extracting(page -> page.tags().size()).containsExactly(5, 5, 2);
assertThat(pages.get(2).nextToken()).isNull();
assertThat(pages.stream().flatMap(page -> page.tags().stream()).map(TagDescription::key).distinct())
.hasSize(12);
assertThat(ec2.describeTags(DescribeTagsRequest.builder()
.filters(byId, Filter.builder().name("tag:Page01").values("Team?").build())
.build()).tags())
.singleElement()
.satisfies(tag -> {
assertThat(tag.key()).isEqualTo("Page01");
assertThat(tag.resourceType()).isEqualTo(ResourceType.VPC);
});
} finally {
ec2.deleteVpc(DeleteVpcRequest.builder().vpcId(pagedVpcId).build());
}
}
@Test
@Order(38)
@DisplayName("DescribeInstances - tags reflected on instance")
+8
View File
@@ -390,6 +390,14 @@ not model is tagged as given. A resource takes at most 50 user tags (`TagLimitEx
the `aws:` prefix do not count), keys up to 128 and values up to 256 Unicode characters
(`InvalidParameterValue`). A request that fails changes no resource's tags.
`DescribeTags` takes the `key`, `value`, `resource-id`, `resource-type` and `tag:<key>` filters.
`tag:Owner` with the value `TeamA` is the same as a `key` filter of `Owner` and a `value` filter
of `TeamA`, so it lists that one tag. Filter values take the `*` and `?` wildcards, the values of
one filter are ORed, and separate filters, including two with the same name, are ANDed. An
unknown filter name is ignored. `MaxResults` (5 to 1000, `InvalidMaxResults` otherwise) pages the
result with `NextToken`, which is absent on the last page; the AWS SDK paginators work as is.
Results are ordered by resource id, so pages stay stable while no tags change.
Public tag mutations reject keys beginning with `aws:` regardless of ASCII case.
An empty `DeleteTags` tag list removes user tags and preserves AWS-managed tags.
CloudFormation tag updates and rollbacks likewise leave AWS-managed tags intact.
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SshPublicKeys;
import io.github.hectorvent.floci.core.common.XmlBuilder;
@@ -3811,13 +3812,18 @@ public class Ec2QueryHandler {
}
private Response handleDescribeTags(MultivaluedMap<String, String> p, String region) {
Map<String, List<String>> filters = getFilters(p);
List<Map<String, String>> tagItems = service.describeTags(region, filters);
String maxResults = p.getFirst("MaxResults");
PaginatedResult<Map<String, String>> result = service.describeTags(region, getFiltersList(p),
maxResults == null || maxResults.isEmpty() ? null : parseIntParam(p, "MaxResults", 0),
p.getFirst("NextToken"));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTagsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("tagSet");
for (Map<String, String> item : tagItems) {
.elem("requestId", UUID.randomUUID().toString());
if (result.nextToken() != null) {
xml.elem("nextToken", result.nextToken());
}
xml.start("tagSet");
for (Map<String, String> item : result.items()) {
xml.start("item")
.elem("resourceId", item.get("resourceId"))
.elem("resourceType", item.get("resourceType"))
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.Resettable;
@@ -97,6 +98,7 @@ import io.github.hectorvent.floci.services.ec2.model.VpcPeeringConnectionVpcInfo
import io.github.hectorvent.floci.services.ec2.net.Cidr4;
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import jakarta.annotation.PostConstruct;
@@ -128,6 +130,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
@@ -8909,23 +8912,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* AWS filter values take two wildcards, {@code *} for any run of characters and {@code ?} for
* exactly one. Only {@code *} was honoured here, so a {@code ?} was matched literally and a
* pattern like {@code ubuntu-?} found nothing, while {@link #wildcardToRegex} a few hundred
* lines down already treated both.
* lines down already treated both. The match is a two-pointer glob rather than a regex: a
* caller-supplied pattern of many stars made the regex backtrack for seconds, and its dot
* skipped line terminators that a tag value may hold.
*/
private boolean wildcardMatches(String pattern, String value) {
if (pattern == null) {
return false;
}
if (!pattern.contains("*") && !pattern.contains("?")) {
return pattern.equals(value);
}
String regex = pattern.chars()
.mapToObj(ch -> switch (ch) {
case '*' -> ".*";
case '?' -> ".";
default -> java.util.regex.Pattern.quote(String.valueOf((char) ch));
})
.collect(Collectors.joining());
return value.matches(regex);
return IamPolicyEvaluator.caseSensitiveGlobMatches(pattern, value);
}
// ─── Tags ──────────────────────────────────────────────────────────────────
@@ -9310,74 +9302,87 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return List.copyOf(tagsOf(region, resourceId).orElse(List.of()));
}
/** Every tag in {@code region} that matches {@code filters}, unpaged. */
public List<Map<String, String>> describeTags(String region, Map<String, List<String>> filters) {
ensureDefaultResources(region);
List<String> filterResourceIds = filters != null ? filters.get("resource-id") : null;
List<String> filterResourceTypes = filters != null ? filters.get("resource-type") : null;
List<String> filterKeys = filters != null ? filters.get("key") : null;
List<String> filterValues = filters != null ? filters.get("value") : null;
List<Map.Entry<String, List<String>>> filterList = filters != null
? new ArrayList<>(filters.entrySet())
: List.of();
return describeTags(region, filterList, null, null).items();
}
List<Map<String, String>> result = new ArrayList<>();
Set<String> processedResourceIds = new LinkedHashSet<>();
/**
* DescribeTags. Filters are ANDed and the values of one filter ORed, each value taking the
* {@code *} and {@code ?} wildcards. {@code tag:<key>} is the documented alternate spelling of
* a {@code key} filter plus a {@code value} filter. Tags are listed by resource id, so a page
* boundary stays put while nothing is written; a null {@code maxResults} means unpaged, and any
* value sent outside 5 to 1000, zero and negatives included, is refused.
*/
public PaginatedResult<Map<String, String>> describeTags(String region,
List<Map.Entry<String, List<String>>> filters,
Integer maxResults, String nextToken) {
if (maxResults != null && (maxResults < 5 || maxResults > 1000)) {
throw new AwsException("InvalidMaxResults",
"Value (" + maxResults + ") for parameter MaxResults is invalid. "
+ "Expecting a value between 5 and 1000.", 400);
}
int offset = decodeToken(nextToken);
ensureDefaultResources(region);
Map<String, List<Tag>> tagsByResource = new TreeMap<>();
String regionPrefix = region + "::";
for (String tagKey : new ArrayList<>(tags.keys())) {
if (!tagKey.startsWith(regionPrefix)) {
continue;
}
String resourceId = tagKey.substring(regionPrefix.length());
processedResourceIds.add(resourceId);
String resourceType = inferResourceType(resourceId);
if (filterResourceIds != null && !filterResourceIds.contains(resourceId)) {
continue;
}
if (filterResourceTypes != null && !filterResourceTypes.contains(resourceType)) {
continue;
}
for (Tag tag : tagsOf(region, resourceId).orElse(List.of())) {
if (filterKeys != null && !filterKeys.contains(tag.getKey())) {
continue;
}
if (filterValues != null && !filterValues.contains(tag.getValue())) {
continue;
}
Map<String, String> item = new LinkedHashMap<>();
item.put("resourceId", resourceId);
item.put("resourceType", resourceType);
item.put("key", tag.getKey());
item.put("value", tag.getValue());
result.add(item);
if (tagKey.startsWith(regionPrefix)) {
String resourceId = tagKey.substring(regionPrefix.length());
tagsByResource.put(resourceId, tagsOf(region, resourceId).orElse(List.of()));
}
}
for (Instance ext : listExternalInstances(callerAccountId(), region)) {
String resourceId = ext.getInstanceId();
if (processedResourceIds.contains(resourceId)) {
continue;
}
tagsByResource.putIfAbsent(ext.getInstanceId(), ext.getTags() != null ? ext.getTags() : List.of());
}
List<Map<String, String>> result = new ArrayList<>();
for (Map.Entry<String, List<Tag>> resource : tagsByResource.entrySet()) {
String resourceId = resource.getKey();
String resourceType = inferResourceType(resourceId);
if (filterResourceIds != null && !filterResourceIds.contains(resourceId)) {
continue;
}
if (filterResourceTypes != null && !filterResourceTypes.contains(resourceType)) {
continue;
}
for (Tag tag : ext.getTags() != null ? ext.getTags() : List.<Tag>of()) {
if (filterKeys != null && !filterKeys.contains(tag.getKey())) {
continue;
for (Tag tag : resource.getValue()) {
if (filters.stream().allMatch(filter -> matchesTagFilter(filter, resourceId, resourceType, tag))) {
Map<String, String> item = new LinkedHashMap<>();
item.put("resourceId", resourceId);
item.put("resourceType", resourceType);
item.put("key", tag.getKey());
item.put("value", tag.getValue());
result.add(item);
}
if (filterValues != null && !filterValues.contains(tag.getValue())) {
continue;
}
Map<String, String> item = new LinkedHashMap<>();
item.put("resourceId", resourceId);
item.put("resourceType", resourceType);
item.put("key", tag.getKey());
item.put("value", tag.getValue());
result.add(item);
}
}
return result;
if (maxResults == null) {
return new PaginatedResult<>(result, null);
}
int total = result.size();
if (offset >= total) {
return new PaginatedResult<>(List.of(), null);
}
int toIndex = offset + Math.min(maxResults, total - offset);
return new PaginatedResult<>(new ArrayList<>(result.subList(offset, toIndex)),
toIndex < total ? encodeToken(toIndex) : null);
}
private boolean matchesTagFilter(Map.Entry<String, List<String>> filter, String resourceId,
String resourceType, Tag tag) {
String name = filter.getKey();
List<String> values = filter.getValue();
String value = tag.getValue() != null ? tag.getValue() : "";
if (name.startsWith("tag:")) {
return name.substring("tag:".length()).equals(tag.getKey()) && matchesFilterValue(values, value);
}
return switch (name) {
case "key" -> matchesFilterValue(values, tag.getKey());
case "value" -> matchesFilterValue(values, value);
case "resource-id" -> matchesFilterValue(values, resourceId);
case "resource-type" -> matchesFilterValue(values, resourceType);
default -> true;
};
}
private String inferResourceType(String resourceId) {
@@ -0,0 +1,135 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** DescribeTags pages with MaxResults and NextToken and honours every documented filter. */
@QuarkusTest
class Ec2DescribeTagsFilterIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private RequestSpecification ec2(String action, String... formParams) {
RequestSpecification req = given().formParam("Action", action).header("Authorization", AUTH);
for (int i = 0; i < formParams.length; i += 2) {
req = req.formParam(formParams[i], formParams[i + 1]);
}
return req;
}
private XmlPath ok(String action, String... formParams) {
return ec2(action, formParams).when().post("/").then().statusCode(200).extract().xmlPath();
}
private String createVpc(String cidr) {
return ok("CreateVpc", "CidrBlock", cidr).getString("CreateVpcResponse.vpc.vpcId");
}
@Test
void maxResultsPagesThroughEveryTagUntilTheTokenIsGone() {
String vpcId = createVpc("10.95.0.0/16");
try {
List<String> create = new ArrayList<>(List.of("ResourceId.1", vpcId));
for (int i = 1; i <= 12; i++) {
create.addAll(List.of("Tag." + i + ".Key", String.format("Page%02d", i), "Tag." + i + ".Value", "v"));
}
ok("CreateTags", create.toArray(String[]::new));
List<String> keys = new ArrayList<>();
List<Integer> pageSizes = new ArrayList<>();
String token = null;
do {
List<String> params = new ArrayList<>(List.of(
"Filter.1.Name", "resource-id", "Filter.1.Value.1", vpcId, "MaxResults", "5"));
if (token != null) {
params.addAll(List.of("NextToken", token));
}
XmlPath page = ok("DescribeTags", params.toArray(String[]::new));
List<String> pageKeys = page.getList("DescribeTagsResponse.tagSet.item.key", String.class);
keys.addAll(pageKeys);
pageSizes.add(pageKeys.size());
token = page.getString("DescribeTagsResponse.nextToken");
token = token == null || token.isEmpty() ? null : token;
} while (token != null);
assertEquals(List.of(5, 5, 2), pageSizes);
assertEquals(12, keys.stream().distinct().count());
String unpaged = ec2("DescribeTags", "Filter.1.Name", "resource-id", "Filter.1.Value.1", vpcId)
.when().post("/").then().statusCode(200).extract().asString();
assertEquals(12, new XmlPath(unpaged).getList("DescribeTagsResponse.tagSet.item.key").size());
assertFalse(unpaged.contains("<nextToken>"), "an unpaged response carries no nextToken");
} finally {
ok("DeleteVpc", "VpcId", vpcId);
}
}
@Test
void maxResultsOutsideFiveToAThousandIsRejected() {
for (String maxResults : List.of("0", "-1", "4", "1001")) {
ec2("DescribeTags", "MaxResults", maxResults).when().post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidMaxResults"));
}
}
@Test
void filtersTakeTagKeyWildcardsAndSeveralValues() {
String a = createVpc("10.96.0.0/16");
String b = createVpc("10.97.0.0/16");
try {
ok("CreateTags", "ResourceId.1", a, "Tag.1.Key", "Owner", "Tag.1.Value", "TeamA",
"Tag.2.Key", "Role", "Tag.2.Value", "webserver");
ok("CreateTags", "ResourceId.1", b, "Tag.1.Key", "Owner", "Tag.1.Value", "TeamB",
"Tag.2.Key", "Role", "Tag.2.Value", "Webserver");
assertEquals(sorted(a + " Owner=TeamA"), listed(a, b,
"Filter.2.Name", "tag:Owner", "Filter.2.Value.1", "TeamA"));
assertEquals(sorted(a + " Role=webserver", b + " Role=Webserver"), listed(a, b,
"Filter.2.Name", "value", "Filter.2.Value.1", "?ebserver"));
assertEquals(sorted(a + " Owner=TeamA", b + " Owner=TeamB"), listed(a, b,
"Filter.2.Name", "key", "Filter.2.Value.1", "Ow*"));
assertEquals(sorted(a + " Owner=TeamA", b + " Owner=TeamB"), listed(a, b,
"Filter.2.Name", "value", "Filter.2.Value.1", "TeamA", "Filter.2.Value.2", "TeamB"));
assertTrue(listed(a, b, "Filter.2.Name", "resource-id", "Filter.2.Value.1", a,
"Filter.3.Name", "resource-id", "Filter.3.Value.1", b).isEmpty());
} finally {
ok("DeleteVpc", "VpcId", a);
ok("DeleteVpc", "VpcId", b);
}
}
/** The tags of {@code a} and {@code b} that also match {@code extraFilters}, as sorted "id key=value". */
private List<String> listed(String a, String b, String... extraFilters) {
List<String> params = new ArrayList<>(List.of(
"Filter.1.Name", "resource-id", "Filter.1.Value.1", a, "Filter.1.Value.2", b));
params.addAll(List.of(extraFilters));
XmlPath xml = ok("DescribeTags", params.toArray(String[]::new));
List<String> ids = xml.getList("DescribeTagsResponse.tagSet.item.resourceId", String.class);
List<String> keys = xml.getList("DescribeTagsResponse.tagSet.item.key", String.class);
List<String> values = xml.getList("DescribeTagsResponse.tagSet.item.value", String.class);
List<String> result = new ArrayList<>();
for (int i = 0; i < ids.size(); i++) {
result.add(ids.get(i) + " " + keys.get(i) + "=" + values.get(i));
}
Collections.sort(result);
return result;
}
private static List<String> sorted(String... items) {
List<String> result = new ArrayList<>(List.of(items));
Collections.sort(result);
return result;
}
}
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ListNetworksCmd;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
@@ -73,9 +74,11 @@ import org.mockito.InOrder;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPrivateCrtKey;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -103,6 +106,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -685,6 +689,37 @@ class Ec2ServiceTest {
assertEquals("east", service.resourceTags("us-east-1", east).getFirst().getValue());
}
@Test
void describeTagsWildcardsMatchLineTerminatorsAndStayLinear() {
Ec2Service service = tagTestService(new InMemoryStorageFactory());
String vpcId = service.createVpc("us-east-1", "10.82.0.0/16", false).getVpcId();
service.createTags("us-east-1", List.of(vpcId),
List.of(new Tag("Note", "first\nsecond"), new Tag("Long", "a".repeat(256))));
assertEquals(2, service.describeTags("us-east-1", Map.of("resource-id", List.of(vpcId),
"value", List.of("*"))).size());
assertEquals(1, service.describeTags("us-east-1", Map.of("resource-id", List.of(vpcId),
"value", List.of("first?second"))).size());
String manyStars = "*a".repeat(40) + "*b";
assertTimeoutPreemptively(Duration.ofSeconds(2), () -> assertTrue(service.describeTags("us-east-1",
Map.of("resource-id", List.of(vpcId), "value", List.of(manyStars))).isEmpty()));
}
@Test
void describeTagsRefusesEverySentMaxResultsOutsideTheRangeAndEndsOnAPastTheEndToken() {
Ec2Service service = tagTestService(new InMemoryStorageFactory());
for (int maxResults : new int[] {0, -1, 4, 1001}) {
AwsException error = assertThrows(AwsException.class,
() -> service.describeTags("us-east-1", List.of(), maxResults, null));
assertEquals("InvalidMaxResults", error.getErrorCode());
}
String pastTheEnd = Base64.getEncoder().encodeToString(
("{\"offset\":" + Integer.MAX_VALUE + "}").getBytes(StandardCharsets.UTF_8));
PaginatedResult<Map<String, String>> page = service.describeTags("us-east-1", List.of(), 5, pastTheEnd);
assertTrue(page.items().isEmpty());
assertNull(page.nextToken());
}
@Test
void tagsCarryTheResourceTypeOfImagesVolumesSnapshotsAclsPeeringsAndSpotRequests() {
Ec2Service service = tagTestService(new InMemoryStorageFactory());