diff --git a/docs/services/route53resolver.md b/docs/services/route53resolver.md index 10f47dd679..4800ab390f 100644 --- a/docs/services/route53resolver.md +++ b/docs/services/route53resolver.md @@ -13,7 +13,7 @@ | `CreateResolverEndpoint` | Creates an inbound (`rslvr-in-`) or outbound (`rslvr-out-`) resolver endpoint, returned immediately as `OPERATIONAL`. `HostVPCId` is the VPC of its subnets. Each address in a subnet EC2 knows gets its own EC2 network interface, with the requested `Ip` or one EC2 picks and the endpoint's security groups, held `in-use` for the endpoint; an `Ip` already in use is refused with `InvalidRequestException`. | | `DeleteResolverEndpoint` | Deletes a resolver endpoint and its network interfaces, and returns its final description. | | `GetResolverEndpoint` | Returns a resolver endpoint by id. | -| `ListResolverEndpoints` | Lists all resolver endpoints. | +| `ListResolverEndpoints` | Lists the region's resolver endpoints, filtered by `Filters` (`CreatorRequestId`, `Direction`, `HostVPCId`, `IpAddressCount`, `Name`, `SecurityGroupIds`, `Status`) and paginated by `MaxResults` (default and maximum 100) and `NextToken`. A `SecurityGroupIds` value matches an endpoint that has that group. | | `ListResolverEndpointIpAddresses` | Lists a resolver endpoint's IP addresses, each `ATTACHED`, with the address of the network interface behind it; an address in a subnet EC2 does not know keeps the requested `Ip`, or none. Not paginated. | | `UpdateResolverEndpoint` | Updates a resolver endpoint's `Name` and `ResolverEndpointType`; `IpAddresses` changes are not modelled. | | `CreateResolverRule` | Creates a resolver rule, returned immediately as `COMPLETE`; `ResolverEndpointId` is not validated against an existing endpoint. | @@ -24,7 +24,7 @@ | `AssociateResolverRule` | Associates a resolver rule with a VPC, returned immediately as `COMPLETE`. | | `DisassociateResolverRule` | Removes the association between a resolver rule and a VPC. | | `GetResolverRuleAssociation` | Returns a resolver rule association by id. | -| `ListResolverRuleAssociations` | Lists all resolver rule associations. | +| `ListResolverRuleAssociations` | Lists the region's resolver rule associations, filtered by `Filters` (`Name`, `ResolverRuleId`, `Status`, `VPCId`) and paginated by `MaxResults` (default and maximum 100) and `NextToken`. | | `UpdateResolverDnssecConfig` | Creates or updates a VPC's DNSSEC validation configuration and returns its terminal validation status. | | `GetResolverDnssecConfig` | Returns a stable DNSSEC validation configuration for an existing VPC, defaulting to `DISABLED` before its first update. | | `ListResolverDnssecConfigs` | Lists the region's DNSSEC validation configurations, leaving out disabled ones, filtered by `Filters` and paginated by `MaxResults` (default and maximum 100) and `NextToken`. | diff --git a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverJsonHandler.java b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverJsonHandler.java index bd5f102fc7..e28a2f694e 100644 --- a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverJsonHandler.java +++ b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverJsonHandler.java @@ -53,7 +53,9 @@ public class Route53ResolverJsonHandler { service.deleteResolverEndpoint(text(request, "ResolverEndpointId"), region)); case "GetResolverEndpoint" -> resolverEndpointResponse( service.getResolverEndpoint(text(request, "ResolverEndpointId"), region)); - case "ListResolverEndpoints" -> handleListResolverEndpoints(region); + case "ListResolverEndpoints" -> Response.ok(service.listResolverEndpoints( + request.get("Filters"), request.get("MaxResults"), text(request, "NextToken"), + region)).build(); case "ListResolverEndpointIpAddresses" -> handleListResolverEndpointIpAddresses( text(request, "ResolverEndpointId"), region); case "UpdateResolverEndpoint" -> resolverEndpointResponse( @@ -75,7 +77,9 @@ public class Route53ResolverJsonHandler { service.disassociateResolverRule(request, region)); case "GetResolverRuleAssociation" -> resolverRuleAssociationResponse( service.getResolverRuleAssociation(text(request, "ResolverRuleAssociationId"), region)); - case "ListResolverRuleAssociations" -> handleListResolverRuleAssociations(region); + case "ListResolverRuleAssociations" -> Response.ok(service.listResolverRuleAssociations( + request.get("Filters"), request.get("MaxResults"), text(request, "NextToken"), + region)).build(); case "UpdateResolverDnssecConfig" -> dnssecConfigResponse(service.updateResolverDnssecConfig( request, region, accountId)); @@ -165,15 +169,6 @@ public class Route53ResolverJsonHandler { return Response.ok(objectMapper.createObjectNode().set("ResolverEndpoint", endpoint)).build(); } - private Response handleListResolverEndpoints(String region) { - ObjectNode result = objectMapper.createObjectNode(); - ArrayNode endpoints = result.putArray("ResolverEndpoints"); - for (ObjectNode endpoint : service.listResolverEndpoints(region)) { - endpoints.add(endpoint); - } - return Response.ok(result).build(); - } - private Response handleListResolverEndpointIpAddresses(String endpointId, String region) { ObjectNode result = objectMapper.createObjectNode(); result.putArray("IpAddresses").addAll(service.listResolverEndpointIpAddresses(endpointId, region)); @@ -202,15 +197,6 @@ public class Route53ResolverJsonHandler { .set("ResolverRuleAssociation", association)).build(); } - private Response handleListResolverRuleAssociations(String region) { - ObjectNode result = objectMapper.createObjectNode(); - ArrayNode associations = result.putArray("ResolverRuleAssociations"); - for (ObjectNode association : service.listResolverRuleAssociations(region)) { - associations.add(association); - } - return Response.ok(result).build(); - } - private Response dnssecConfigResponse(ObjectNode config) { return Response.ok(objectMapper.createObjectNode().set("ResolverDNSSECConfig", config)).build(); } diff --git a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java index b0c623eefa..d371dc3f15 100644 --- a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java +++ b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java @@ -90,6 +90,23 @@ public class Route53ResolverService { "resourceid", "ResourceId", "validationstatus", "ValidationStatus"); + /** The endpoint fields the endpoint listing filters on, keyed as the normalized filter name. */ + private static final Map ENDPOINT_FILTER_FIELDS = Map.of( + "creatorrequestid", "CreatorRequestId", + "direction", "Direction", + "hostvpcid", "HostVPCId", + "ipaddresscount", "IpAddressCount", + "name", "Name", + "securitygroupids", "SecurityGroupIds", + "status", "Status"); + + /** The association fields the association listing filters on, keyed as the normalized filter name. */ + private static final Map ASSOCIATION_FILTER_FIELDS = Map.of( + "name", "Name", + "resolverruleid", "ResolverRuleId", + "status", "Status", + "vpcid", "VPCId"); + /** The AWS-managed domain lists available in commercial regions. */ static final List AWS_MANAGED_DOMAIN_LIST_NAMES = List.of( "AWSManagedDomainsAggregateThreatList", @@ -474,8 +491,17 @@ public class Route53ResolverService { return require(endpointStore, id, "resolver endpoint", region).deepCopy(); } - public List listResolverEndpoints(String region) { - return recordsIn(endpointStore, region); + /** + * A page of {@code region}'s resolver endpoints matching every filter of {@code filters}, resuming + * after the endpoint {@code nextToken} names. A filter name may also be given in the legacy + * upper-case form ({@code HOST_VPC_ID}), and a name the operation does not list filters nothing. + */ + public ObjectNode listResolverEndpoints(JsonNode filters, JsonNode maxResults, String nextToken, + String region) { + List matching = filtered(recordsIn(endpointStore, region), filters, ENDPOINT_FILTER_FIELDS, + field -> false); + return page(matching, endpoint -> text(endpoint, "Id"), pageSize(maxResults), nextToken, + "resolver-endpoints", "ResolverEndpoints", ArrayNode::add); } /** @@ -653,8 +679,18 @@ public class Route53ResolverService { return require(ruleAssociationStore, id, "resolver rule association", region).deepCopy(); } - public List listResolverRuleAssociations(String region) { - return recordsIn(ruleAssociationStore, region); + /** + * A page of {@code region}'s rule associations matching every filter of {@code filters}, resuming + * after the association {@code nextToken} names. As in {@link #listResolverEndpoints}, a filter + * name may be given in the legacy upper-case form ({@code VPC_ID}) and a name the operation does + * not list filters nothing. + */ + public ObjectNode listResolverRuleAssociations(JsonNode filters, JsonNode maxResults, String nextToken, + String region) { + List matching = filtered(recordsIn(ruleAssociationStore, region), filters, + ASSOCIATION_FILTER_FIELDS, field -> false); + return page(matching, association -> text(association, "Id"), pageSize(maxResults), nextToken, + "resolver-rule-associations", "ResolverRuleAssociations", ArrayNode::add); } // ---------- VPC DNSSEC validation ---------- @@ -1176,9 +1212,10 @@ public class Route53ResolverService { /** * The records matching every filter of {@code filters}, a record matching a filter when its field equals any of - * the filter's values. A filter name is read case-insensitively and without underscores, so the legacy - * upper-case form ({@code CREATOR_REQUEST_ID}) works too, and a name {@code fields} does not list filters - * nothing. A field {@code domainField} accepts compares as a domain name. + * the filter's values, or, for a field holding a list, when one of its members does. A filter name is read + * case-insensitively and without underscores, so the legacy upper-case form ({@code CREATOR_REQUEST_ID}) works + * too, and a name {@code fields} does not list filters nothing. A field {@code domainField} accepts compares as a + * domain name. */ private List filtered(List records, JsonNode filters, Map fields, Predicate domainField) { @@ -1216,16 +1253,30 @@ public class Route53ResolverService { continue; } boolean domain = domainField.test(field); - matching = matching.stream() - .filter(record -> values.stream().anyMatch(value -> domain - ? DnsLookupHelper.normalizeTarget(value) - .equalsIgnoreCase(DnsLookupHelper.normalizeTarget(text(record, field))) - : value.equals(text(record, field)))) - .toList(); + matching = matching.stream().filter(record -> matches(record, field, values, domain)).toList(); } return matching; } + /** + * Whether {@code record}'s {@code field} answers {@code values}. A list field, such as an endpoint's + * {@code SecurityGroupIds}, answers when one of its members equals a value, which is how AWS reads that filter: + * the value names an endpoint having the group. Any other field answers when its text equals a value, and a + * domain field is compared after both sides are normalized. + */ + private boolean matches(ObjectNode record, String field, List values, boolean domain) { + JsonNode stored = record.path(field); + if (stored.isArray()) { + List members = new ArrayList<>(); + stored.forEach(member -> members.add(JsonNodes.asText(member))); + return values.stream().anyMatch(members::contains); + } + String held = text(record, field); + return values.stream().anyMatch(value -> domain + ? DnsLookupHelper.normalizeTarget(value).equalsIgnoreCase(DnsLookupHelper.normalizeTarget(held)) + : value.equals(held)); + } + /** * {@code MaxResults} as a page size: the modeled 100 when absent. It arrives as a JSON value, so it is * type-checked rather than parsed from a string: {@code 1.5}, {@code true} and {@code "1"} are not the modeled @@ -1244,13 +1295,14 @@ public class Route53ResolverService { /** * One page of {@code items} under {@code member}, cursored by {@code cursor} through {@link Pagination#paginate}, - * with a {@code NextToken} only when another page remains. An invalid token is the modeled - * {@code InvalidNextTokenException}. + * with a {@code NextToken} only when another page remains. A token the listing did not mint is the modeled + * {@code InvalidNextTokenException}, and AWS says which token it could not read and why: an invalid version. */ private ObjectNode page(List items, Function cursor, int pageSize, String nextToken, String namespace, String member, BiConsumer write) { PaginatedResult paged = Pagination.paginate(items, cursor, pageSize, nextToken, namespace, - token -> new AwsException("InvalidNextTokenException", "Invalid NextToken: " + token, 400)); + token -> new AwsException("InvalidNextTokenException", "[RSLVR-00302] Invalid next token: \"" + + token + "\", invalid version.", 400)); ObjectNode result = objectMapper.createObjectNode(); ArrayNode page = result.putArray(member); for (T item : paged.items()) { diff --git a/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverListingIntegrationTest.java b/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverListingIntegrationTest.java new file mode 100644 index 0000000000..84e4459bdc --- /dev/null +++ b/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverListingIntegrationTest.java @@ -0,0 +1,308 @@ +package io.floci.aws.services.route53resolver; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.Route53ResolverRequests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * ListResolverEndpoints and ListResolverRuleAssociations model {@code Filters}, {@code MaxResults} + * and {@code NextToken} as their sibling listings do, so a filter narrows the records to those + * matching every one of them, and a page size ends the list with a token. + */ +@QuarkusTest +class Route53ResolverListingIntegrationTest { + + /** Its own region, so only what this class creates and deletes is ever in it. */ + private static final String REGION = "eu-central-1"; + private static final String ENDPOINTS = "ResolverEndpoints"; + private static final String ASSOCIATIONS = "ResolverRuleAssociations"; + private static final String AUTH_HEADER = "AWS4-HMAC-SHA256 Credential=AKID/20260101/" + REGION + + "/route53resolver/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void listResolverEndpointsAppliesFilters() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String inbound = createEndpoint("in-" + suffix, "INBOUND", 2); + String outbound = createEndpoint("out-" + suffix, "OUTBOUND", 3); + try { + assertEquals(List.of(inbound), endpointIds(filter("Name", "in-" + suffix))); + assertEquals(List.of(outbound), endpointIds(filter("Direction", "OUTBOUND"))); + // An address count is stored as a number and the filter's value is a string: they must agree. + assertEquals(List.of(outbound), endpointIds(filter("IpAddressCount", "3"))); + assertEquals(List.of(inbound), endpointIds(filter("CreatorRequestId", "in-" + suffix))); + assertEquals(List.of(), endpointIds(filter("HostVPCId", "vpc-absent"))); + assertEquals(List.of(outbound), endpointIds(filter("HOST_VPC_ID", hostVpcOf(outbound)))); + // Every filter has to hold, so two that no single record answers leave nothing. + assertEquals(List.of(), endpointIds(filter("Direction", "INBOUND"), filter("IpAddressCount", "3"))); + assertEquals(Set.of(inbound, outbound), + Set.copyOf(endpointIds(filter("Name", "in-" + suffix, "out-" + suffix)))); + // A name the operation does not list filters nothing, which leaves the region whole. + assertEquals(endpointIds(), endpointIds(filter("UnhandledName", suffix))); + } finally { + deleteEndpoint(inbound); + deleteEndpoint(outbound); + } + } + + @Test + void listResolverEndpointsFiltersBySecurityGroup() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String both = createEndpoint("grp-a-" + suffix, "INBOUND", 2, + "sg-" + suffix + "-one", "sg-" + suffix + "-two"); + String single = createEndpoint("grp-b-" + suffix, "INBOUND", 2, "sg-" + suffix + "-three"); + try { + // AWS matches an endpoint that has the group among its several, not one whose list equals the value. + assertEquals(List.of(both), endpointIds(filter("SecurityGroupIds", "sg-" + suffix + "-two"))); + assertEquals(Set.of(both, single), Set.copyOf(endpointIds(filter("SecurityGroupIds", + "sg-" + suffix + "-one", "sg-" + suffix + "-three")))); + assertEquals(List.of(), endpointIds(filter("SecurityGroupIds", "sg-" + suffix + "-absent"))); + } finally { + deleteEndpoint(both); + deleteEndpoint(single); + } + } + + @Test + void listResolverEndpointsPagesWithMaxResultsAndNextToken() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + List created = List.of(createEndpoint("page-a-" + suffix, "INBOUND", 2), + createEndpoint("page-b-" + suffix, "INBOUND", 2), createEndpoint("page-c-" + suffix, "INBOUND", 2)); + String[] threeNames = {"page-a-" + suffix, "page-b-" + suffix, "page-c-" + suffix}; + try { + JsonPath firstPage = page("ListResolverEndpoints", maxResults(2), filter("Name", threeNames)); + List first = firstPage.getList(ENDPOINTS + ".Id", String.class); + assertEquals(2, first.size(), "MaxResults did not end the page: " + first); + String token = firstPage.getString("NextToken"); + assertTrue(token != null && !token.isBlank(), "a second page was there, but no token named it"); + + JsonPath secondPage = page("ListResolverEndpoints", nextToken(token), filter("Name", threeNames)); + List rest = secondPage.getList(ENDPOINTS + ".Id", String.class); + assertEquals(1, rest.size(), "the last page did not hold the record left over: " + rest); + assertNull(secondPage.getString("NextToken"), "the last page still asked to be continued"); + + Set seen = new HashSet<>(first); + seen.addAll(rest); + assertEquals(Set.copyOf(created), seen, "the pages did not cover the three endpoints"); + } finally { + created.forEach(Route53ResolverListingIntegrationTest::deleteEndpoint); + } + } + + @Test + void listResolverEndpointsRefusesMalformedFiltersAndPageKnobs() { + for (String filters : new String[] {"\"Name\"", "[\"Name\"]", "[{\"Name\":\"Name\",\"Values\":\"x\"}]", + "[{\"Name\":\"Name\",\"Values\":[1]}]", "[{\"Name\":\"\",\"Values\":[\"x\"]}]", + "[{\"Name\":\"" + "n".repeat(65) + "\",\"Values\":[\"x\"]}]"}) { + raw("ListResolverEndpoints", "{\"Filters\":" + filters + "}").statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + for (String maxResults : new String[] {"0", "101", "1.5", "true", "\"1\""}) { + raw("ListResolverEndpoints", "{\"MaxResults\":" + maxResults + "}").statusCode(400) + .body("__type", equalTo("InvalidParameterException")) + .body("message", equalTo("MaxResults must be an integer between 1 and 100")); + } + raw("ListResolverEndpoints", "{\"NextToken\":\"no-such-token\"}").statusCode(400) + .body("__type", equalTo("InvalidNextTokenException")) + // AWS names the token it could not read and says its version is invalid. + .body("message", equalTo("[RSLVR-00302] Invalid next token: \"no-such-token\", invalid version.")); + } + + @Test + void listResolverRuleAssociationsAppliesFilters() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String ruleA = createRule("rule-a-" + suffix, "a-" + suffix + ".example.com"); + String ruleB = createRule("rule-b-" + suffix, "b-" + suffix + ".example.com"); + String onA = associate(ruleA, "assoc-a-" + suffix, "vpc-a-" + suffix); + String onB = associate(ruleB, "assoc-b-" + suffix, "vpc-b-" + suffix); + try { + assertEquals(List.of(onA), associationIds(filter("ResolverRuleId", ruleA))); + assertEquals(List.of(onB), associationIds(filter("VPC_ID", "vpc-b-" + suffix))); + assertEquals(List.of(onA), associationIds(filter("Name", "assoc-a-" + suffix))); + // Every association is COMPLETE here, and the listing orders its records by id, not by creation. + assertEquals(Set.of(onA, onB), Set.copyOf(associationIds(filter("Status", "COMPLETE")))); + assertEquals(List.of(), associationIds(filter("Status", "CREATING"))); + // HostVPCId names an endpoint's VPC, not one of the four association names, so it filters nothing. + assertEquals(associationIds(), associationIds(filter("HostVPCId", "vpc-a-" + suffix))); + assertEquals(associationIds(), associationIds(filter("UnhandledName", suffix))); + } finally { + disassociate(ruleA, "vpc-a-" + suffix); + disassociate(ruleB, "vpc-b-" + suffix); + deleteRule(ruleA); + deleteRule(ruleB); + } + } + + @Test + void listResolverRuleAssociationsPagesAndRefusesMalformedPageKnobs() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String rule = createRule("paged-" + suffix, "paged-" + suffix + ".example.com"); + String first = associate(rule, "page-one-" + suffix, "vpc-1-" + suffix); + String second = associate(rule, "page-two-" + suffix, "vpc-2-" + suffix); + String byRule = filter("ResolverRuleId", rule); + try { + JsonPath only = page("ListResolverRuleAssociations", maxResults(1), byRule); + List head = only.getList(ASSOCIATIONS + ".Id", String.class); + assertEquals(1, head.size(), "MaxResults did not end the page: " + head); + String token = only.getString("NextToken"); + assertTrue(token != null && !token.isBlank(), "a second page was there, but no token named it"); + + JsonPath rest = page("ListResolverRuleAssociations", nextToken(token), byRule); + assertEquals(1, rest.getList(ASSOCIATIONS + ".Id", String.class).size()); + assertNull(rest.getString("NextToken"), "the last page still asked to be continued"); + + Set seen = new HashSet<>(head); + seen.addAll(rest.getList(ASSOCIATIONS + ".Id", String.class)); + assertEquals(Set.of(first, second), seen, "the pages did not cover both associations"); + } finally { + disassociate(rule, "vpc-1-" + suffix); + disassociate(rule, "vpc-2-" + suffix); + deleteRule(rule); + } + + raw("ListResolverRuleAssociations", "{\"MaxResults\":0}").statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + raw("ListResolverRuleAssociations", "{\"NextToken\":\"no-such-token\"}").statusCode(400) + .body("__type", equalTo("InvalidNextTokenException")); + } + + // Each listing cursors its own records, so a token the other one minted names no place here. + @Test + void eachListingRefusesTheOtherListingsToken() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String rule = createRule("token-" + suffix, "token-" + suffix + ".example.com"); + List vpcs = List.of("vpc-a-" + suffix, "vpc-b-" + suffix); + List endpoints = List.of(createEndpoint("token-c-" + suffix, "INBOUND", 2), + createEndpoint("token-d-" + suffix, "INBOUND", 2)); + try { + vpcs.forEach(vpc -> associate(rule, "assoc-" + vpc, vpc)); + String associationToken = page("ListResolverRuleAssociations", maxResults(1)).getString("NextToken"); + String endpointToken = page("ListResolverEndpoints", maxResults(1)).getString("NextToken"); + assertTrue(associationToken != null && endpointToken != null, "a listing had no second page to mint a token"); + + raw("ListResolverEndpoints", "{\"NextToken\":\"" + associationToken + "\"}").statusCode(400) + .body("__type", equalTo("InvalidNextTokenException")); + raw("ListResolverRuleAssociations", "{\"NextToken\":\"" + endpointToken + "\"}").statusCode(400) + .body("__type", equalTo("InvalidNextTokenException")); + } finally { + vpcs.forEach(vpc -> disassociate(rule, vpc)); + deleteRule(rule); + endpoints.forEach(Route53ResolverListingIntegrationTest::deleteEndpoint); + } + } + + private static String createEndpoint(String name, String direction, int ipCount) { + return createEndpoint(name, direction, ipCount, "sg-abc123"); + } + + private static String createEndpoint(String name, String direction, int ipCount, String... securityGroups) { + StringBuilder addresses = new StringBuilder(); + for (int i = 0; i < ipCount; i++) { + if (i > 0) { + addresses.append(","); + } + addresses.append("{\"SubnetId\":\"subnet-").append(i).append("\"}"); + } + return raw("CreateResolverEndpoint", "{\"Name\":\"" + name + "\",\"Direction\":\"" + direction + + "\",\"CreatorRequestId\":\"" + name + "\",\"SecurityGroupIds\":[" + quoted(securityGroups) + + "],\"IpAddresses\":[" + addresses + "]}").statusCode(200).extract().path("ResolverEndpoint.Id"); + } + + private static String hostVpcOf(String endpointId) { + return raw("GetResolverEndpoint", "{\"ResolverEndpointId\":\"" + endpointId + "\"}") + .statusCode(200).extract().path("ResolverEndpoint.HostVPCId"); + } + + private static String createRule(String name, String domain) { + return Route53ResolverRequests.createRule(name, "SYSTEM", domain, AUTH_HEADER); + } + + private static String associate(String ruleId, String name, String vpcId) { + return raw("AssociateResolverRule", "{\"ResolverRuleId\":\"" + ruleId + "\",\"Name\":\"" + name + + "\",\"VPCId\":\"" + vpcId + "\"}").statusCode(200).extract().path("ResolverRuleAssociation.Id"); + } + + private static void disassociate(String ruleId, String vpcId) { + raw("DisassociateResolverRule", "{\"ResolverRuleId\":\"" + ruleId + "\",\"VPCId\":\"" + vpcId + "\"}"); + } + + private static void deleteRule(String ruleId) { + raw("DeleteResolverRule", "{\"ResolverRuleId\":\"" + ruleId + "\"}"); + } + + private static void deleteEndpoint(String endpointId) { + raw("DeleteResolverEndpoint", "{\"ResolverEndpointId\":\"" + endpointId + "\"}"); + } + + /** One filter, in the shape AWS models it: a name and the values any of which matches. */ + private static String filter(String name, String... values) { + return "{\"Name\":\"" + name + "\",\"Values\":[" + quoted(values) + "]}"; + } + + /** {@code values} as the inside of a JSON array: each one quoted, joined by commas. */ + private static String quoted(String... values) { + StringBuilder json = new StringBuilder(); + for (String value : values) { + json.append(json.length() == 0 ? "" : ",").append('"').append(value).append('"'); + } + return json.toString(); + } + + private static String maxResults(int value) { + return "\"MaxResults\":" + value; + } + + private static String nextToken(String token) { + return "\"NextToken\":\"" + token + "\""; + } + + private static List endpointIds(String... filters) { + return ids("ListResolverEndpoints", ENDPOINTS, listBody("", filters)); + } + + private static List associationIds(String... filters) { + return ids("ListResolverRuleAssociations", ASSOCIATIONS, listBody("", filters)); + } + + /** A listing request: {@code knobs}, which may be none, beside a {@code Filters} array. */ + private static String listBody(String knobs, String... filters) { + String filterPart = filters.length == 0 ? "" : "\"Filters\":[" + String.join(",", filters) + "]"; + String knobPart = knobs.isEmpty() ? "" : knobs + (filterPart.isEmpty() ? "" : ","); + return "{" + knobPart + filterPart + "}"; + } + + private static List ids(String action, String member, String body) { + return body(action, body).getList(member + ".Id", String.class); + } + + /** One page of {@code action}: {@code knobs}, a page size or a token, beside the {@code filters}. */ + private static JsonPath page(String action, String knobs, String... filters) { + return body(action, listBody(knobs, filters)); + } + + private static JsonPath body(String action, String body) { + return JsonPath.from(raw(action, body).statusCode(200).extract().body().asString()); + } + + private static ValidatableResponse raw(String action, String body) { + return Route53ResolverRequests.call(action, body, AUTH_HEADER); + } +} diff --git a/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleDeletionRaceTest.java b/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleDeletionRaceTest.java index 067cc660fe..c3642d5951 100644 --- a/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleDeletionRaceTest.java +++ b/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleDeletionRaceTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.node.ObjectNode; +import java.util.ArrayList; import java.util.List; import static io.floci.aws.testing.ParkingStoreAssertions.assertOperationWaitsForParkedStore; @@ -42,7 +43,9 @@ class Route53ResolverRuleDeletionRaceTest { () -> service.deleteResolverRule(ruleId, REGION)).getErrorCode())); assertEquals(ruleId, service.getResolverRule(ruleId, REGION).get("Id").asString()); - assertEquals(List.of(ruleId), service.listResolverRuleAssociations(REGION).stream() - .map(association -> association.get("ResolverRuleId").asString()).toList()); + List associatedRuleIds = new ArrayList<>(); + service.listResolverRuleAssociations(null, null, null, REGION).path("ResolverRuleAssociations") + .forEach(association -> associatedRuleIds.add(association.get("ResolverRuleId").asString())); + assertEquals(List.of(ruleId), associatedRuleIds); } } diff --git a/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleFilterIntegrationTest.java b/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleFilterIntegrationTest.java index 0ac9865bf5..8014f40e13 100644 --- a/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleFilterIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/route53resolver/Route53ResolverRuleFilterIntegrationTest.java @@ -88,9 +88,7 @@ class Route53ResolverRuleFilterIntegrationTest { } private static String createRule(String name, String type, String domain) { - return call("CreateResolverRule", "{\"CreatorRequestId\":\"" + name + "\",\"Name\":\"" + name - + "\",\"RuleType\":\"" + type + "\",\"DomainName\":\"" + domain + "\"}") - .statusCode(200).extract().path("ResolverRule.Id"); + return Route53ResolverRequests.createRule(name, type, domain, AUTH_HEADER); } private static ValidatableResponse list(String... filters) { diff --git a/src/test/java/io/floci/aws/testing/Route53ResolverRequests.java b/src/test/java/io/floci/aws/testing/Route53ResolverRequests.java index 3deebb412a..0ab9d8cb2b 100644 --- a/src/test/java/io/floci/aws/testing/Route53ResolverRequests.java +++ b/src/test/java/io/floci/aws/testing/Route53ResolverRequests.java @@ -24,6 +24,16 @@ public final class Route53ResolverRequests { return send(given().port(port), action, body, authorization); } + /** + * A rule named {@code name} of {@code type} covering {@code domain}, as the listings that page or filter rules + * need one in hand. Returns the id of the rule the create answers with. + */ + public static String createRule(String name, String type, String domain, String authorization) { + return call("CreateResolverRule", "{\"CreatorRequestId\":\"" + name + "\",\"Name\":\"" + name + + "\",\"RuleType\":\"" + type + "\",\"DomainName\":\"" + domain + "\"}", authorization) + .statusCode(200).extract().path("ResolverRule.Id"); + } + private static ValidatableResponse send(RequestSpecification request, String action, String body, String authorization) { return request.contentType(CONTENT_TYPE)