fix(ec2): AND repeated filter names on every Describe action (#6170)

* fix(ec2): AND repeated filter names on every Describe action

The Query handler read Filter.N into a map keyed by name, so a filter
whose name was already given replaced the earlier one: tag-key=Env with
tag-key=Team matched every resource tagged Team, and two vpc-id filters
naming different VPCs matched the second VPC's resources. AWS joins
every filter with an AND, a repeated name included.

Every Describe action that reads Filter.N now passes the filters in
request order to the service, as DescribeKeyPairs, DescribeTags and
DescribeAvailabilityZones already did, and each filter narrows the
answer the way a lone filter of that name does. The service keeps its
map overloads for the callers that build filters of distinct names in
code; they delegate to the ordered overloads, so what they get back
does not change. DescribeImages builds its lookup image from the first
name wildcard and returns it only when it satisfies every filter.

Four existing tests passed null or any() as the filters of a method
that now has a second overload. They pass Map.of() or anyMap() instead,
which is what the code under test sends.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): sweep transit gateway peering attachments for repeated filters

DescribeTransitGatewayPeeringAttachments goes through the same shared
matcher as the other actions the parameterized tag-key case covers, but
had no case of its own. It now has one: two tag-key filters find only
the peering attachment that carries both keys.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): satisfy every repeated filter when building a lookup image

With a filter name given twice, DescribeImages built the image it
synthesizes for an unmatched lookup from the first name wildcard and the
first concrete value of each other filter, so a later filter of the same
name could reject it and the lookup came back empty: architecture with
x86_64 or arm64 and architecture with arm64 returned nothing. Each name
filter now offers its wildcard in turn, and each other value is the
first one that every filter of its name admits. A lone filter of each
name still yields the one image it always did.

DescribeInstanceTypeOfferings kept the types of its InstanceType.N
parameter only through the first instance-type filter, so repeating that
filter dropped them. They are now kept beside the types that every
instance-type filter names.

The docs say "an action" rather than "a Describe action", since the Get
and Search actions that read Filter.N are covered too.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): let an instance-type filter without values narrow nothing

DescribeInstanceTypeOfferings looked up the types its first
instance-type filter named, so a first filter without values limited the
answer to the InstanceType.N types while a later one without values
narrowed nothing: the answer depended on the order of the filters. A
filter without values now names and narrows nothing wherever it stands,
as a lone one never added a type.

The lookup image of DescribeImages tries the first wildcard of each name
filter, which the comment now says. Every filter value the image is
built from is tested by the image matchers' own rule.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(ec2): name the per-filter checks of repeated filters

The test that every filter of one name admits a value was written out by
hand at each site. Two helpers beside everyFilterAdmits now carry it:
everyFilterContains, for exact values where a filter without values
admits anything (security group rules, prefix lists, the later
instance-type filters of DescribeInstanceTypeOfferings), and
everyFilterMatches, for values with wildcards where a filter without
values matches nothing (the location filters of offerings, and the
spot-price and timestamp filters of DescribeSpotPriceHistory). No
answer changes.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): match instance-type wildcards in DescribeInstanceTypeOfferings

AWS takes * and ? in an instance-type filter value of
DescribeInstanceTypeOfferings (the CLI reference filters on c5*), but
Floci looked each value up by its exact name, so a lone t3.* found
nothing and t3.* beside t3.micro found nothing either. A first filter
holding a wildcard now looks up the whole catalog, and every filter
matches a type with the same matcher as the location filter. Exact
values give the same answer as before.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): pin an empty lookup for overlapping name patterns

Two name filters foo-* and *-bar-* overlap, but the image built from
the first wildcard of each breaks the other filter. DescribeImages
returns no image here, as AWS returns only images that exist; before
the filters were ANDed it returned one that broke foo-*.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): match offerings instance-type values with the linear glob

The instance-type wildcards of DescribeInstanceTypeOfferings went
through the regex matcher, which backtracks on a caller-supplied
pattern of many stars: twenty stars took about sixteen seconds per
request. They now go through everyFilterAdmits, the two-pointer glob
the image filters already use. Value-less filters are dropped before
the check, so no answer changes. Also reword a test comment.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): name the matcher a many-star pattern goes through

The glob that matches instance-type values is a two-pointer match, not
a strictly linear one, so the test's Javadoc says that instead.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-21 22:44:26 -04:00
1 parent e38980b6c1
commit 7c202a8966
10 files changed
+1561 -139

No files matched your search

@@ -0,0 +1,116 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Filter;
import software.amazon.awssdk.services.ec2.model.SecurityGroupRule;
import software.amazon.awssdk.services.ec2.model.Subnet;
import software.amazon.awssdk.services.ec2.model.Vpc;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* AWS joins every filter with an AND, so a filter name given twice narrows the answer twice
* instead of the second filter replacing the first.
*/
@DisplayName("EC2 Describe actions AND filters that repeat a name")
class Ec2RepeatedFilterNamesTest {
private static Filter filter(String name, String... values) {
return Filter.builder().name(name).values(values).build();
}
@Test
@DisplayName("Two tag-key filters find only the VPC that carries both keys")
void twoTagKeyFiltersFindTheVpcWithBothKeys() {
String only = TestFixtures.uniqueName("RepeatedOnly");
String shared = TestFixtures.uniqueName("RepeatedShared");
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
String both = ec2.createVpc(r -> r.cidrBlock("10.181.0.0/16")).vpc().vpcId();
String one = ec2.createVpc(r -> r.cidrBlock("10.182.0.0/16")).vpc().vpcId();
try {
ec2.createTags(r -> r.resources(both, one).tags(t -> t.key(shared).value("v")));
ec2.createTags(r -> r.resources(both).tags(t -> t.key(only).value("v")));
assertThat(vpcIds(ec2, filter("tag-key", shared))).containsExactlyInAnyOrder(both, one);
assertThat(vpcIds(ec2, filter("tag-key", only), filter("tag-key", shared))).containsExactly(both);
assertThat(vpcIds(ec2, filter("tag-key", shared), filter("tag-key", only))).containsExactly(both);
} finally {
ec2.deleteVpc(r -> r.vpcId(both));
ec2.deleteVpc(r -> r.vpcId(one));
}
}
}
@Test
@DisplayName("Two vpc-id filters naming different VPCs find no subnet")
void twoVpcIdFiltersFindNoSubnet() {
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
String first = ec2.createVpc(r -> r.cidrBlock("10.183.0.0/16")).vpc().vpcId();
String second = ec2.createVpc(r -> r.cidrBlock("10.184.0.0/16")).vpc().vpcId();
String firstSubnet = null;
String secondSubnet = null;
try {
firstSubnet = ec2.createSubnet(r -> r.vpcId(first).cidrBlock("10.183.1.0/24")).subnet().subnetId();
secondSubnet = ec2.createSubnet(r -> r.vpcId(second).cidrBlock("10.184.1.0/24")).subnet().subnetId();
assertThat(subnetIds(ec2, filter("vpc-id", second))).containsExactly(secondSubnet);
assertThat(subnetIds(ec2, filter("vpc-id", first), filter("vpc-id", second))).isEmpty();
assertThat(subnetIds(ec2, filter("vpc-id", first, second), filter("vpc-id", second)))
.containsExactly(secondSubnet);
} finally {
for (String subnet : new String[] {firstSubnet, secondSubnet}) {
if (subnet != null) {
ec2.deleteSubnet(r -> r.subnetId(subnet));
}
}
ec2.deleteVpc(r -> r.vpcId(first));
ec2.deleteVpc(r -> r.vpcId(second));
}
}
}
@Test
@DisplayName("Two group-id filters naming different groups find no security group rule")
void twoGroupIdFiltersFindNoSecurityGroupRule() {
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
String vpc = ec2.createVpc(r -> r.cidrBlock("10.185.0.0/16")).vpc().vpcId();
String first = null;
String second = null;
try {
first = ec2.createSecurityGroup(r -> r.vpcId(vpc).groupName(TestFixtures.uniqueName("repeated"))
.description("repeated filters")).groupId();
second = ec2.createSecurityGroup(r -> r.vpcId(vpc).groupName(TestFixtures.uniqueName("repeated"))
.description("repeated filters")).groupId();
String firstGroup = first;
String secondGroup = second;
assertThat(ruleGroups(ec2, filter("group-id", secondGroup))).isNotEmpty().containsOnly(secondGroup);
assertThat(ruleGroups(ec2, filter("group-id", firstGroup), filter("group-id", secondGroup))).isEmpty();
} finally {
for (String group : new String[] {first, second}) {
if (group != null) {
ec2.deleteSecurityGroup(r -> r.groupId(group));
}
}
ec2.deleteVpc(r -> r.vpcId(vpc));
}
}
}
private static List<String> vpcIds(Ec2Client ec2, Filter... filters) {
return ec2.describeVpcs(r -> r.filters(filters)).vpcs().stream().map(Vpc::vpcId).toList();
}
private static List<String> subnetIds(Ec2Client ec2, Filter... filters) {
return ec2.describeSubnets(r -> r.filters(filters)).subnets().stream().map(Subnet::subnetId).toList();
}
private static List<String> ruleGroups(Ec2Client ec2, Filter... filters) {
return ec2.describeSecurityGroupRules(r -> r.filters(filters)).securityGroupRules().stream()
.map(SecurityGroupRule::groupId).toList();
}
}
+7 -1
View File
@@ -247,6 +247,12 @@ Floci seeds the following resources on first use in each region so Terraform, th
## Supported Actions
Where an action reads `Filter.N`, every filter is joined with an AND and the values of one filter
with an OR, as the [Filter](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Filter.html)
reference describes. A name given twice counts as two filters, so `tag-key` with `Env` and
`tag-key` with `Team` find only the resources that carry both tag keys, and two `vpc-id` filters
naming different VPCs find nothing.
### Instances
| Action | Description |
@@ -799,7 +805,7 @@ regions, for which AWS publishes no zone id, keep the whole region as the prefix
| Action | Description |
|--------|-------------|
| DescribeInstanceTypes | Returns instance type metadata known to the local EC2 service, including `burstablePerformanceSupported` for the T families. |
| DescribeInstanceTypeOfferings | Returns instance type offerings for the requested location filters. |
| DescribeInstanceTypeOfferings | Returns instance type offerings for the requested location filters. An `instance-type` filter value may hold `*` and `?` wildcards, such as `t3.*`. |
### Launch Templates
@@ -395,14 +395,6 @@ public class Ec2QueryHandler {
}
}
private Map<String, List<String>> getFilters(MultivaluedMap<String, String> p) {
Map<String, List<String>> filters = new LinkedHashMap<>();
for (Map.Entry<String, List<String>> filter : getFiltersList(p)) {
filters.put(filter.getKey(), filter.getValue());
}
return filters;
}
/**
* Returns filters as a list of entries to preserve multiple filters with the same name
* (AND semantics across filters, OR within values of the same filter).
@@ -1260,8 +1252,7 @@ public class Ec2QueryHandler {
private Response handleDescribeIamInstanceProfileAssociations(MultivaluedMap<String, String> p, String region) {
List<String> associationIds = getList(p, "AssociationId");
Map<String, List<String>> filters = getFilters(p);
List<String> instanceFilter = filters.get("instance-id");
List<List<String>> instanceFilters = Ec2Service.filterValues(getFiltersList(p), "instance-id");
List<Reservation> reservations = service.describeInstances(region, List.of(), Map.of());
XmlBuilder xml = new XmlBuilder()
@@ -1274,7 +1265,7 @@ public class Ec2QueryHandler {
continue;
}
String assocId = Ec2Service.iamInstanceProfileAssociationId(inst.getInstanceId());
if (instanceFilter != null && !instanceFilter.contains(inst.getInstanceId())) {
if (instanceFilters.stream().anyMatch(values -> !values.contains(inst.getInstanceId()))) {
continue;
}
if (!associationIds.isEmpty() && !associationIds.contains(assocId)) {
@@ -1357,7 +1348,7 @@ public class Ec2QueryHandler {
private Response handleDescribeInstances(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "InstanceId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<Reservation> reservations = service.describeInstances(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
@@ -1497,7 +1488,7 @@ public class Ec2QueryHandler {
*/
private Response handleDescribeInstanceCreditSpecifications(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "InstanceId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
int maxResults = parseIntParam(p, "MaxResults", 0);
String nextToken = p.getFirst("NextToken");
@@ -1650,7 +1641,7 @@ public class Ec2QueryHandler {
private Response handleDescribeVpcs(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "VpcId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
// Resolve the lookup first so unsupported filters retain their error precedence.
List<Vpc> vpcs = service.describeVpcs(region, ids, filters);
// Shared service callers decide their own missing-resource behavior, as with subnets.
@@ -2298,7 +2289,7 @@ public class Ec2QueryHandler {
private Response handleDescribeVpcEndpoints(MultivaluedMap<String, String> p, String region) {
List<String> endpointIds = getList(p, "VpcEndpointId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<VpcEndpoint> endpoints = service.describeVpcEndpoints(region, endpointIds, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeVpcEndpointsResponse", AwsNamespaces.EC2)
@@ -2313,7 +2304,7 @@ public class Ec2QueryHandler {
private Response handleDescribePrefixLists(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "PrefixListId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<PrefixList> lists = service.describePrefixLists(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribePrefixListsResponse", AwsNamespaces.EC2)
@@ -2351,7 +2342,7 @@ public class Ec2QueryHandler {
private Response handleDescribeManagedPrefixLists(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "PrefixListId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<ManagedPrefixList> lists = service.describeManagedPrefixLists(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeManagedPrefixListsResponse", AwsNamespaces.EC2)
@@ -2426,7 +2417,7 @@ public class Ec2QueryHandler {
private Response handleDescribeTransitGateways(MultivaluedMap<String, String> p, String region) {
List<TransitGateway> gateways = service.describeTransitGateways(
region, getList(p, "TransitGatewayIds"), getFilters(p));
region, getList(p, "TransitGatewayIds"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewaysResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -2501,7 +2492,7 @@ public class Ec2QueryHandler {
private Response handleDescribeTransitGatewayVpcAttachments(MultivaluedMap<String, String> p, String region) {
List<TransitGatewayVpcAttachment> attachments = service.describeTransitGatewayVpcAttachments(
region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p));
region, getList(p, "TransitGatewayAttachmentIds"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewayVpcAttachmentsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -2520,7 +2511,7 @@ public class Ec2QueryHandler {
*/
private Response handleDescribeTransitGatewayAttachments(MultivaluedMap<String, String> p, String region) {
List<TransitGatewayVpcAttachment> attachments = service.describeTransitGatewayVpcAttachments(
region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p));
region, getList(p, "TransitGatewayAttachmentIds"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewayAttachmentsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -2550,7 +2541,7 @@ public class Ec2QueryHandler {
/** floci does not yet support creating Connect attachments, so this is always an empty list. */
private Response handleDescribeTransitGatewayConnects(MultivaluedMap<String, String> p, String region) {
service.describeTransitGatewayConnects(region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p));
service.describeTransitGatewayConnects(region, getList(p, "TransitGatewayAttachmentIds"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewayConnectsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -2608,7 +2599,7 @@ public class Ec2QueryHandler {
.elem("requestId", UUID.randomUUID().toString())
.start("transitGatewayPeeringAttachments");
for (TransitGatewayPeeringAttachment attachment : service.describeTransitGatewayPeeringAttachments(
region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p))) {
region, getList(p, "TransitGatewayAttachmentIds"), getFiltersList(p))) {
xml.start("item").raw(peeringAttachmentXml(attachment)).end("item");
}
xml.end("transitGatewayPeeringAttachments").end("DescribeTransitGatewayPeeringAttachmentsResponse");
@@ -2671,7 +2662,7 @@ public class Ec2QueryHandler {
private Response handleDescribeTransitGatewayRouteTables(MultivaluedMap<String, String> p, String region) {
List<TransitGatewayRouteTable> routeTables = service.describeTransitGatewayRouteTables(
region, getList(p, "TransitGatewayRouteTableIds"), getFilters(p));
region, getList(p, "TransitGatewayRouteTableIds"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewayRouteTablesResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -2724,7 +2715,7 @@ public class Ec2QueryHandler {
MultivaluedMap<String, String> p, String region) {
String routeTableId = p.getFirst("TransitGatewayRouteTableId");
List<TransitGatewayVpcAttachment> associated =
service.associationsOf(region, routeTableId, getFilters(p));
service.associationsOf(region, routeTableId, getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("GetTransitGatewayRouteTableAssociationsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -2763,7 +2754,7 @@ public class Ec2QueryHandler {
private Response handleGetTransitGatewayRouteTablePropagations(
MultivaluedMap<String, String> p, String region) {
List<TransitGatewayRouteTablePropagation> propagations =
service.propagationsOf(region, p.getFirst("TransitGatewayRouteTableId"), getFilters(p));
service.propagationsOf(region, p.getFirst("TransitGatewayRouteTableId"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("GetTransitGatewayRouteTablePropagationsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -2817,7 +2808,7 @@ public class Ec2QueryHandler {
private Response handleSearchTransitGatewayRoutes(MultivaluedMap<String, String> p, String region) {
List<TransitGatewayRoute> routes = service.searchTransitGatewayRoutes(
region, p.getFirst("TransitGatewayRouteTableId"), getFilters(p));
region, p.getFirst("TransitGatewayRouteTableId"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("SearchTransitGatewayRoutesResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3042,7 +3033,7 @@ public class Ec2QueryHandler {
private Response handleDescribeEgressOnlyInternetGateways(MultivaluedMap<String, String> p, String region) {
EgressOnlyInternetGatewayListResult result = service.describeEgressOnlyInternetGateways(
region, getList(p, "EgressOnlyInternetGatewayId"), getFilters(p),
region, getList(p, "EgressOnlyInternetGatewayId"), getFiltersList(p),
p.getFirst("MaxResults") == null ? null : parseIntParam(p, "MaxResults", 0),
p.getFirst("NextToken"));
XmlBuilder xml = new XmlBuilder()
@@ -3181,7 +3172,7 @@ public class Ec2QueryHandler {
private Response handleDescribeSubnets(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "SubnetId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
// A requested id that does not exist is an error, not an omission from the result. Returning
// an empty list tells a caller the subnet is gone when the id may simply be wrong, and a
// waiter polling for a subnet it just created cannot tell "not yet" from "never".
@@ -3260,7 +3251,7 @@ public class Ec2QueryHandler {
private Response handleDescribeSecurityGroups(MultivaluedMap<String, String> p, String region) {
List<String> groupIds = getList(p, "GroupId");
List<String> groupNames = getList(p, "GroupName");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<SecurityGroup> sgs = service.describeSecurityGroups(region, groupIds, groupNames, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeSecurityGroupsResponse", AwsNamespaces.EC2)
@@ -3275,7 +3266,7 @@ public class Ec2QueryHandler {
private Response handleGetSecurityGroupsForVpc(MultivaluedMap<String, String> p, String region) {
String vpcId = p.getFirst("VpcId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<SecurityGroup> sgs = service.getSecurityGroupsForVpc(region, vpcId, filters);
XmlBuilder xml = new XmlBuilder()
.start("GetSecurityGroupsForVpcResponse", AwsNamespaces.EC2)
@@ -3353,20 +3344,19 @@ public class Ec2QueryHandler {
}
private Response handleDescribeSecurityGroupRules(MultivaluedMap<String, String> p, String region) {
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
// The AWS SDK sends the security group id as a filter with name "group-id". Rule ids can
// arrive as the SecurityGroupRuleId.N parameter or the "security-group-rule-id" filter;
// filters are conjunctive with parameters, so intersect rather than union when both appear.
List<String> paramRuleIds = getList(p, "SecurityGroupRuleId");
List<String> filterRuleIds = filters.getOrDefault("security-group-rule-id", List.of());
List<String> ruleIds = paramRuleIds.isEmpty() || filterRuleIds.isEmpty()
? (paramRuleIds.isEmpty() ? filterRuleIds : paramRuleIds)
: paramRuleIds.stream().filter(filterRuleIds::contains).toList();
boolean unsatisfiable = !paramRuleIds.isEmpty() && !filterRuleIds.isEmpty() && ruleIds.isEmpty();
List<String> groupIds = filters.getOrDefault("group-id", List.of());
List<SecurityGroupRule> rules = unsatisfiable
? List.of()
: service.describeSecurityGroupRules(region, groupIds, ruleIds);
// filters are conjunctive with parameters and with each other, so each one narrows the
// rules the parameter names. A filter without values narrows nothing.
List<List<String>> ruleIdFilters = Ec2Service.filterValues(filters, "security-group-rule-id");
List<List<String>> groupIdFilters = Ec2Service.filterValues(filters, "group-id");
List<SecurityGroupRule> named = service.describeSecurityGroupRules(
region, List.of(), getList(p, "SecurityGroupRuleId"));
List<SecurityGroupRule> rules = named.stream()
.filter(rule -> Ec2Service.everyFilterContains(ruleIdFilters, rule.getSecurityGroupRuleId()))
.filter(rule -> Ec2Service.everyFilterContains(groupIdFilters, rule.getGroupId()))
.toList();
XmlBuilder xml = new XmlBuilder()
.start("DescribeSecurityGroupRulesResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3539,21 +3529,26 @@ public class Ec2QueryHandler {
private Response handleDescribeImages(MultivaluedMap<String, String> p, String region) {
List<String> imageIds = getList(p, "ImageId");
List<String> owners = getList(p, "Owner");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<Image> images = service.describeImages(region, imageIds, owners, filters);
// CDK's MachineImage.lookup is a synth-time context provider that queries
// by a `name` wildcard and aborts `cdk deploy` if the response is empty.
// When a wildcard name filter matches no seeded AMI, synthesize one that
// satisfies it, so the lookup resolves — the exact id is a runtime detail.
if (images.isEmpty() && imageIds.isEmpty() && filters.containsKey("name")) {
List<List<String>> nameFilters = Ec2Service.filterValues(filters, "name");
if (images.isEmpty() && imageIds.isEmpty() && !nameFilters.isEmpty()) {
// A filter's values are an OR, so the wildcard is whichever value carries one rather
// than whichever comes first. Taking the first outright meant an exact value ahead of
// a wildcard skipped synthesis and the lookup got nothing.
String namePattern = filters.get("name").stream()
.filter(v -> v != null && (v.contains("*") || v.contains("?")))
.findFirst()
.orElse(null);
if (namePattern != null) {
// a wildcard skipped synthesis and the lookup got nothing. Each name filter offers its
// first wildcard in turn, since the image one builds may fail another.
for (List<String> nameFilter : nameFilters) {
String namePattern = nameFilter.stream()
.filter(v -> v != null && (v.contains("*") || v.contains("?")))
.findFirst()
.orElse(null);
if (namePattern == null) {
continue;
}
Image synthesized = synthesizeLookupImage(namePattern, filters, owners);
// Only hand it back if it satisfies everything that was asked for. Returning an
// AMI that violates the request is worse than the empty result the lookup would
@@ -3562,6 +3557,7 @@ public class Ec2QueryHandler {
if (service.imageMatchesFilters(synthesized, filters)
&& service.imageMatchesOwners(synthesized, owners)) {
images = List.of(synthesized);
break;
}
}
}
@@ -3615,13 +3611,19 @@ public class Ec2QueryHandler {
* through verbatim produced an image owned by the literal string. AWS always reports an account
* id in {@code imageOwnerId}, so each alias resolves to the account it names.
*/
private String resolveSynthOwner(Map<String, List<String>> filters, List<String> owners) {
private String resolveSynthOwner(List<Map.Entry<String, List<String>>> filters, List<String> owners) {
// An owner-alias filter names an account just as much as Owner.N does, so it is consulted
// before the default. Without that, filtering on owner-alias alone produced an image
// carrying that alias beside the default Amazon account id, contradicting itself the same
// way an unresolved alias did in the other direction.
String requested = filters.getOrDefault("owner-id", owners == null ? List.of() : owners)
.stream().findFirst()
List<List<String>> ownerIdFilters = Ec2Service.filterValues(filters, "owner-id");
List<String> ownerIds = ownerIdFilters.isEmpty()
? (owners == null ? List.of() : owners)
: ownerIdFilters.stream()
.flatMap(List::stream)
.filter(v -> Ec2Service.everyFilterAdmits(ownerIdFilters, v))
.toList();
String requested = ownerIds.stream().findFirst()
.orElseGet(() -> firstFilterValue(filters, "owner-alias", AMAZON_OWNER_ID));
return switch (requested) {
case "self" -> service.callerAccountId();
@@ -3644,10 +3646,17 @@ public class Ec2QueryHandler {
};
}
/** The requested value for a scalar filter, so the synthesized image satisfies it. */
private static String firstFilterValue(Map<String, List<String>> filters, String name, String fallback) {
return filters.getOrDefault(name, List.of()).stream()
/**
* The requested value for a scalar filter, so the synthesized image satisfies it: the first
* value without a wildcard that every filter of that name admits.
*/
private static String firstFilterValue(List<Map.Entry<String, List<String>>> filters, String name,
String fallback) {
List<List<String>> named = Ec2Service.filterValues(filters, name);
return named.stream()
.flatMap(List::stream)
.filter(v -> v != null && !v.contains("*") && !v.contains("?"))
.filter(v -> Ec2Service.everyFilterAdmits(named, v))
.findFirst()
.orElse(fallback);
}
@@ -3656,7 +3665,8 @@ public class Ec2QueryHandler {
* Builds an AMI that satisfies a lookup's name wildcard and its owner and architecture filters.
* The id is a hash of the pattern, so repeated lookups resolve to the same image.
*/
private Image synthesizeLookupImage(String namePattern, Map<String, List<String>> filters, List<String> owners) {
private Image synthesizeLookupImage(String namePattern, List<Map.Entry<String, List<String>>> filters,
List<String> owners) {
Image img = new Image();
// 17 hex chars after "ami-", deterministic from the pattern.
String hash = String.format("%08x", namePattern.hashCode() & 0x7fffffff);
@@ -3769,7 +3779,7 @@ public class Ec2QueryHandler {
private Response handleDescribeSnapshots(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "SnapshotId");
List<String> owners = getList(p, "Owner", "OwnerId", "OwnerIds");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<Snapshot> snapshots = service.describeSnapshots(region, ids, owners, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeSnapshotsResponse", AwsNamespaces.EC2)
@@ -3856,7 +3866,7 @@ public class Ec2QueryHandler {
private Response handleDescribeInternetGateways(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "InternetGatewayId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<InternetGateway> igws = service.describeInternetGateways(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeInternetGatewaysResponse", AwsNamespaces.EC2)
@@ -3900,13 +3910,13 @@ public class Ec2QueryHandler {
}
private Response handleDescribeVpnGateways(MultivaluedMap<String, String> p) {
service.describeVpnGatewayIds(getList(p, "VpnGatewayId"), getFilters(p));
service.describeVpnGatewayIds(getList(p, "VpnGatewayId"), getFiltersList(p));
return emptyDescribeResponse("DescribeVpnGateways", "vpnGatewaySet");
}
private Response handleDescribeRouteTables(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "RouteTableId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<RouteTable> rts = service.describeRouteTables(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeRouteTablesResponse", AwsNamespaces.EC2)
@@ -4038,7 +4048,7 @@ public class Ec2QueryHandler {
private Response handleDescribeVpcPeeringConnections(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "VpcPeeringConnectionId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<VpcPeeringConnection> connections = service.describeVpcPeeringConnections(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeVpcPeeringConnectionsResponse", AwsNamespaces.EC2)
@@ -4129,7 +4139,7 @@ public class Ec2QueryHandler {
private Response handleDescribeNetworkAcls(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "NetworkAclId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<NetworkAcl> acls = service.describeNetworkAcls(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeNetworkAclsResponse", AwsNamespaces.EC2)
@@ -4201,7 +4211,7 @@ public class Ec2QueryHandler {
private Response handleDescribeNatGateways(MultivaluedMap<String, String> p, String region) {
List<String> natGatewayIds = getList(p, "NatGatewayId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<NatGateway> natGateways = service.describeNatGateways(region, natGatewayIds, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeNatGatewaysResponse", AwsNamespaces.EC2)
@@ -4254,7 +4264,7 @@ public class Ec2QueryHandler {
private Response handleDescribeCapacityReservations(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "CapacityReservationId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<CapacityReservation> reservations = service.describeCapacityReservations(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeCapacityReservationsResponse", AwsNamespaces.EC2)
@@ -4338,7 +4348,7 @@ public class Ec2QueryHandler {
}
private Response handleDescribeHosts(MultivaluedMap<String, String> p, String region) {
List<Host> found = service.describeHosts(region, getList(p, "HostId"), getFilters(p));
List<Host> found = service.describeHosts(region, getList(p, "HostId"), getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeHostsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -4486,7 +4496,7 @@ public class Ec2QueryHandler {
private Response handleDescribeAddresses(MultivaluedMap<String, String> p, String region) {
List<String> allocationIds = getList(p, "AllocationId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<Address> addrs = service.describeAddresses(region, allocationIds, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeAddressesResponse", AwsNamespaces.EC2)
@@ -4648,7 +4658,7 @@ public class Ec2QueryHandler {
private Response handleDescribeInstanceTypeOfferings(MultivaluedMap<String, String> p, String region) {
List<String> typeNames = getList(p, "InstanceType");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<Map<String, String>> offerings = service.describeInstanceTypeOfferings(
region, typeNames, p.getFirst("LocationType"), filters);
XmlBuilder xml = new XmlBuilder()
@@ -4702,7 +4712,7 @@ public class Ec2QueryHandler {
private Response handleDescribeLaunchTemplates(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "LaunchTemplateId");
List<String> names = getList(p, "LaunchTemplateName");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<LaunchTemplate> launchTemplates = service.describeLaunchTemplates(region, ids, names, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeLaunchTemplatesResponse", AwsNamespaces.EC2)
@@ -4763,7 +4773,7 @@ public class Ec2QueryHandler {
private Response handleDescribeNetworkInterfaces(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "NetworkInterfaceId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
// Phase 5: pagination parameters
int maxResults = parseIntParam(p, "MaxResults", 0);
@@ -6191,7 +6201,7 @@ public class Ec2QueryHandler {
private Response handleDescribeVolumes(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "VolumeId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<Volume> volList = service.describeVolumes(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeVolumesResponse", AwsNamespaces.EC2)
@@ -6237,7 +6247,7 @@ public class Ec2QueryHandler {
private Response handleDescribeVolumesModifications(MultivaluedMap<String, String> p, String region) {
checkDryRun(p);
List<String> ids = getList(p, "VolumeId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<VolumeModification> modList = service.describeVolumesModifications(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeVolumesModificationsResponse", AwsNamespaces.EC2)
@@ -6456,7 +6466,7 @@ public class Ec2QueryHandler {
private Response handleDescribeSpotInstanceRequests(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "SpotInstanceRequestId");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
List<SpotInstanceRequest> requests = service.describeSpotInstanceRequests(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
@@ -6510,7 +6520,7 @@ public class Ec2QueryHandler {
}
Instant startTime = instantOrNull(p, "StartTime");
Instant endTime = instantOrNull(p, "EndTime");
Map<String, List<String>> filters = getFilters(p);
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
String nextToken = p.getFirst("NextToken");
int maxResults = 0;
@@ -1477,6 +1477,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<NetworkAcl> describeNetworkAcls(String region, List<String> ids, Map<String, List<String>> filters) {
return describeNetworkAcls(region, ids, filterList(filters));
}
List<NetworkAcl> describeNetworkAcls(String region, List<String> ids,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
return networkAcls.scan(k -> true).stream()
.filter(a -> region.equals(a.getRegion()))
@@ -1485,8 +1490,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.collect(Collectors.toList());
}
private boolean matchesNetworkAclFilters(NetworkAcl acl, Map<String, List<String>> filters) {
for (Map.Entry<String, List<String>> f : filters.entrySet()) {
private boolean matchesNetworkAclFilters(NetworkAcl acl, List<Map.Entry<String, List<String>>> filters) {
for (Map.Entry<String, List<String>> f : filters) {
List<String> values = f.getValue();
boolean matches = switch (f.getKey()) {
case "network-acl-id" -> values.contains(acl.getNetworkAclId());
@@ -1604,12 +1609,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// DescribeManagedPrefixLists serves, so the two APIs cannot report different CIDRs for the
// same list.
public List<PrefixList> describePrefixLists(String region, List<String> ids, Map<String, List<String>> filters) {
List<String> names = filters.getOrDefault("prefix-list-name", List.of());
List<String> filterIds = filters.getOrDefault("prefix-list-id", List.of());
return describePrefixLists(region, ids, filterList(filters));
}
List<PrefixList> describePrefixLists(String region, List<String> ids,
List<Map.Entry<String, List<String>>> filters) {
List<List<String>> names = filterValues(filters, "prefix-list-name");
List<List<String>> filterIds = filterValues(filters, "prefix-list-id");
return awsManagedPrefixLists(region).stream()
.filter(pl -> ids.isEmpty() || ids.contains(pl.getPrefixListId()))
.filter(pl -> filterIds.isEmpty() || filterIds.contains(pl.getPrefixListId()))
.filter(pl -> names.isEmpty() || names.contains(pl.getPrefixListName()))
.filter(pl -> everyFilterContains(filterIds, pl.getPrefixListId()))
.filter(pl -> everyFilterContains(names, pl.getPrefixListName()))
.map(pl -> new PrefixList(pl.getPrefixListId(), pl.getPrefixListName(),
pl.currentEntries().stream()
.map(PrefixListEntry::getCidr)
@@ -1717,6 +1727,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<ManagedPrefixList> describeManagedPrefixLists(String region, List<String> prefixListIds,
Map<String, List<String>> filters) {
return describeManagedPrefixLists(region, prefixListIds, filterList(filters));
}
List<ManagedPrefixList> describeManagedPrefixLists(String region, List<String> prefixListIds,
List<Map.Entry<String, List<String>>> filters) {
List<ManagedPrefixList> all = new ArrayList<>(awsManagedPrefixLists(region));
managedPrefixLists.scan(k -> true).stream()
.filter(list -> region.equals(list.getRegion()))
@@ -2091,6 +2106,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<TransitGateway> describeTransitGateways(String region, List<String> transitGatewayIds,
Map<String, List<String>> filters) {
return describeTransitGateways(region, transitGatewayIds, filterList(filters));
}
List<TransitGateway> describeTransitGateways(String region, List<String> transitGatewayIds,
List<Map.Entry<String, List<String>>> filters) {
transitGatewayIds.forEach(Ec2Service::requireWellFormedTransitGatewayId);
List<TransitGateway> all = transitGateways.scan(k -> true).stream()
.filter(gateway -> region.equals(gateway.getRegion()))
@@ -2535,6 +2555,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<TransitGatewayVpcAttachment> describeTransitGatewayVpcAttachments(
String region, List<String> attachmentIds, Map<String, List<String>> filters) {
return describeTransitGatewayVpcAttachments(region, attachmentIds, filterList(filters));
}
List<TransitGatewayVpcAttachment> describeTransitGatewayVpcAttachments(
String region, List<String> attachmentIds, List<Map.Entry<String, List<String>>> filters) {
attachmentIds.forEach(Ec2Service::requireWellFormedAttachmentId);
List<TransitGatewayVpcAttachment> all = transitGatewayVpcAttachments.scan(k -> true).stream()
.filter(attachment -> region.equals(attachment.getRegion()))
@@ -2560,6 +2585,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
*/
public void describeTransitGatewayConnects(
String region, List<String> attachmentIds, Map<String, List<String>> filters) {
describeTransitGatewayConnects(region, attachmentIds, filterList(filters));
}
void describeTransitGatewayConnects(
String region, List<String> attachmentIds, List<Map.Entry<String, List<String>>> filters) {
attachmentIds.forEach(Ec2Service::requireWellFormedAttachmentId);
if (!attachmentIds.isEmpty()) {
throw new AwsException("InvalidTransitGatewayConnectID.NotFound",
@@ -2702,6 +2732,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<TransitGatewayPeeringAttachment> describeTransitGatewayPeeringAttachments(
String region, List<String> attachmentIds, Map<String, List<String>> filters) {
return describeTransitGatewayPeeringAttachments(region, attachmentIds, filterList(filters));
}
List<TransitGatewayPeeringAttachment> describeTransitGatewayPeeringAttachments(
String region, List<String> attachmentIds, List<Map.Entry<String, List<String>>> filters) {
attachmentIds.forEach(Ec2Service::requireWellFormedAttachmentId);
String account = callerAccountId();
List<TransitGatewayPeeringAttachment> visible = allPeeringAttachments().stream()
@@ -2912,6 +2947,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<TransitGatewayRouteTable> describeTransitGatewayRouteTables(
String region, List<String> routeTableIds, Map<String, List<String>> filters) {
return describeTransitGatewayRouteTables(region, routeTableIds, filterList(filters));
}
List<TransitGatewayRouteTable> describeTransitGatewayRouteTables(
String region, List<String> routeTableIds, List<Map.Entry<String, List<String>>> filters) {
routeTableIds.forEach(Ec2Service::requireWellFormedRouteTableId);
List<TransitGatewayRouteTable> all = transitGatewayRouteTables.scan(k -> true).stream()
.filter(routeTable -> region.equals(routeTable.getRegion()))
@@ -3002,8 +3042,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
/** The attachments associated with a route table, which is where an association is recorded. */
public List<TransitGatewayVpcAttachment> associationsOf(
String region, String routeTableId, Map<String, List<String>> filters) {
Map<String, List<String>> modeledFilters = new LinkedHashMap<>(filters);
modeledFilters.keySet().retainAll(ROUTE_TABLE_MEMBERSHIP_FILTER_NAMES);
return associationsOf(region, routeTableId, filterList(filters));
}
List<TransitGatewayVpcAttachment> associationsOf(
String region, String routeTableId, List<Map.Entry<String, List<String>>> filters) {
List<Map.Entry<String, List<String>>> modeledFilters = membershipFilters(filters);
return transitGatewayVpcAttachments.scan(k -> true).stream()
.filter(attachment -> region.equals(attachment.getRegion()))
.filter(attachment -> routeTableId.equals(attachment.getAssociationRouteTableId()))
@@ -3057,8 +3101,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<TransitGatewayRouteTablePropagation> propagationsOf(
String region, String routeTableId, Map<String, List<String>> filters) {
Map<String, List<String>> modeledFilters = new LinkedHashMap<>(filters);
modeledFilters.keySet().retainAll(ROUTE_TABLE_MEMBERSHIP_FILTER_NAMES);
return propagationsOf(region, routeTableId, filterList(filters));
}
List<TransitGatewayRouteTablePropagation> propagationsOf(
String region, String routeTableId, List<Map.Entry<String, List<String>>> filters) {
List<Map.Entry<String, List<String>>> modeledFilters = membershipFilters(filters);
return transitGatewayPropagations.scan(k -> true).stream()
.filter(propagation -> region.equals(propagation.getRegion()))
.filter(propagation -> routeTableId.equals(propagation.getTransitGatewayRouteTableId()))
@@ -3066,6 +3114,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.collect(Collectors.toList());
}
private static List<Map.Entry<String, List<String>>> membershipFilters(
List<Map.Entry<String, List<String>>> filters) {
return filters.stream()
.filter(filter -> ROUTE_TABLE_MEMBERSHIP_FILTER_NAMES.contains(filter.getKey()))
.toList();
}
public TransitGatewayRoute createTransitGatewayRoute(String region, String routeTableId,
String destinationCidrBlock, String attachmentId,
boolean blackhole) {
@@ -3165,6 +3220,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
*/
public List<TransitGatewayRoute> searchTransitGatewayRoutes(String region, String routeTableId,
Map<String, List<String>> filters) {
return searchTransitGatewayRoutes(region, routeTableId, filterList(filters));
}
List<TransitGatewayRoute> searchTransitGatewayRoutes(String region, String routeTableId,
List<Map.Entry<String, List<String>>> filters) {
getRequiredTransitGatewayRouteTable(region, routeTableId);
List<TransitGatewayRoute> routes = new ArrayList<>(routesOf(region, routeTableId));
for (TransitGatewayRouteTablePropagation propagation : propagationsOf(region, routeTableId)) {
@@ -3214,12 +3274,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* answer a question that was never asked.
*/
private List<TransitGatewayRoute> applyRouteFilters(List<TransitGatewayRoute> routes,
Map<String, List<String>> filters) {
List<Map.Entry<String, List<String>>> filters) {
if (filters == null || filters.isEmpty()) {
return routes;
}
List<TransitGatewayRoute> matched = new ArrayList<>(routes);
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
for (Map.Entry<String, List<String>> filter : filters) {
String name = filter.getKey();
List<String> values = filter.getValue();
switch (name) {
@@ -4353,6 +4413,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<Reservation> describeInstances(String region, List<String> instanceIds, Map<String, List<String>> filters) {
return describeInstances(region, instanceIds, filterList(filters));
}
List<Reservation> describeInstances(String region, List<String> instanceIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
if (!instanceIds.isEmpty()) {
for (String id : instanceIds) {
@@ -4961,6 +5026,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.collect(Collectors.toList());
}
public InstanceCreditSpecificationListResult describeInstanceCreditSpecifications(
String region, List<String> instanceIds, Map<String, List<String>> filters,
int maxResults, String nextToken) {
return describeInstanceCreditSpecifications(region, instanceIds, filterList(filters), maxResults, nextToken);
}
/**
* The credit option for CPU usage of burstable performance instances.
*
@@ -4991,8 +5062,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* @param maxResults page size, or 0 for no pagination. AWS rejects it together with ids
* @param nextToken the cursor from a previous page, or null
*/
public InstanceCreditSpecificationListResult describeInstanceCreditSpecifications(
String region, List<String> instanceIds, Map<String, List<String>> filters,
InstanceCreditSpecificationListResult describeInstanceCreditSpecifications(
String region, List<String> instanceIds, List<Map.Entry<String, List<String>>> filters,
int maxResults, String nextToken) {
validateInstanceCreditSpecificationsPagination(instanceIds, maxResults);
ensureDefaultResources(region);
@@ -5522,11 +5593,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<Vpc> describeVpcs(String region, List<String> vpcIds, Map<String, List<String>> filters) {
return describeVpcs(region, vpcIds, filterList(filters));
}
List<Vpc> describeVpcs(String region, List<String> vpcIds, List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
// matchesFilters answers true for a name it does not recognise, so without this an
// unsupported filter matches every VPC instead of narrowing anything. Real EC2 rejects the
// name outright, which is the difference between a wrong result and an error.
requireSupportedFilters(filters.keySet(), VPC_FILTERS);
requireSupportedFilters(filterNames(filters), VPC_FILTERS);
return vpcs.scan(k -> true).stream()
.filter(v -> v.getRegion().equals(region))
.filter(v -> vpcIds.isEmpty() || vpcIds.contains(v.getVpcId()))
@@ -5536,7 +5611,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<String> describeVpnGatewayIds(
List<String> gatewayIds, Map<String, List<String>> filters) {
requireSupportedFilters(filters.keySet(), VPN_GATEWAY_FILTERS);
return describeVpnGatewayIds(gatewayIds, filterList(filters));
}
List<String> describeVpnGatewayIds(
List<String> gatewayIds, List<Map.Entry<String, List<String>>> filters) {
requireSupportedFilters(filterNames(filters), VPN_GATEWAY_FILTERS);
if (!gatewayIds.isEmpty()) {
throw new AwsException("InvalidVpnGatewayID.NotFound",
"The vpnGateway ID '" + gatewayIds.getFirst() + "' does not exist", 400);
@@ -5592,7 +5672,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// the Terraform provider treat the empty result as "not found".
public List<EgressOnlyInternetGateway> describeEgressOnlyInternetGateways(String region, List<String> ids,
Map<String, List<String>> filters) {
requireSupportedFilters(filters.keySet(), EGRESS_ONLY_INTERNET_GATEWAY_FILTERS);
return describeEgressOnlyInternetGateways(region, ids, filterList(filters));
}
List<EgressOnlyInternetGateway> describeEgressOnlyInternetGateways(String region, List<String> ids,
List<Map.Entry<String, List<String>>> filters) {
requireSupportedFilters(filterNames(filters), EGRESS_ONLY_INTERNET_GATEWAY_FILTERS);
return egressOnlyInternetGateways.scan(k -> k.startsWith(region + "::")).stream()
.filter(eigw -> ids.isEmpty() || ids.contains(eigw.getEgressOnlyInternetGatewayId()))
.filter(eigw -> matchesFilters(eigw, filters, region))
@@ -5607,6 +5692,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public EgressOnlyInternetGatewayListResult describeEgressOnlyInternetGateways(
String region, List<String> ids, Map<String, List<String>> filters, Integer maxResults,
String nextToken) {
return describeEgressOnlyInternetGateways(region, ids, filterList(filters), maxResults, nextToken);
}
EgressOnlyInternetGatewayListResult describeEgressOnlyInternetGateways(
String region, List<String> ids, List<Map.Entry<String, List<String>>> filters, Integer maxResults,
String nextToken) {
if (maxResults != null && (maxResults < 5 || maxResults > 255)) {
throw new AwsException("InvalidMaxResults",
"Value (" + maxResults + ") for parameter MaxResults is invalid. "
@@ -6234,6 +6325,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<VpcEndpoint> describeVpcEndpoints(String region, List<String> endpointIds,
Map<String, List<String>> filters) {
return describeVpcEndpoints(region, endpointIds, filterList(filters));
}
List<VpcEndpoint> describeVpcEndpoints(String region, List<String> endpointIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
if (!endpointIds.isEmpty()) {
for (String endpointId : endpointIds) {
@@ -6858,6 +6954,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<Subnet> describeSubnets(String region, List<String> subnetIds, Map<String, List<String>> filters) {
return describeSubnets(region, subnetIds, filterList(filters));
}
List<Subnet> describeSubnets(String region, List<String> subnetIds, List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
List<Subnet> result = subnets.scan(k -> true).stream()
.filter(s -> s.getRegion().equals(region))
@@ -6998,6 +7098,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<SecurityGroup> describeSecurityGroups(String region, List<String> groupIds,
List<String> groupNames, Map<String, List<String>> filters) {
return describeSecurityGroups(region, groupIds, groupNames, filterList(filters));
}
List<SecurityGroup> describeSecurityGroups(String region, List<String> groupIds, List<String> groupNames,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
return securityGroups.scan(k -> true).stream()
.filter(sg -> sg.getRegion().equals(region))
@@ -7009,6 +7114,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<SecurityGroup> getSecurityGroupsForVpc(String region, String vpcId,
Map<String, List<String>> filters) {
return getSecurityGroupsForVpc(region, vpcId, filterList(filters));
}
List<SecurityGroup> getSecurityGroupsForVpc(String region, String vpcId,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
getRequiredVpc(region, vpcId);
return securityGroups.scan(k -> true).stream()
@@ -7679,6 +7789,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<Image> describeImages(String region, List<String> imageIds, List<String> owners, Map<String, List<String>> filters) {
return describeImages(region, imageIds, owners, filterList(filters));
}
List<Image> describeImages(String region, List<String> imageIds, List<String> owners,
List<Map.Entry<String, List<String>>> filters) {
List<Image> catalogImages = imageCatalog.images().stream()
.filter(Ec2ImageCatalog.CatalogImage::advertised)
.filter(img -> img.matchesIdOrAlias(imageIds))
@@ -7712,7 +7827,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// create (the aws provider reports "collecting instance settings: empty result"). Mirror the launch-time
// fallback so a describe of a launchable id returns a matching image instead of nothing.
private void addFallbackLaunchableImages(String region, List<Image> images, List<String> imageIds,
List<String> owners, Map<String, List<String>> filters) {
List<String> owners, List<Map.Entry<String, List<String>>> filters) {
if (imageIds == null || imageIds.isEmpty()) {
return;
}
@@ -8319,6 +8434,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<Snapshot> describeSnapshots(String region, List<String> snapshotIds,
List<String> ownerIds, Map<String, List<String>> filters) {
return describeSnapshots(region, snapshotIds, ownerIds, filterList(filters));
}
List<Snapshot> describeSnapshots(String region, List<String> snapshotIds, List<String> ownerIds,
List<Map.Entry<String, List<String>>> filters) {
if (snapshotIds != null && !snapshotIds.isEmpty()) {
for (String id : snapshotIds) {
if (snapshots.get(key(region, id)).isEmpty()) {
@@ -8533,7 +8653,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
region,
id != null && !id.isBlank() ? List.of(id) : List.of(),
name != null && !name.isBlank() ? List.of(name) : List.of(),
Map.of());
List.of());
List<LaunchTemplate> versions = new ArrayList<>();
for (LaunchTemplate launchTemplate : templates) {
List<String> effectiveVersions = requestedVersions == null || requestedVersions.isEmpty()
@@ -8578,9 +8698,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
*/
public List<LaunchTemplate> describeLaunchTemplates(String region, List<String> ids,
List<String> names, Map<String, List<String>> filters) {
return describeLaunchTemplates(region, ids, names, filterList(filters));
}
List<LaunchTemplate> describeLaunchTemplates(String region, List<String> ids, List<String> names,
List<Map.Entry<String, List<String>>> filters) {
if (!names.isEmpty() || !ids.isEmpty()) {
List<LaunchTemplate> regionTemplates =
matchingLaunchTemplates(region, List.of(), List.of(), Map.of());
matchingLaunchTemplates(region, List.of(), List.of(), List.of());
for (String name : names) {
if (regionTemplates.stream().noneMatch(lt -> name.equals(lt.getLaunchTemplateName()))) {
throw new AwsException("InvalidLaunchTemplateName.NotFoundException",
@@ -8597,8 +8722,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return matchingLaunchTemplates(region, ids, names, filters);
}
private List<LaunchTemplate> matchingLaunchTemplates(String region, List<String> ids,
List<String> names, Map<String, List<String>> filters) {
private List<LaunchTemplate> matchingLaunchTemplates(String region, List<String> ids, List<String> names,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
return launchTemplates.scan(k -> true).stream()
.filter(lt -> lt.getRegion().equals(region))
@@ -8786,11 +8911,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return copy;
}
private boolean matchesImageFilters(Ec2ImageCatalog.CatalogImage image, Map<String, List<String>> filters) {
private boolean matchesImageFilters(Ec2ImageCatalog.CatalogImage image,
List<Map.Entry<String, List<String>>> filters) {
if (filters == null || filters.isEmpty()) {
return true;
}
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
for (Map.Entry<String, List<String>> filter : filters) {
if (!matchesImageFilter(image, filter.getKey(), filter.getValue())) {
return false;
}
@@ -8849,7 +8975,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* Whether an image satisfies a DescribeImages filter set. Exposed so a synthesized lookup image
* can be checked against the request that produced it before being returned.
*/
public boolean imageMatchesFilters(Image image, Map<String, List<String>> filters) {
public boolean imageMatchesFilters(Image image, List<Map.Entry<String, List<String>>> filters) {
return matchesRegisteredImageFilters(image, filters);
}
@@ -8862,11 +8988,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return matchesImageOwners(image, owners);
}
private boolean matchesRegisteredImageFilters(Image image, Map<String, List<String>> filters) {
private boolean matchesRegisteredImageFilters(Image image, List<Map.Entry<String, List<String>>> filters) {
if (filters == null || filters.isEmpty()) {
return true;
}
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
for (Map.Entry<String, List<String>> filter : filters) {
if (!matchesRegisteredImageFilter(image, filter.getKey(), filter.getValue())) {
return false;
}
@@ -8939,7 +9065,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
private boolean matchesImageTagFilter(Image image, String name, List<String> values) {
return matchesTagFilter(image.getTags(), name, values, this::matchesFilterValue);
return matchesTagFilter(image.getTags(), name, values, Ec2Service::matchesFilterValue);
}
private boolean matchesTagFilter(List<Tag> resourceTags, String filterName, List<String> values,
@@ -8967,11 +9093,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return snapshot;
}
private boolean matchesSnapshotFilters(Snapshot snapshot, Map<String, List<String>> filters) {
private boolean matchesSnapshotFilters(Snapshot snapshot, List<Map.Entry<String, List<String>>> filters) {
if (filters == null || filters.isEmpty()) {
return true;
}
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
for (Map.Entry<String, List<String>> filter : filters) {
if (!matchesSnapshotFilter(snapshot, filter.getKey(), filter.getValue())) {
return false;
}
@@ -9002,7 +9128,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
};
}
private boolean matchesFilterValue(List<String> patterns, String value) {
private static boolean matchesFilterValue(List<String> patterns, String value) {
if (patterns == null || patterns.isEmpty()) {
return true;
}
@@ -9020,7 +9146,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* 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) {
private static boolean wildcardMatches(String pattern, String value) {
return IamPolicyEvaluator.caseSensitiveGlobMatches(pattern, value);
}
@@ -9586,6 +9712,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<InternetGateway> describeInternetGateways(String region, List<String> igwIds, Map<String, List<String>> filters) {
return describeInternetGateways(region, igwIds, filterList(filters));
}
List<InternetGateway> describeInternetGateways(String region, List<String> igwIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
return internetGateways.scan(k -> true).stream()
.filter(igw -> igw.getRegion().equals(region))
@@ -9689,6 +9820,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<CapacityReservation> describeCapacityReservations(String region, List<String> ids,
Map<String, List<String>> filters) {
return describeCapacityReservations(region, ids, filterList(filters));
}
List<CapacityReservation> describeCapacityReservations(String region, List<String> ids,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
for (String id : ids) {
getRequiredCapacityReservation(region, id);
@@ -9819,6 +9955,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<Host> describeHosts(String region, List<String> ids, Map<String, List<String>> filters) {
return describeHosts(region, ids, filterList(filters));
}
List<Host> describeHosts(String region, List<String> ids, List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
for (String id : ids) {
getRequiredHost(region, id);
@@ -9965,10 +10105,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<RouteTable> describeRouteTables(String region, List<String> routeTableIds, Map<String, List<String>> filters) {
return describeRouteTables(callerAccountId(), region, routeTableIds, filterList(filters));
}
List<RouteTable> describeRouteTables(String region, List<String> routeTableIds,
List<Map.Entry<String, List<String>>> filters) {
return describeRouteTables(callerAccountId(), region, routeTableIds, filters);
}
public List<RouteTable> describeRouteTables(String accountId, String region, List<String> routeTableIds, Map<String, List<String>> filters) {
return describeRouteTables(accountId, region, routeTableIds, filterList(filters));
}
List<RouteTable> describeRouteTables(String accountId, String region, List<String> routeTableIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
String safeAccount = accountId != null ? accountId : callerAccountId();
List<RouteTable> accountRouteTables = routeTables instanceof AccountAwareStorageBackend<RouteTable> aware
@@ -10565,6 +10715,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<VpcPeeringConnection> describeVpcPeeringConnections(String region, List<String> ids,
Map<String, List<String>> filters) {
return describeVpcPeeringConnections(region, ids, filterList(filters));
}
List<VpcPeeringConnection> describeVpcPeeringConnections(String region, List<String> ids,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
String caller = callerAccountId();
return allVpcPeeringConnections().stream()
@@ -10912,6 +11067,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<NatGateway> describeNatGateways(String region, List<String> natGatewayIds,
Map<String, List<String>> filters) {
return describeNatGateways(region, natGatewayIds, filterList(filters));
}
List<NatGateway> describeNatGateways(String region, List<String> natGatewayIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
if (!natGatewayIds.isEmpty()) {
for (String natGatewayId : natGatewayIds) {
@@ -11340,6 +11500,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<Address> describeAddresses(String region, List<String> allocationIds, Map<String, List<String>> filters) {
return describeAddresses(region, allocationIds, filterList(filters));
}
List<Address> describeAddresses(String region, List<String> allocationIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
List<Address> candidates = addresses.scan(k -> true).stream()
.filter(a -> a.getRegion().equals(region))
@@ -11517,10 +11682,28 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<Map<String, String>> describeInstanceTypeOfferings(String region, List<String> instanceTypeNames,
String locationType,
Map<String, List<String>> filters) {
return describeInstanceTypeOfferings(region, instanceTypeNames, locationType, filterList(filters));
}
List<Map<String, String>> describeInstanceTypeOfferings(String region, List<String> instanceTypeNames,
String locationType,
List<Map.Entry<String, List<String>>> filters) {
// The first instance-type filter names the types to look up beside InstanceType.N, as a
// lone one always has, or the whole catalog when one of its values holds a * or ?
// wildcard. Every filter must then match a looked-up type, so the answer is InstanceType.N
// plus the types every filter matches. A filter without values names nothing and narrows
// nothing, as a lone one never added a type.
List<List<String>> typeFilters = filterValues(filters, "instance-type").stream()
.filter(values -> !values.isEmpty())
.toList();
List<String> effectiveTypeNames = new ArrayList<>(new LinkedHashSet<>(instanceTypeNames));
if (filters != null && filters.containsKey("instance-type")) {
effectiveTypeNames.addAll(filters.get("instance-type"));
effectiveTypeNames = new ArrayList<>(new LinkedHashSet<>(effectiveTypeNames));
if (!typeFilters.isEmpty()) {
if (typeFilters.getFirst().stream().anyMatch(value -> value.contains("*") || value.contains("?"))) {
effectiveTypeNames = List.of();
} else {
effectiveTypeNames.addAll(typeFilters.getFirst());
effectiveTypeNames = new ArrayList<>(new LinkedHashSet<>(effectiveTypeNames));
}
}
String effectiveLocationType = locationType != null && !locationType.isBlank()
? locationType
@@ -11530,13 +11713,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
: describeAvailabilityZones(region, List.of(), List.of(), null).stream()
.map(zone -> zone.get("zoneName"))
.toList();
List<String> locationFilter = filters != null ? filters.get("location") : null;
List<List<String>> locationFilters = filterValues(filters, "location");
List<Map<String, String>> offerings = new ArrayList<>();
for (Map<String, Object> type : describeInstanceTypes(effectiveTypeNames)) {
String instanceType = (String) type.get("instanceType");
if (!instanceTypeNames.contains(instanceType) && !everyFilterAdmits(typeFilters, instanceType)) {
continue;
}
for (String location : locations) {
if (locationFilter != null && !matchesValue(location, locationFilter)) {
if (!everyFilterMatches(locationFilters, location)) {
continue;
}
Map<String, String> offering = new LinkedHashMap<>();
@@ -11551,6 +11737,52 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// ─── Filter matching ───────────────────────────────────────────────────────
/**
* Filters of distinct names, as the Map overloads of the Describe methods take them from code
* that builds its own. A request's Filter.N reaches the list overloads instead, in request
* order: every filter is joined with an AND and a name may repeat, which a map, holding one
* filter per name, cannot carry.
*/
private static List<Map.Entry<String, List<String>>> filterList(Map<String, List<String>> filters) {
return filters == null ? List.of() : List.copyOf(filters.entrySet());
}
private static List<String> filterNames(List<Map.Entry<String, List<String>>> filters) {
return filters.stream().map(Map.Entry::getKey).toList();
}
/** The values of every filter named {@code name}, in request order. */
static List<List<String>> filterValues(List<Map.Entry<String, List<String>>> filters, String name) {
if (filters == null) {
return List.of();
}
return filters.stream()
.filter(filter -> name.equals(filter.getKey()))
.map(Map.Entry::getValue)
.toList();
}
/**
* Whether every one of {@code filters} admits {@code value}, as the image matchers test a
* filter. A filter without values admits anything.
*/
static boolean everyFilterAdmits(List<List<String>> filters, String value) {
return filters.stream().allMatch(values -> matchesFilterValue(values, value));
}
/** Whether every one of {@code filters} names {@code value} exactly. A filter without values admits anything. */
static boolean everyFilterContains(List<List<String>> filters, String value) {
return filters.stream().allMatch(values -> values.isEmpty() || values.contains(value));
}
/**
* Whether {@code value} matches a value of every one of {@code filters}, wildcards included, as
* {@link #matchesValue(String, List)} tests one. A filter without values matches nothing.
*/
private boolean everyFilterMatches(List<List<String>> filters, String value) {
return filters.stream().allMatch(values -> matchesValue(value, values));
}
private boolean matchesValue(String resourceValue, List<String> filterValues) {
String normalizedResourceValue = Objects.toString(resourceValue, "");
return filterValues.stream()
@@ -11598,11 +11830,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.anyMatch(pattern -> normalizedValue.matches(wildcardToRegex(pattern)));
}
private boolean matchesFilters(Object resource, Map<String, List<String>> filters, String region) {
private boolean matchesFilters(Object resource, List<Map.Entry<String, List<String>>> filters, String region) {
if (filters == null || filters.isEmpty()) {
return true;
}
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
for (Map.Entry<String, List<String>> filter : filters) {
String name = filter.getKey();
List<String> values = filter.getValue();
if (!matchesFilter(resource, name, values, region)) {
@@ -12062,6 +12294,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<Volume> describeVolumes(String region, List<String> volumeIds,
Map<String, List<String>> filters) {
return describeVolumes(region, volumeIds, filterList(filters));
}
List<Volume> describeVolumes(String region, List<String> volumeIds,
List<Map.Entry<String, List<String>>> filters) {
if (volumeIds != null && !volumeIds.isEmpty()) {
for (String id : volumeIds) {
if (volumes.get(key(region, id)).orElse(null) == null) {
@@ -12305,6 +12542,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<VolumeModification> describeVolumesModifications(String region, List<String> volumeIds,
Map<String, List<String>> filters) {
return describeVolumesModifications(region, volumeIds, filterList(filters));
}
List<VolumeModification> describeVolumesModifications(String region, List<String> volumeIds,
List<Map.Entry<String, List<String>>> filters) {
if (volumeIds != null && !volumeIds.isEmpty()) {
for (String id : volumeIds) {
if (volumeModifications.get(key(region, id)).isEmpty()) {
@@ -12445,25 +12687,40 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public NetworkInterfaceListResult describeNetworkInterfaces(String region, List<String> networkInterfaceIds,
Map<String, List<String>> filters) {
return describeNetworkInterfaces(callerAccountId(), region, networkInterfaceIds, filters, 0, null);
return describeNetworkInterfaces(callerAccountId(), region, networkInterfaceIds, filterList(filters), 0, null);
}
public NetworkInterfaceListResult describeNetworkInterfaces(String region, List<String> networkInterfaceIds,
Map<String, List<String>> filters,
int maxResults, String nextToken) {
return describeNetworkInterfaces(callerAccountId(), region, networkInterfaceIds, filterList(filters),
maxResults, nextToken);
}
NetworkInterfaceListResult describeNetworkInterfaces(String region, List<String> networkInterfaceIds,
List<Map.Entry<String, List<String>>> filters,
int maxResults, String nextToken) {
return describeNetworkInterfaces(callerAccountId(), region, networkInterfaceIds, filters, maxResults, nextToken);
}
public NetworkInterfaceListResult describeNetworkInterfaces(String accountId, String region,
List<String> networkInterfaceIds,
Map<String, List<String>> filters) {
return describeNetworkInterfaces(accountId, region, networkInterfaceIds, filters, 0, null);
return describeNetworkInterfaces(accountId, region, networkInterfaceIds, filterList(filters), 0, null);
}
public NetworkInterfaceListResult describeNetworkInterfaces(String accountId, String region,
List<String> networkInterfaceIds,
Map<String, List<String>> filters,
int maxResults, String nextToken) {
return describeNetworkInterfaces(accountId, region, networkInterfaceIds, filterList(filters),
maxResults, nextToken);
}
NetworkInterfaceListResult describeNetworkInterfaces(String accountId, String region,
List<String> networkInterfaceIds,
List<Map.Entry<String, List<String>>> filters,
int maxResults, String nextToken) {
// Validate pagination parameters
if (maxResults > 0 && !networkInterfaceIds.isEmpty()) {
throw new AwsException("InvalidParameterCombination",
@@ -13163,6 +13420,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<SpotInstanceRequest> describeSpotInstanceRequests(String region, List<String> spotRequestIds, Map<String, List<String>> filters) {
return describeSpotInstanceRequests(region, spotRequestIds, filterList(filters));
}
List<SpotInstanceRequest> describeSpotInstanceRequests(String region, List<String> spotRequestIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
if (!spotRequestIds.isEmpty()) {
@@ -13209,8 +13471,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
Instant startTime,
Instant endTime,
Map<String, List<String>> filters) {
validateSpotPriceHistory(productDescriptions, availabilityZone, availabilityZoneId, startTime, endTime,
filterList(filters));
}
void validateSpotPriceHistory(List<String> productDescriptions,
String availabilityZone,
String availabilityZoneId,
Instant startTime,
Instant endTime,
List<Map.Entry<String, List<String>>> filters) {
if (filters != null && !filters.isEmpty()) {
requireSupportedFilters(filters.keySet(), SPOT_PRICE_HISTORY_FILTERS);
requireSupportedFilters(filterNames(filters), SPOT_PRICE_HISTORY_FILTERS);
}
if (productDescriptions != null) {
for (String desc : productDescriptions) {
@@ -13245,6 +13517,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
Map<String, List<String>> filters,
int maxResults,
String nextToken) {
return describeSpotPriceHistory(region, instanceTypes, productDescriptions, availabilityZone,
availabilityZoneId, startTime, endTime, filterList(filters), maxResults, nextToken);
}
SpotPriceHistoryResult describeSpotPriceHistory(String region,
List<String> instanceTypes,
List<String> productDescriptions,
String availabilityZone,
String availabilityZoneId,
Instant startTime,
Instant endTime,
List<Map.Entry<String, List<String>>> filters,
int maxResults,
String nextToken) {
ensureDefaultResources(region);
validateSpotPriceHistory(productDescriptions, availabilityZone, availabilityZoneId, startTime, endTime, filters);
@@ -13272,14 +13558,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.filter(z -> availabilityZoneId.equals(z.get("zoneId")))
.toList();
}
if (filters != null && filters.containsKey("availability-zone")) {
List<String> azFilter = filters.get("availability-zone");
for (List<String> azFilter : filterValues(filters, "availability-zone")) {
zones = zones.stream()
.filter(z -> matchesValue(z.get("zoneName"), azFilter))
.toList();
}
if (filters != null && filters.containsKey("availability-zone-id")) {
List<String> azIdFilter = filters.get("availability-zone-id");
for (List<String> azIdFilter : filterValues(filters, "availability-zone-id")) {
zones = zones.stream()
.filter(z -> matchesValue(z.get("zoneId"), azIdFilter))
.toList();
@@ -13298,8 +13582,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.filter(t -> t.supportedUsageClasses.contains("spot"))
.toList();
}
if (filters != null && filters.containsKey("instance-type")) {
List<String> itFilter = filters.get("instance-type");
for (List<String> itFilter : filterValues(filters, "instance-type")) {
catalogTypes = catalogTypes.stream()
.filter(t -> matchesValue(t.instanceType, itFilter))
.toList();
@@ -13312,18 +13595,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.filter(requested::contains)
.toList();
}
if (filters != null && filters.containsKey("product-description")) {
List<String> pdFilter = filters.get("product-description");
for (List<String> pdFilter : filterValues(filters, "product-description")) {
targetProductDescs = targetProductDescs.stream()
.filter(pd -> matchesValue(pd, pdFilter))
.toList();
}
List<String> priceFilter = filters != null ? filters.get("spot-price") : null;
List<String> timestampFilter = filters != null ? filters.get("timestamp") : null;
List<List<String>> priceFilters = filterValues(filters, "spot-price");
String formattedTimestamp = ISO_FMT.format(effectiveTimestamp);
if (timestampFilter != null && !matchesValue(formattedTimestamp, timestampFilter)) {
if (!everyFilterMatches(filterValues(filters, "timestamp"), formattedTimestamp)) {
return new SpotPriceHistoryResult(List.of(), null);
}
@@ -13337,7 +13618,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
double priceVal = ((type.vcpu * 0.0016) + ((type.memoryMib / 1024.0) * 0.0012)) * multiplier;
String formattedPrice = String.format(Locale.ROOT, "%.6f", priceVal);
if (priceFilter != null && !matchesValue(formattedPrice, priceFilter)) {
if (!everyFilterMatches(priceFilters, formattedPrice)) {
continue;
}
@@ -212,7 +212,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest {
"x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex())));
String keptSnapshot = snapshotIdOf(kept);
service.deregisterImage(EAST, kept.getImageId(), false);
assertEquals(1, service.describeSnapshots(EAST, List.of(keptSnapshot), null, null).size());
assertEquals(1, service.describeSnapshots(EAST, List.of(keptSnapshot), null, Map.of()).size());
Image deleted = service.registerImage(EAST, uniqueName("floci-delete-snapshots"), null,
"x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex())));
@@ -221,7 +221,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest {
service.deregisterImage(EAST, deleted.getImageId(), true);
assertEquals(List.of(new Ec2Service.SnapshotDeletion(deletedSnapshot, "success")), results);
assertThrows(AwsException.class,
() -> service.describeSnapshots(EAST, List.of(deletedSnapshot), null, null));
() -> service.describeSnapshots(EAST, List.of(deletedSnapshot), null, Map.of()));
}
@Test
@@ -250,7 +250,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest {
service.deregisterImage(EAST, first.getImageId(), true);
assertEquals(List.of(new Ec2Service.SnapshotDeletion(snapshotId, "skipped")), results);
assertEquals(1, service.describeSnapshots(EAST, List.of(snapshotId), null, null).size());
assertEquals(1, service.describeSnapshots(EAST, List.of(snapshotId), null, Map.of()).size());
assertTrue(service.describeImages(EAST, List.of(first.getImageId()), null).isEmpty(),
"the AMI is still deregistered even when its snapshot is kept");
}
@@ -317,8 +317,8 @@ class Ec2DeregisterAndCopyImageIntegrationTest {
uniqueName("floci-copy-snap-dst"), null);
assertNotEquals(snapshotIdOf(source), snapshotIdOf(copy));
assertEquals(1, service.describeSnapshots(WEST, List.of(snapshotIdOf(copy)), null, null).size());
assertEquals(1, service.describeSnapshots(EAST, List.of(snapshotIdOf(source)), null, null).size());
assertEquals(1, service.describeSnapshots(WEST, List.of(snapshotIdOf(copy)), null, Map.of()).size());
assertEquals(1, service.describeSnapshots(EAST, List.of(snapshotIdOf(source)), null, Map.of()).size());
}
@Test
@@ -0,0 +1,256 @@
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.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Filter.N with one name given more than once, over the wire. AWS joins every filter with an AND,
* so each repeated name narrows the answer, instead of the last filter of a name replacing the
* ones before it.
*/
@QuarkusTest
class Ec2RepeatedFilterNamesIntegrationTest {
/** An account of its own, so nothing another test creates shows up in these answers. */
private static final String ACCOUNT = "246813579135";
private static final String AMI = "ami-0abcdef1234567890";
private static RequestSpecification request(String service, String action, String... params) {
RequestSpecification request = given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
+ "/20261021/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc")
.formParam("Action", action);
for (int i = 0; i < params.length; i += 2) {
request = request.formParam(params[i], params[i + 1]);
}
return request;
}
private static XmlPath ec2(String action, String... params) {
return request("ec2", action, params).when().post("/").then().statusCode(200).extract().xmlPath();
}
private static String[] filter(String name, String... values) {
String[] filter = new String[values.length + 1];
filter[0] = name;
System.arraycopy(values, 0, filter, 1, values.length);
return filter;
}
private static XmlPath describe(String action, List<String> params, String[]... filters) {
List<String> all = new ArrayList<>(params);
for (int i = 0; i < filters.length; i++) {
all.add("Filter." + (i + 1) + ".Name");
all.add(filters[i][0]);
for (int j = 1; j < filters[i].length; j++) {
all.add("Filter." + (i + 1) + ".Value." + j);
all.add(filters[i][j]);
}
}
return ec2(action, all.toArray(String[]::new));
}
private static Set<String> values(XmlPath xml, String path) {
return new LinkedHashSet<>(xml.getList(path, String.class));
}
private static String unique(String prefix) {
return prefix + UUID.randomUUID().toString().substring(0, 8);
}
private static String runInstance(String... tagKeys) {
List<String> params = new ArrayList<>(List.of("ImageId", AMI, "InstanceType", "t3.micro",
"MinCount", "1", "MaxCount", "1"));
if (tagKeys.length > 0) {
params.addAll(List.of("TagSpecification.1.ResourceType", "instance"));
for (int i = 0; i < tagKeys.length; i++) {
params.addAll(List.of("TagSpecification.1.Tag." + (i + 1) + ".Key", tagKeys[i],
"TagSpecification.1.Tag." + (i + 1) + ".Value", "v"));
}
}
return ec2("RunInstances", params.toArray(String[]::new))
.getString("RunInstancesResponse.instancesSet.item.instanceId");
}
private static String createVpc(String cidr) {
return ec2("CreateVpc", "CidrBlock", cidr).getString("CreateVpcResponse.vpc.vpcId");
}
private static String createSubnet(String vpcId, String cidr) {
return ec2("CreateSubnet", "VpcId", vpcId, "CidrBlock", cidr)
.getString("CreateSubnetResponse.subnet.subnetId");
}
private static String createSecurityGroup(String vpcId) {
return ec2("CreateSecurityGroup", "GroupName", unique("repeated-"), "GroupDescription", "repeated filters",
"VpcId", vpcId).getString("CreateSecurityGroupResponse.groupId");
}
@Test
void describeInstancesAndsTwoTagKeyFilters() {
String only = unique("RepeatedOnly");
String shared = unique("RepeatedShared");
String both = runInstance(only, shared);
String one = runInstance(shared);
String path = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId";
assertEquals(Set.of(both, one), values(describe("DescribeInstances", List.of(),
filter("tag-key", shared)), path));
assertEquals(Set.of(both), values(describe("DescribeInstances", List.of(),
filter("tag-key", only), filter("tag-key", shared)), path));
assertEquals(Set.of(both), values(describe("DescribeInstances", List.of(),
filter("tag-key", shared), filter("tag-key", only)), path));
}
@Test
void describeSubnetsInTwoVpcsAtOnceFindsNone() {
String first = createVpc("10.161.0.0/16");
String second = createVpc("10.162.0.0/16");
createSubnet(first, "10.161.1.0/24");
String secondSubnet = createSubnet(second, "10.162.1.0/24");
String path = "DescribeSubnetsResponse.subnetSet.item.subnetId";
assertEquals(Set.of(secondSubnet), values(describe("DescribeSubnets", List.of(),
filter("vpc-id", second)), path));
assertEquals(Set.of(), values(describe("DescribeSubnets", List.of(),
filter("vpc-id", first), filter("vpc-id", second)), path));
assertEquals(Set.of(secondSubnet), values(describe("DescribeSubnets", List.of(),
filter("vpc-id", first, second), filter("vpc-id", second)), path));
}
@Test
void describeVpcsAndsTwoTagFiltersOfOneKey() {
String key = unique("Stage");
String prod = createVpc("10.163.0.0/16");
String dev = createVpc("10.164.0.0/16");
ec2("CreateTags", "ResourceId.1", prod, "Tag.1.Key", key, "Tag.1.Value", "prod");
ec2("CreateTags", "ResourceId.1", dev, "Tag.1.Key", key, "Tag.1.Value", "dev");
String path = "DescribeVpcsResponse.vpcSet.item.vpcId";
assertEquals(Set.of(prod), values(describe("DescribeVpcs", List.of(),
filter("tag:" + key, "prod", "dev"), filter("tag:" + key, "prod")), path));
assertEquals(Set.of(), values(describe("DescribeVpcs", List.of(),
filter("tag:" + key, "prod"), filter("tag:" + key, "dev")), path));
}
@Test
void describeNetworkAclsInTwoVpcsAtOnceFindsNone() {
String first = createVpc("10.165.0.0/16");
String second = createVpc("10.166.0.0/16");
String path = "DescribeNetworkAclsResponse.networkAclSet.item.networkAclId";
assertEquals(1, values(describe("DescribeNetworkAcls", List.of(), filter("vpc-id", second)), path).size());
assertEquals(Set.of(), values(describe("DescribeNetworkAcls", List.of(),
filter("vpc-id", first), filter("vpc-id", second)), path));
}
@Test
void describeSecurityGroupRulesOfTwoGroupsAtOnceFindsNone() {
String vpc = createVpc("10.167.0.0/16");
String first = createSecurityGroup(vpc);
String second = createSecurityGroup(vpc);
String path = "DescribeSecurityGroupRulesResponse.securityGroupRuleSet.item.securityGroupRuleId";
Set<String> secondRules = values(describe("DescribeSecurityGroupRules", List.of(),
filter("group-id", second)), path);
assertTrue(!secondRules.isEmpty(), "a new group carries its default egress rule");
assertEquals(Set.of(), values(describe("DescribeSecurityGroupRules", List.of(),
filter("group-id", first), filter("group-id", second)), path));
}
@Test
void describeImagesAndsTwoNamePatterns() {
String path = "DescribeImagesResponse.imagesSet.item.name";
Set<String> arm = values(describe("DescribeImages", List.of(), filter("name", "*arm64*")), path);
Set<String> both = values(describe("DescribeImages", List.of(),
filter("name", "al2023-ami-*"), filter("name", "*arm64*")), path);
assertTrue(!both.isEmpty() && arm.containsAll(both) && both.size() < arm.size(), both + " of " + arm);
assertTrue(both.stream().allMatch(name -> name.startsWith("al2023-ami-")), both.toString());
assertEquals(Set.of(), values(describe("DescribeImages", List.of(),
filter("name", "repeated-first-*"), filter("name", "repeated-second-*")), path));
}
@Test
void describeIamInstanceProfileAssociationsOfTwoInstancesAtOnceFindsNone() {
String profile = unique("repeated-filters-");
request("iam", "CreateInstanceProfile", "InstanceProfileName", profile)
.post("/").then().statusCode(200);
String first = runInstance();
String second = runInstance();
for (String instance : List.of(first, second)) {
ec2("AssociateIamInstanceProfile", "InstanceId", instance, "IamInstanceProfile.Name", profile);
}
String path = "DescribeIamInstanceProfileAssociationsResponse.iamInstanceProfileAssociationSet.item.instanceId";
assertEquals(Set.of(second), values(describe("DescribeIamInstanceProfileAssociations", List.of(),
filter("instance-id", second)), path));
assertEquals(Set.of(), values(describe("DescribeIamInstanceProfileAssociations", List.of(),
filter("instance-id", first), filter("instance-id", second)), path));
}
@Test
void describeInstanceTypeOfferingsAndsTwoInstanceTypeFilters() {
String path = "DescribeInstanceTypeOfferingsResponse.instanceTypeOfferingSet.item.instanceType";
List<String> region = List.of("LocationType", "region");
assertEquals(Set.of("t3.micro"), values(describe("DescribeInstanceTypeOfferings", region,
filter("instance-type", "t3.micro", "m5.large"), filter("instance-type", "t3.micro")), path));
assertEquals(Set.of(), values(describe("DescribeInstanceTypeOfferings", region,
filter("instance-type", "m5.large"), filter("instance-type", "t3.micro")), path));
}
@Test
void describeSpotPriceHistoryAndsTwoAvailabilityZoneFilters() {
String path = "DescribeSpotPriceHistoryResponse.spotPriceHistorySet.item.availabilityZone";
assertEquals(Set.of("us-east-1b"), values(describe("DescribeSpotPriceHistory", List.of(),
filter("instance-type", "t3.micro"), filter("availability-zone", "us-east-1b")), path));
assertEquals(Set.of(), values(describe("DescribeSpotPriceHistory", List.of(),
filter("instance-type", "t3.micro"), filter("availability-zone", "us-east-1a"),
filter("availability-zone", "us-east-1b")), path));
}
@Test
void searchTransitGatewayRoutesAndsTwoExactMatchFilters() {
String gateway = ec2("CreateTransitGateway").getString("CreateTransitGatewayResponse.transitGateway.transitGatewayId");
String routeTable = ec2("CreateTransitGatewayRouteTable", "TransitGatewayId", gateway)
.getString("CreateTransitGatewayRouteTableResponse.transitGatewayRouteTable.transitGatewayRouteTableId");
for (String cidr : List.of("10.168.0.0/16", "10.169.0.0/16")) {
ec2("CreateTransitGatewayRoute", "TransitGatewayRouteTableId", routeTable,
"DestinationCidrBlock", cidr, "Blackhole", "true");
}
String path = "SearchTransitGatewayRoutesResponse.routeSet.item.destinationCidrBlock";
List<String> table = List.of("TransitGatewayRouteTableId", routeTable);
assertEquals(Set.of("10.169.0.0/16"), values(describe("SearchTransitGatewayRoutes", table,
filter("route-search.exact-match", "10.169.0.0/16")), path));
assertEquals(Set.of(), values(describe("SearchTransitGatewayRoutes", table,
filter("route-search.exact-match", "10.168.0.0/16"),
filter("route-search.exact-match", "10.169.0.0/16")), path));
}
@Test
void describePrefixListsAndsTwoNameFilters() {
String s3 = "com.amazonaws.us-east-1.s3";
String dynamodb = "com.amazonaws.us-east-1.dynamodb";
String path = "DescribePrefixListsResponse.prefixListSet.item.prefixListName";
assertEquals(Set.of(dynamodb), values(describe("DescribePrefixLists", List.of(),
filter("prefix-list-name", s3, dynamodb), filter("prefix-list-name", dynamodb)), path));
assertEquals(Set.of(), values(describe("DescribePrefixLists", List.of(),
filter("prefix-list-name", s3), filter("prefix-list-name", dynamodb)), path));
}
}
@@ -0,0 +1,751 @@
package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Filter.N with one name given more than once, sent through the Query handler to a real service.
* AWS joins every filter with an AND, so a repeated name narrows the answer as a second filter of
* another name would, rather than replacing the filter before it.
*/
class Ec2RepeatedFilterNamesTest {
private static final String REGION = "us-east-1";
private static final String AMI = "ami-0abcdef1234567890";
private Ec2Service service;
private Ec2QueryHandler handler;
private int sequence;
private String vpcId;
private String subnetId;
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(true);
when(ec2.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
when(ec2.mockPublicAddress()).thenReturn(Optional.empty());
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
service = new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
new AmiImageResolver(imageCatalog), imageCatalog, new Ec2InstanceTypeCatalog(), new MemoryFactory());
handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class),
mock(Ec2EbsEncryptionService.class), mock(Ec2SnapshotBlockPublicAccessService.class),
mock(Ec2IpamService.class), new RegionResolver(REGION, "000000000000"));
}
/**
* Resources a tag filter reaches through the shared matcher, each with the action that lists
* them and the element that carries their id.
*/
enum Tagged {
INSTANCE("DescribeInstances", "instanceId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.runInstance();
}
},
VPC("DescribeVpcs", "vpcId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newVpc();
}
},
SUBNET("DescribeSubnets", "subnetId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateSubnet", "VpcId", t.vpc(), "CidrBlock", t.nextSubnetCidr()), "subnetId");
}
},
SECURITY_GROUP("DescribeSecurityGroups", "groupId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newSecurityGroup();
}
},
SECURITY_GROUP_FOR_VPC("GetSecurityGroupsForVpc", "groupId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newSecurityGroup();
}
@Override
List<String> describeParams(Ec2RepeatedFilterNamesTest t) {
return List.of("VpcId", t.vpc());
}
},
INTERNET_GATEWAY("DescribeInternetGateways", "internetGatewayId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateInternetGateway"), "internetGatewayId");
}
},
EGRESS_ONLY_INTERNET_GATEWAY("DescribeEgressOnlyInternetGateways", "egressOnlyInternetGatewayId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateEgressOnlyInternetGateway", "VpcId", t.newVpc()),
"egressOnlyInternetGatewayId");
}
},
ROUTE_TABLE("DescribeRouteTables", "routeTableId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateRouteTable", "VpcId", t.vpc()), "routeTableId");
}
},
ADDRESS("DescribeAddresses", "allocationId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newAddress();
}
},
VOLUME("DescribeVolumes", "volumeId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newVolume();
}
},
MANAGED_PREFIX_LIST("DescribeManagedPrefixLists", "prefixListId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateManagedPrefixList", "PrefixListName", "repeated-" + t.next(),
"AddressFamily", "IPv4", "MaxEntries", "5"), "prefixListId");
}
},
LAUNCH_TEMPLATE("DescribeLaunchTemplates", "launchTemplateId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateLaunchTemplate", "LaunchTemplateName", "repeated-" + t.next(),
"LaunchTemplateData.InstanceType", "t3.micro"), "launchTemplateId");
}
},
VPC_ENDPOINT("DescribeVpcEndpoints", "vpcEndpointId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateVpcEndpoint", "VpcId", t.vpc(),
"ServiceName", "com.amazonaws.us-east-1.s3"), "vpcEndpointId");
}
},
NAT_GATEWAY("DescribeNatGateways", "natGatewayId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateNatGateway", "SubnetId", t.subnet(),
"AllocationId", t.newAddress()), "natGatewayId");
}
},
SPOT_INSTANCE_REQUEST("DescribeSpotInstanceRequests", "spotInstanceRequestId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("RequestSpotInstances", "InstanceCount", "1",
"LaunchSpecification.ImageId", AMI, "LaunchSpecification.InstanceType", "t3.micro"),
"spotInstanceRequestId");
}
},
TRANSIT_GATEWAY("DescribeTransitGateways", "transitGatewayId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newTransitGateway();
}
},
TRANSIT_GATEWAY_ROUTE_TABLE("DescribeTransitGatewayRouteTables", "transitGatewayRouteTableId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateTransitGatewayRouteTable", "TransitGatewayId", t.newTransitGateway()),
"transitGatewayRouteTableId");
}
},
TRANSIT_GATEWAY_VPC_ATTACHMENT("DescribeTransitGatewayVpcAttachments", "transitGatewayAttachmentId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newVpcAttachment(t.newTransitGateway());
}
},
TRANSIT_GATEWAY_ATTACHMENT("DescribeTransitGatewayAttachments", "transitGatewayAttachmentId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.newVpcAttachment(t.newTransitGateway());
}
},
TRANSIT_GATEWAY_PEERING_ATTACHMENT("DescribeTransitGatewayPeeringAttachments", "transitGatewayAttachmentId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateTransitGatewayPeeringAttachment",
"TransitGatewayId", t.newTransitGateway(), "PeerTransitGatewayId", t.newTransitGateway(),
"PeerAccountId", "000000000000", "PeerRegion", REGION), "transitGatewayAttachmentId");
}
},
VPC_PEERING_CONNECTION("DescribeVpcPeeringConnections", "vpcPeeringConnectionId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateVpcPeeringConnection", "VpcId", t.newVpc(), "PeerVpcId", t.newVpc()),
"vpcPeeringConnectionId");
}
},
CAPACITY_RESERVATION("DescribeCapacityReservations", "capacityReservationId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("CreateCapacityReservation", "InstanceType", "t3.micro",
"InstancePlatform", "Linux/UNIX", "AvailabilityZone", "us-east-1a", "InstanceCount", "1"),
"capacityReservationId");
}
},
HOST("DescribeHosts", "hostId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("AllocateHosts", "AvailabilityZone", "us-east-1a",
"InstanceType", "m5.large", "Quantity", "1"), "item");
}
},
IMAGE("DescribeImages", "imageId") {
@Override
String create(Ec2RepeatedFilterNamesTest t) {
return t.first(t.ok("RegisterImage", "Name", "repeated-" + t.next(),
"RootDeviceName", "/dev/xvda",
"BlockDeviceMapping.1.DeviceName", "/dev/xvda",
"BlockDeviceMapping.1.Ebs.VolumeSize", "8"), "imageId");
}
};
private final String describeAction;
private final String idElement;
Tagged(String describeAction, String idElement) {
this.describeAction = describeAction;
this.idElement = idElement;
}
abstract String create(Ec2RepeatedFilterNamesTest t);
List<String> describeParams(Ec2RepeatedFilterNamesTest t) {
return List.of();
}
}
@ParameterizedTest
@EnumSource(Tagged.class)
void tagKeyFiltersOfOneNameAreAnded(Tagged type) {
String both = type.create(this);
String one = type.create(this);
ok("CreateTags", "ResourceId.1", both, "ResourceId.2", one, "Tag.1.Key", "RepeatedShared");
ok("CreateTags", "ResourceId.1", both, "Tag.1.Key", "RepeatedOnly");
assertEquals(Set.of(both, one), described(type, filter("tag-key", "RepeatedShared")));
assertEquals(Set.of(both), described(type, filter("tag-key", "RepeatedOnly")));
assertEquals(Set.of(both), described(type,
filter("tag-key", "RepeatedOnly"), filter("tag-key", "RepeatedShared")));
assertEquals(Set.of(both), described(type,
filter("tag-key", "RepeatedShared"), filter("tag-key", "RepeatedOnly")));
}
@Test
void tagFiltersOfOneKeyMustAllMatchTheValue() {
String prod = runInstance();
String dev = runInstance();
ok("CreateTags", "ResourceId.1", prod, "Tag.1.Key", "Stage", "Tag.1.Value", "prod");
ok("CreateTags", "ResourceId.1", dev, "Tag.1.Key", "Stage", "Tag.1.Value", "dev");
assertEquals(Set.of(prod), ids(describe("DescribeInstances",
filter("tag:Stage", "prod"), filter("tag:Stage", "prod", "dev")), "instanceId"));
assertEquals(Set.of(), ids(describe("DescribeInstances",
filter("tag:Stage", "prod"), filter("tag:Stage", "dev")), "instanceId"));
}
@Test
void subnetsAndRouteTablesInTwoVpcsAtOnceAreNone() {
String first = vpc();
String second = newVpc();
ok("CreateSubnet", "VpcId", first, "CidrBlock", nextSubnetCidr());
String secondSubnet = first(ok("CreateSubnet", "VpcId", second,
"CidrBlock", cidrOf(second).replace(".0.0/16", ".1.0/24")), "subnetId");
assertEquals(Set.of(secondSubnet), ids(describe("DescribeSubnets",
filter("vpc-id", second)), "subnetId"));
assertEquals(Set.of(), ids(describe("DescribeSubnets",
filter("vpc-id", first), filter("vpc-id", second)), "subnetId"));
assertEquals(Set.of(), ids(describe("DescribeRouteTables",
filter("vpc-id", first), filter("vpc-id", second)), "routeTableId"));
assertEquals(Set.of(), ids(describe("DescribeSecurityGroups",
filter("vpc-id", first), filter("vpc-id", second)), "groupId"));
}
@Test
void vpcsWithTwoCidrFiltersMatchOnlyBoth() {
String vpc = newVpc();
assertEquals(Set.of(vpc), ids(describe("DescribeVpcs",
filter("cidr", cidrOf(vpc)), filter("vpc-id", vpc)), "vpcId"));
assertEquals(Set.of(), ids(describe("DescribeVpcs",
filter("cidr", "10.249.0.0/16"), filter("cidr", cidrOf(vpc))), "vpcId"));
}
@Test
void networkAclsInTwoVpcsAtOnceAreNone() {
String first = vpc();
String second = newVpc();
String secondAcl = first(ok("CreateNetworkAcl", "VpcId", second), "networkAclId");
assertTrue(ids(describe("DescribeNetworkAcls", filter("vpc-id", second)), "networkAclId")
.contains(secondAcl));
assertEquals(Set.of(), ids(describe("DescribeNetworkAcls",
filter("vpc-id", first), filter("vpc-id", second)), "networkAclId"));
assertEquals(Set.of(secondAcl), ids(describe("DescribeNetworkAcls",
filter("default", "false"), filter("vpc-id", second)), "networkAclId"));
}
@Test
void snapshotsMatchEveryFilter() {
String first = "snap-0123456789abcdef1";
String second = "snap-0123456789abcdef2";
registerImageWithSnapshot(first, "8");
registerImageWithSnapshot(second, "16");
assertEquals(Set.of(second), ids(describe("DescribeSnapshots",
filter("snapshot-id", second)), "snapshotId"));
assertEquals(Set.of(), ids(describe("DescribeSnapshots",
filter("snapshot-id", first), filter("snapshot-id", second)), "snapshotId"));
assertEquals(Set.of(), ids(describe("DescribeSnapshots",
filter("volume-size", "8"), filter("volume-size", "16")), "snapshotId"));
}
@Test
void volumeModificationsOfTwoVolumesAtOnceAreNone() {
String firstVolume = newVolume();
String secondVolume = newVolume();
ok("ModifyVolume", "VolumeId", firstVolume, "Size", "16");
ok("ModifyVolume", "VolumeId", secondVolume, "Size", "16");
assertEquals(Set.of(secondVolume), ids(describe("DescribeVolumesModifications",
filter("volume-id", secondVolume)), "volumeId"));
assertEquals(Set.of(), ids(describe("DescribeVolumesModifications",
filter("volume-id", firstVolume), filter("volume-id", secondVolume)), "volumeId"));
}
@Test
void catalogImagesMatchEveryNamePattern() {
Set<String> amazonLinux = names(describe("DescribeImages", filter("name", "al2023-ami-*")));
Set<String> arm = names(describe("DescribeImages", filter("name", "*arm64*")));
Set<String> both = new LinkedHashSet<>(amazonLinux);
both.retainAll(arm);
assertTrue(!both.isEmpty() && both.size() < arm.size(),
"the catalog needs an image matching both patterns and one matching only the second: " + arm);
assertEquals(both, names(describe("DescribeImages",
filter("name", "al2023-ami-*"), filter("name", "*arm64*"))));
}
@Test
void aLookupImageIsSynthesizedOnlyWhenItSatisfiesEveryNameFilter() {
for (List<String[]> filters : List.of(
List.of(filter("name", "repeated-lookup-*-x86_64"), filter("name", "repeated-lookup-*")),
List.of(filter("name", "repeated-lookup-*"), filter("name", "repeated-lookup-*-x86_64")))) {
Set<String> synthesized = names(describe("DescribeImages", filters.toArray(String[][]::new)));
assertEquals(1, synthesized.size(), synthesized.toString());
String name = synthesized.iterator().next();
assertTrue(name.startsWith("repeated-lookup-") && name.endsWith("-x86_64"), name);
}
assertEquals(Set.of(), names(describe("DescribeImages",
filter("name", "repeated-first-*"), filter("name", "repeated-second-*"))));
// Patterns that overlap, but the name built from either one breaks the other: no image is
// made up, as AWS returns only images that exist.
assertEquals(Set.of(), names(describe("DescribeImages",
filter("name", "foo-*"), filter("name", "*-bar-*"))));
}
@Test
void aLookupImageTakesTheValueEveryFilterOfANameAdmits() {
String xml = describe("DescribeImages", filter("name", "repeated-scalar-*"),
filter("architecture", "x86_64", "arm64"), filter("architecture", "arm64"),
filter("owner-id", "111111111111", "222222222222"), filter("owner-id", "222222222222"),
filter("state", "available", "pending"), filter("state", "pending"));
assertEquals(1, names(xml).size(), xml);
assertEquals(Set.of("arm64"), ids(xml, "architecture"));
assertEquals(Set.of("222222222222"), ids(xml, "imageOwnerId"));
assertEquals(Set.of("pending"), ids(xml, "imageState"));
}
@Test
void securityGroupRulesOfTwoGroupsAtOnceAreNone() {
String first = newSecurityGroup();
String second = newSecurityGroup();
Set<String> secondRules = ids(describe("DescribeSecurityGroupRules", filter("group-id", second)),
"securityGroupRuleId");
assertTrue(!secondRules.isEmpty(), "a new group carries its default egress rule");
assertEquals(Set.of(), ids(describe("DescribeSecurityGroupRules",
filter("group-id", first), filter("group-id", second)), "securityGroupRuleId"));
String rule = secondRules.iterator().next();
assertEquals(Set.of(), ids(describe("DescribeSecurityGroupRules",
filter("security-group-rule-id", "sgr-00000000000000000"),
filter("security-group-rule-id", rule)), "securityGroupRuleId"));
assertEquals(Set.of(rule), ids(describe("DescribeSecurityGroupRules",
filter("security-group-rule-id", rule), filter("group-id", first, second),
filter("group-id", second)), "securityGroupRuleId"));
}
@Test
void networkInterfacesInTwoSubnetsAtOnceAreNone() {
String first = subnet();
String second = first(ok("CreateSubnet", "VpcId", vpc(), "CidrBlock", nextSubnetCidr()), "subnetId");
ok("CreateNetworkInterface", "SubnetId", first);
String secondInterface = first(ok("CreateNetworkInterface", "SubnetId", second), "networkInterfaceId");
assertEquals(Set.of(secondInterface), ids(describe("DescribeNetworkInterfaces",
filter("subnet-id", second)), "networkInterfaceId"));
assertEquals(Set.of(), ids(describe("DescribeNetworkInterfaces",
filter("subnet-id", first), filter("subnet-id", second)), "networkInterfaceId"));
}
@Test
void instanceCreditSpecificationsOfTwoInstancesAtOnceAreNone() {
String first = runInstance();
String second = runInstance();
assertEquals(Set.of(second), ids(describe("DescribeInstanceCreditSpecifications",
filter("instance-id", second)), "instanceId"));
assertEquals(Set.of(), ids(describe("DescribeInstanceCreditSpecifications",
filter("instance-id", first), filter("instance-id", second)), "instanceId"));
}
@Test
void awsManagedPrefixListsOfTwoNamesAtOnceAreNone() {
String s3 = "com.amazonaws.us-east-1.s3";
String dynamodb = "com.amazonaws.us-east-1.dynamodb";
assertEquals(Set.of(dynamodb), ids(describe("DescribePrefixLists",
filter("prefix-list-name", dynamodb)), "prefixListName"));
assertEquals(Set.of(), ids(describe("DescribePrefixLists",
filter("prefix-list-name", s3), filter("prefix-list-name", dynamodb)), "prefixListName"));
assertEquals(Set.of(dynamodb), ids(describe("DescribePrefixLists",
filter("prefix-list-name", s3, dynamodb), filter("prefix-list-name", dynamodb)),
"prefixListName"));
}
@Test
void instanceTypeOfferingsMatchEveryInstanceTypeAndLocationFilter() {
assertEquals(Set.of("t3.micro"), ids(describe("DescribeInstanceTypeOfferings",
"LocationType", "region", filter("instance-type", "t3.micro", "m5.large"),
filter("instance-type", "t3.micro")), "instanceType"));
assertEquals(Set.of(), ids(describe("DescribeInstanceTypeOfferings",
"LocationType", "region", filter("instance-type", "m5.large"),
filter("instance-type", "t3.micro")), "instanceType"));
assertEquals(Set.of(), ids(describe("DescribeInstanceTypeOfferings",
"LocationType", "availability-zone", filter("instance-type", "t3.micro"),
filter("location", "us-east-1a"), filter("location", "us-east-1b")), "location"));
}
/**
* The InstanceType.N parameter, which Floci reads beside the instance-type filter, adds its
* types to those every instance-type filter names, so repeating a filter or reordering the
* filters leaves the answer as it was.
*/
@Test
void instanceTypeOfferingsKeepTheNamedTypesBesideEveryInstanceTypeFilter() {
List<String> params = List.of("LocationType", "region", "InstanceType.1", "m5.large");
Set<String> lone = ids(describe("DescribeInstanceTypeOfferings", params,
filter("instance-type", "t3.micro")), "instanceType");
assertEquals(Set.of("m5.large", "t3.micro"), lone);
assertEquals(lone, ids(describe("DescribeInstanceTypeOfferings", params,
filter("instance-type", "t3.micro"), filter("instance-type", "t3.micro")), "instanceType"));
assertEquals(lone, ids(describe("DescribeInstanceTypeOfferings", params,
filter("instance-type", "t3.micro", "m5.large"), filter("instance-type", "t3.micro")), "instanceType"));
assertEquals(lone, ids(describe("DescribeInstanceTypeOfferings", params,
filter("instance-type", "t3.micro"), filter("instance-type", "t3.micro", "m5.large")), "instanceType"));
assertEquals(lone, ids(describe("DescribeInstanceTypeOfferings", params,
filter("instance-type"), filter("instance-type", "t3.micro")), "instanceType"));
assertEquals(lone, ids(describe("DescribeInstanceTypeOfferings", params,
filter("instance-type", "t3.micro"), filter("instance-type")), "instanceType"));
}
/** An instance-type value may hold * and ?, as AWS takes, whichever filter of the name it is in. */
@Test
void instanceTypeOfferingsMatchInstanceTypeWildcards() {
Set<String> t3 = ids(describe("DescribeInstanceTypeOfferings", "LocationType", "region",
filter("instance-type", "t3.*")), "instanceType");
assertTrue(t3.contains("t3.micro") && t3.stream().allMatch(type -> type.startsWith("t3.")), t3.toString());
Set<String> micro = ids(describe("DescribeInstanceTypeOfferings", "LocationType", "region",
filter("instance-type", "*.micro")), "instanceType");
assertTrue(micro.size() > 1 && micro.stream().allMatch(type -> type.endsWith(".micro")), micro.toString());
assertEquals(Set.of("t3.micro"), ids(describe("DescribeInstanceTypeOfferings", "LocationType", "region",
filter("instance-type", "t3.mi?ro")), "instanceType"));
assertEquals(Set.of("t3.micro"), ids(describe("DescribeInstanceTypeOfferings", "LocationType", "region",
filter("instance-type", "t3.*"), filter("instance-type", "t3.micro")), "instanceType"));
assertEquals(Set.of("t3.micro"), ids(describe("DescribeInstanceTypeOfferings", "LocationType", "region",
filter("instance-type", "t3.micro"), filter("instance-type", "t3.*")), "instanceType"));
assertEquals(Set.of("t3.micro"), ids(describe("DescribeInstanceTypeOfferings", "LocationType", "region",
filter("instance-type", "t3.*"), filter("instance-type", "*.micro")), "instanceType"));
Set<String> named = new LinkedHashSet<>(t3);
named.add("m5.large");
assertEquals(named, ids(describe("DescribeInstanceTypeOfferings",
List.of("LocationType", "region", "InstanceType.1", "m5.large"),
filter("instance-type", "t3.*")), "instanceType"));
}
/** A caller-supplied pattern of many stars is matched by the two-pointer glob, not a backtracking regex. */
@Test
void instanceTypeOfferingsMatchAPatternOfManyStarsQuickly() {
String pattern = "*".repeat(30) + "#";
assertEquals(Set.of(), assertTimeoutPreemptively(Duration.ofSeconds(5),
() -> ids(describe("DescribeInstanceTypeOfferings", "LocationType", "region",
filter("instance-type", pattern)), "instanceType")));
}
@Test
void spotPriceHistoryMatchesEveryFilter() {
assertEquals(Set.of("t3.micro"), ids(describe("DescribeSpotPriceHistory",
filter("instance-type", "t3.micro", "m5.large"), filter("instance-type", "t3.micro")),
"instanceType"));
assertEquals(Set.of(), ids(describe("DescribeSpotPriceHistory",
filter("instance-type", "m5.large"), filter("instance-type", "t3.micro")), "instanceType"));
assertEquals(Set.of(), ids(describe("DescribeSpotPriceHistory", filter("instance-type", "t3.micro"),
filter("availability-zone", "us-east-1a"), filter("availability-zone", "us-east-1b")),
"availabilityZone"));
assertEquals(Set.of(), ids(describe("DescribeSpotPriceHistory", filter("instance-type", "t3.micro"),
filter("product-description", "Linux/UNIX"), filter("product-description", "Windows")),
"productDescription"));
}
@Test
void transitGatewayRoutesMatchEveryFilter() {
String gateway = newTransitGateway();
String routeTable = first(ok("CreateTransitGatewayRouteTable", "TransitGatewayId", gateway),
"transitGatewayRouteTableId");
for (String cidr : List.of("10.230.0.0/16", "10.231.0.0/16")) {
ok("CreateTransitGatewayRoute", "TransitGatewayRouteTableId", routeTable,
"DestinationCidrBlock", cidr, "Blackhole", "true");
}
assertEquals(Set.of("10.231.0.0/16"), ids(describe("SearchTransitGatewayRoutes",
"TransitGatewayRouteTableId", routeTable,
filter("route-search.exact-match", "10.231.0.0/16")), "destinationCidrBlock"));
assertEquals(Set.of(), ids(describe("SearchTransitGatewayRoutes",
"TransitGatewayRouteTableId", routeTable,
filter("route-search.exact-match", "10.230.0.0/16"),
filter("route-search.exact-match", "10.231.0.0/16")), "destinationCidrBlock"));
}
@Test
void transitGatewayRouteTableMembersMatchEveryFilter() {
String gateway = first(ok("CreateTransitGateway", "Options.DefaultRouteTableAssociation", "disable",
"Options.DefaultRouteTablePropagation", "disable"), "transitGatewayId");
String routeTable = first(ok("CreateTransitGatewayRouteTable", "TransitGatewayId", gateway),
"transitGatewayRouteTableId");
String first = newVpcAttachment(gateway);
String second = newVpcAttachment(gateway);
for (String attachment : List.of(first, second)) {
ok("AssociateTransitGatewayRouteTable", "TransitGatewayRouteTableId", routeTable,
"TransitGatewayAttachmentId", attachment);
ok("EnableTransitGatewayRouteTablePropagation", "TransitGatewayRouteTableId", routeTable,
"TransitGatewayAttachmentId", attachment);
}
for (String action : List.of("GetTransitGatewayRouteTableAssociations",
"GetTransitGatewayRouteTablePropagations")) {
assertEquals(Set.of(second), ids(describe(action, "TransitGatewayRouteTableId", routeTable,
filter("transit-gateway-attachment-id", second)), "transitGatewayAttachmentId"), action);
assertEquals(Set.of(), ids(describe(action, "TransitGatewayRouteTableId", routeTable,
filter("transit-gateway-attachment-id", first),
filter("transit-gateway-attachment-id", second)), "transitGatewayAttachmentId"), action);
}
}
@Test
void repeatedSupportedNamesAreAcceptedWhereNamesAreChecked() {
for (String action : List.of("DescribeVpnGateways", "DescribeEgressOnlyInternetGateways")) {
ok(action, "Filter.1.Name", "tag-key", "Filter.1.Value.1", "a",
"Filter.2.Name", "tag-key", "Filter.2.Value.1", "b");
}
ok("DescribeSpotPriceHistory", "Filter.1.Name", "instance-type", "Filter.1.Value.1", "t3.micro",
"Filter.2.Name", "instance-type", "Filter.2.Value.1", "t3.micro");
}
// ─── Fixtures ────────────────────────────────────────────────────────────
private String vpc() {
if (vpcId == null) {
vpcId = newVpc();
}
return vpcId;
}
private String subnet() {
if (subnetId == null) {
subnetId = first(ok("CreateSubnet", "VpcId", vpc(), "CidrBlock", nextSubnetCidr()), "subnetId");
}
return subnetId;
}
private int next() {
return ++sequence;
}
private String newVpc() {
return first(ok("CreateVpc", "CidrBlock", "10." + (100 + next()) + ".0.0/16"), "vpcId");
}
private String nextSubnetCidr() {
return "10." + (100 + vpcSequenceOf(vpc())) + "." + next() + ".0/24";
}
private int vpcSequenceOf(String vpc) {
String cidr = cidrOf(vpc);
return Integer.parseInt(cidr.split("\\.")[1]) - 100;
}
private String cidrOf(String vpc) {
return first(ok("DescribeVpcs", "VpcId.1", vpc), "cidrBlock");
}
private String newSecurityGroup() {
return first(ok("CreateSecurityGroup", "GroupName", "repeated-" + next(),
"GroupDescription", "repeated filters", "VpcId", vpc()), "groupId");
}
private String newAddress() {
return first(ok("AllocateAddress", "Domain", "vpc"), "allocationId");
}
private String newVolume() {
return first(ok("CreateVolume", "AvailabilityZone", "us-east-1a", "Size", "8"), "volumeId");
}
private String newTransitGateway() {
return first(ok("CreateTransitGateway"), "transitGatewayId");
}
private String newVpcAttachment(String gateway) {
String vpc = newVpc();
String cidr = cidrOf(vpc);
String attachSubnet = first(ok("CreateSubnet", "VpcId", vpc,
"CidrBlock", cidr.replace(".0.0/16", ".1.0/24")), "subnetId");
return first(ok("CreateTransitGatewayVpcAttachment", "TransitGatewayId", gateway, "VpcId", vpc,
"SubnetIds.1", attachSubnet), "transitGatewayAttachmentId");
}
private void registerImageWithSnapshot(String snapshotId, String volumeSize) {
ok("RegisterImage", "Name", "repeated-" + next(), "RootDeviceName", "/dev/xvda",
"BlockDeviceMapping.1.DeviceName", "/dev/xvda",
"BlockDeviceMapping.1.Ebs.SnapshotId", snapshotId,
"BlockDeviceMapping.1.Ebs.VolumeSize", volumeSize);
}
private String runInstance() {
return first(ok("RunInstances", "ImageId", AMI, "InstanceType", "t3.micro",
"MinCount", "1", "MaxCount", "1"), "instanceId");
}
// ─── Requests ────────────────────────────────────────────────────────────
private static String[] filter(String name, String... values) {
String[] filter = new String[values.length + 1];
filter[0] = name;
System.arraycopy(values, 0, filter, 1, values.length);
return filter;
}
private Set<String> described(Tagged type, String[]... filters) {
List<String> params = new ArrayList<>(type.describeParams(this));
return ids(describe(type.describeAction, params, filters), type.idElement);
}
private String describe(String action, String[]... filters) {
return describe(action, List.of(), filters);
}
private String describe(String action, String paramName, String paramValue, String[]... filters) {
return describe(action, List.of(paramName, paramValue), filters);
}
private String describe(String action, List<String> params, String[]... filters) {
List<String> all = new ArrayList<>(params);
for (int i = 0; i < filters.length; i++) {
all.add("Filter." + (i + 1) + ".Name");
all.add(filters[i][0]);
for (int j = 1; j < filters[i].length; j++) {
all.add("Filter." + (i + 1) + ".Value." + j);
all.add(filters[i][j]);
}
}
return ok(action, all.toArray(String[]::new));
}
private String ok(String action, String... params) {
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
for (int i = 0; i < params.length; i += 2) {
form.add(params[i], params[i + 1]);
}
Response response = handler.handle(action, form, REGION);
String body = String.valueOf(response.getEntity());
assertEquals(200, response.getStatus(), action + ": " + body);
return body;
}
private String first(String xml, String element) {
Matcher matcher = elementPattern(element).matcher(xml);
assertTrue(matcher.find(), "no <" + element + "> in " + xml);
return matcher.group(1).trim();
}
private static Set<String> ids(String xml, String element) {
Set<String> found = new LinkedHashSet<>();
Matcher matcher = elementPattern(element).matcher(xml);
while (matcher.find()) {
found.add(matcher.group(1).trim());
}
return found;
}
private static Set<String> names(String describeImagesXml) {
return ids(describeImagesXml, "name");
}
private static Pattern elementPattern(String element) {
return Pattern.compile("<" + element + ">([^<]*)</" + element + ">");
}
private static final class MemoryFactory extends StorageFactory {
private MemoryFactory() {
super(null, null);
}
@Override
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return AccountAwareStorageBackend.inMemory("000000000000");
}
}
}
@@ -5200,7 +5200,7 @@ class Ec2ServiceTest {
// The mapping's snapshot is registered, so DescribeSnapshots can resolve it.
List<Snapshot> snapshots = service.describeSnapshots("us-east-1",
List.of(root.getEbs().getSnapshotId()), null, null);
List.of(root.getEbs().getSnapshotId()), null, Map.of());
assertEquals(1, snapshots.size());
}
@@ -27,6 +27,7 @@ import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@@ -85,7 +86,7 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
void cleanup() {
for (String volId : volumesToClean) {
try {
Volume vol = ec2Service.describeVolumes("us-east-1", List.of(volId), null).getFirst();
Volume vol = ec2Service.describeVolumes("us-east-1", List.of(volId), Map.of()).getFirst();
if (vol != null && vol.getAttachments() != null) {
for (VolumeAttachment att : vol.getAttachments()) {
try {
@@ -580,7 +581,7 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
ec2Service.stopInstances("us-east-1", List.of(instance.getInstanceId()));
await().atMost(Duration.ofSeconds(35)).until(() ->
"stopped".equals(ec2Service.describeInstances("us-east-1", List.of(instance.getInstanceId()), null)
"stopped".equals(ec2Service.describeInstances("us-east-1", List.of(instance.getInstanceId()), Map.of())
.getFirst().getInstances().getFirst().getState().getName()));
ec2Service.detachVolume("us-east-1", rootVolId, instance.getInstanceId(), instance.getRootDeviceName(), true);
@@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
@@ -41,7 +42,7 @@ class FlowLogServiceTest {
private FlowLogService serviceCallingAs(String accountId) {
Ec2Service ec2Service = mock(Ec2Service.class);
when(ec2Service.callerAccountId()).thenReturn(accountId);
when(ec2Service.describeInstances(any(), any(), any())).thenReturn(List.of());
when(ec2Service.describeInstances(any(), any(), anyMap())).thenReturn(List.of());
when(ec2Service.endpointNetworkInterfaces(any())).thenReturn(List.of());
return new FlowLogService(ec2Service, mock(S3Service.class), new InMemoryStorage<>());
}
@@ -214,7 +215,7 @@ class FlowLogServiceTest {
private List<String> deliver(String region, String logFormat) throws Exception {
Ec2Service ec2Service = mock(Ec2Service.class);
when(ec2Service.callerAccountId()).thenReturn("000000000000");
when(ec2Service.describeInstances(any(), any(), any()))
when(ec2Service.describeInstances(any(), any(), anyMap()))
.thenReturn(List.of(reservation(region)));
when(ec2Service.endpointNetworkInterfaces(any())).thenReturn(List.of());
S3Service s3Service = mock(S3Service.class);