diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java index 9468c12ec0..ff9b71e412 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java @@ -23,12 +23,14 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Supplier; import java.util.stream.Collectors; /** @@ -554,22 +556,102 @@ public class Ec2IpamService { return findScope(ipamScopeId).orElseThrow(() -> scopeNotFound(ipamScopeId)).ipam().getIpamId(); } - public List describeIpamPools(String region, List ipamPoolIds) { + /** DescribeIpamPools filter names, tag:<key> being admitted through tag-key. The names for + * fields a pool does not carry (aws-service, publicly-advertisable) match no pool for a + * concrete value, rather than every pool. */ + private static final Set POOL_FILTERS = Set.of( + "address-family", "allocation-default-netmask-length", "allocation-max-netmask-length", + "allocation-min-netmask-length", "auto-import", "aws-service", "description", "ipam-arn", + "ipam-pool-id", "ipam-region", "ipam-scope-arn", "ipam-scope-id", "ipam-scope-type", + "locale", "pool-depth", "publicly-advertisable", "source-ipam-pool-id", "state", "tag-key"); + + public List describeIpamPools(String region, List ipamPoolIds, + List>> filters) { + Ec2Service.requireSupportedFilters(filters.stream().map(Map.Entry::getKey).toList(), POOL_FILTERS); + List candidates; if (ipamPoolIds != null && !ipamPoolIds.isEmpty()) { - List result = new ArrayList<>(); + candidates = new ArrayList<>(); for (String id : ipamPoolIds) { - result.add(requirePool(region, id)); + candidates.add(requirePool(region, id)); } - return result; - } - List result = new ArrayList<>(); - for (IpamPool pool : pools.scan(k -> true)) { - if (region != null && pool.getRegion() != null && !region.equals(pool.getRegion())) { - continue; + } else { + candidates = new ArrayList<>(); + for (IpamPool pool : pools.scan(k -> true)) { + if (region == null || pool.getRegion() == null || region.equals(pool.getRegion())) { + candidates.add(pool); + } } - result.add(pool); } - return result; + // scope/IPAM looked up only for the filters that need it, once per scope per request + Map> scopes = new HashMap<>(); + return candidates.stream() + .filter(pool -> filters.stream().allMatch(f -> matchesPoolFilter(pool, f.getKey(), f.getValue(), + () -> scopes.computeIfAbsent(pool.getIpamScopeId(), id -> scopeOfPool(pool))))) + .toList(); + } + + /** The pool's scope, resolved from the IPAM that owns the pool, which for a RAM-shared pool + * lives in another account's partition than the caller's. Empty when that IPAM is gone. */ + private Optional scopeOfPool(IpamPool pool) { + Ipam ipam; + try { + ipam = requireOwnedIpam(pool.getRegion(), pool.getIpamId()).ipam(); + } catch (AwsException e) { + LOG.debugv("IPAM {0} of pool {1} not found; scope filters match nothing: {2}", + pool.getIpamId(), pool.getIpamPoolId(), e.getErrorCode()); + return Optional.empty(); + } + return ipam.getScopes().stream() + .filter(s -> s.getIpamScopeId().equals(pool.getIpamScopeId())) + .findFirst().map(s -> new ScopeOfIpam(ipam, s)); + } + + private boolean matchesPoolFilter(IpamPool pool, String name, List values, + Supplier> scopeLookup) { + if (name.startsWith("tag:") || "tag-key".equals(name)) { + return Ec2Service.matchesTagFilter(pool.getTags(), name, values, Ec2Service::matchesFilterValue); + } + String value = switch (name) { + case "address-family" -> pool.getAddressFamily(); + case "allocation-default-netmask-length" -> str(pool.getAllocationDefaultNetmaskLength()); + case "allocation-max-netmask-length" -> str(pool.getAllocationMaxNetmaskLength()); + case "allocation-min-netmask-length" -> str(pool.getAllocationMinNetmaskLength()); + case "auto-import" -> String.valueOf(pool.isAutoImport()); + case "description" -> pool.getDescription(); + case "ipam-arn" -> scopeLookup.get().map(s -> s.ipam().getIpamArn()).orElse(null); + case "ipam-pool-id" -> pool.getIpamPoolId(); + case "ipam-region" -> scopeLookup.get().map(s -> s.ipam().getRegion()).orElse(null); + case "ipam-scope-arn" -> scopeLookup.get().map(s -> s.scope().getIpamScopeArn()).orElse(null); + case "ipam-scope-id" -> pool.getIpamScopeId(); + case "ipam-scope-type" -> scopeLookup.get().map(s -> s.scope().getScopeType()).orElse(null); + case "locale" -> pool.getLocale(); + case "pool-depth" -> String.valueOf(poolDepth(pool)); + case "source-ipam-pool-id" -> pool.getSourceIpamPoolId(); + case "state" -> pool.getState(); + default -> null; // aws-service, publicly-advertisable: not modelled, no pool matches + }; + return Ec2Service.matchesFilterValue(values, value); + } + + private static String str(Integer n) { + return n == null ? null : String.valueOf(n); + } + + /** 1 for a top-level pool, the source pool's depth + 1 otherwise. DeleteIpamPool can remove a + * parent that still has children, so the chain stops at a missing ancestor: an orphan counts + * as top-level rather than failing the whole DescribeIpamPools request. */ + private int poolDepth(IpamPool pool) { + int depth = 1; + for (IpamPool p = pool; p.getSourceIpamPoolId() != null && depth < 20; depth++) { + try { + p = requirePool(p.getRegion(), p.getSourceIpamPoolId()); + } catch (AwsException e) { + LOG.debugv("Source pool {0} of {1} not found; treating {1} as top-level: {2}", + p.getSourceIpamPoolId(), p.getIpamPoolId(), e.getErrorCode()); + break; + } + } + return depth; } public IpamPool deleteIpamPool(String region, String ipamPoolId) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 6798315505..85d030d9ab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -2280,7 +2280,7 @@ public class Ec2QueryHandler { .start("DescribeIpamPoolsResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) .start("ipamPoolSet"); - for (IpamPool pool : ipamService.describeIpamPools(region, ids)) { + for (IpamPool pool : ipamService.describeIpamPools(region, ids, getFiltersList(p))) { writeIpamPool(xml, "item", pool); } xml.end("ipamPoolSet").end("DescribeIpamPoolsResponse"); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 233f353ea5..cb33f79b30 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -6398,7 +6398,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } - private void requireSupportedFilters(Collection filterNames, Set supportedFilters) { + static void requireSupportedFilters(Collection filterNames, Set supportedFilters) { filterNames.stream() .filter(name -> !supportedFilters.contains(name) && !(supportedFilters.contains("tag-key") && name.startsWith("tag:"))) @@ -9987,8 +9987,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return matchesTagFilter(image.getTags(), name, values, Ec2Service::matchesFilterValue); } - private boolean matchesTagFilter(List resourceTags, String filterName, List values, - BiPredicate, String> valueMatcher) { + static boolean matchesTagFilter(List resourceTags, String filterName, List values, + BiPredicate, String> valueMatcher) { List tags = resourceTags == null ? List.of() : resourceTags; if (filterName.startsWith("tag:")) { String key = filterName.substring("tag:".length()); @@ -10047,7 +10047,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab }; } - private static boolean matchesFilterValue(List patterns, String value) { + static boolean matchesFilterValue(List patterns, String value) { if (patterns == null || patterns.isEmpty()) { return true; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java index 225b1b7967..2d51460fc8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java @@ -5654,6 +5654,80 @@ class Ec2IntegrationTest { .body("Response.Errors.Error.Code", equalTo("InvalidIpamScopeId.NotFound")); } + @Test + @Order(3225) + void describeIpamPoolsAppliesFiltersOverQuery() { + String ipamId = given() + .formParam("Action", "CreateIpam") + .formParam("OperatingRegion.1.RegionName", "us-east-1") + .formParam("OperatingRegion.2.RegionName", "eu-west-1") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().path("CreateIpamResponse.ipam.ipamId"); + String scopeId = given() + .formParam("Action", "DescribeIpams") + .formParam("IpamId.1", ipamId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().path("DescribeIpamsResponse.ipamSet.item.privateDefaultScopeId"); + String poolId = given() + .formParam("Action", "CreateIpamPool") + .formParam("IpamScopeId", scopeId) + .formParam("AddressFamily", "ipv4") + .formParam("Locale", "eu-west-1") + .formParam("Description", "filter-target-pool") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().path("CreateIpamPoolResponse.ipamPool.ipamPoolId"); + + // scope-id pins the query to this test's pool; the other filter is the one under test + assertIpamPoolFilter("locale", "eu-west-1", scopeId, poolId, true); + assertIpamPoolFilter("locale", "eu-west-9", scopeId, poolId, false); + assertIpamPoolFilter("address-family", "ipv4", scopeId, poolId, true); + assertIpamPoolFilter("address-family", "ipv6", scopeId, poolId, false); + assertIpamPoolFilter("description", "filter-target-*", scopeId, poolId, true); + assertIpamPoolFilter("description", "no-such-pool", scopeId, poolId, false); + assertIpamPoolFilter("ipam-scope-type", "private", scopeId, poolId, true); + assertIpamPoolFilter("ipam-scope-type", "public", scopeId, poolId, false); + assertIpamPoolFilter("tag:Env", "prod", scopeId, poolId, false); + + // AND across two non-scope filters: locale matches, description does not + List anded = given() + .formParam("Action", "DescribeIpamPools") + .formParam("Filter.1.Name", "locale") + .formParam("Filter.1.Value.1", "eu-west-1") + .formParam("Filter.2.Name", "description") + .formParam("Filter.2.Value.1", "no-such-pool") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().xmlPath() + .getList("DescribeIpamPoolsResponse.ipamPoolSet.item.ipamPoolId"); + assertEquals(List.of(), anded); + + given() + .formParam("Action", "DescribeIpamPools") + .formParam("Filter.1.Name", "no-such-filter") + .formParam("Filter.1.Value.1", "x") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(400).body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")); + } + + private void assertIpamPoolFilter(String name, String value, String scopeId, String poolId, + boolean expectPool) { + List ids = given() + .formParam("Action", "DescribeIpamPools") + .formParam("Filter.1.Name", "ipam-scope-id") + .formParam("Filter.1.Value.1", scopeId) + .formParam("Filter.2.Name", name) + .formParam("Filter.2.Value.1", value) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().xmlPath() + .getList("DescribeIpamPoolsResponse.ipamPoolSet.item.ipamPoolId"); + assertEquals(expectPool ? List.of(poolId) : List.of(), ids, name + "=" + value); + } + @Test @Order(323) void associateIpamByoasnSuccess() { diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamServiceTest.java index aef9bdbe8e..3f48e13a54 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamServiceTest.java @@ -17,13 +17,20 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class Ec2IpamServiceTest { @@ -265,9 +272,54 @@ class Ec2IpamServiceTest { Ipam ipam = service.createIpam(REGION, null, List.of(REGION)); IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), REGION, null, "ipv4", null); - assertEquals(1, service.describeIpamPools(REGION, List.of(pool.getIpamPoolId())).size()); + assertEquals(1, service.describeIpamPools(REGION, List.of(pool.getIpamPoolId()), List.of()).size()); assertThrows(AwsException.class, - () -> service.describeIpamPools(REGION, List.of("ipam-pool-doesnotexist"))); + () -> service.describeIpamPools(REGION, List.of("ipam-pool-doesnotexist"), List.of())); + } + + @Test + void describeIpamPoolsFiltersOnTags() { + Ipam ipam = service.createIpam(REGION, null, List.of(REGION)); + IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), + REGION, null, "ipv4", null); + // no API path tags a pool yet, so seed the stored object directly + pool.getTags().add(new Tag("Env", "prod")); + assertEquals(1, service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("tag:Env", List.of("prod")))).size()); + assertEquals(0, service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("tag:Env", List.of("dev")))).size()); + assertEquals(1, service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("tag-key", List.of("Env")))).size()); + assertEquals(0, service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("tag-key", List.of("Team")))).size()); + assertEquals(1, service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("tag:Env", List.of("pr*")))).size()); + // a pool restored with a null tag list matches no tag filter instead of failing the request + pool.setTags(null); + assertEquals(0, service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("tag:Env", List.of("prod")))).size()); + } + + @Test + void describeIpamPoolsFiltersOnDepthNetmaskAndUnmodelledNames() { + Ipam ipam = service.createIpam(REGION, null, List.of(REGION)); + IpamPool top = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), + REGION, null, "ipv4", null); + IpamPool child = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), + REGION, top.getIpamPoolId(), "ipv4", null); + child.setAllocationMinNetmaskLength(24); + String scope = ipam.getPrivateDefaultScopeId(); + List>> inScope = List.of(Map.entry("ipam-scope-id", List.of(scope))); + BiFunction count = (name, value) -> + service.describeIpamPools(REGION, List.of(), List.of(inScope.get(0), + Map.entry(name, List.of(value)))).size(); + assertEquals(1, count.apply("pool-depth", "1")); + assertEquals(1, count.apply("pool-depth", "2")); + assertEquals(0, count.apply("pool-depth", "3")); + assertEquals(1, count.apply("allocation-min-netmask-length", "24")); + assertEquals(0, count.apply("publicly-advertisable", "true")); + assertEquals(0, count.apply("aws-service", "ec2")); + assertThrows(AwsException.class, () -> count.apply("no-such-filter", "x")); } @Test @@ -335,7 +387,7 @@ class Ec2IpamServiceTest { void allocateSkipsSpaceProvisionedToChildPools() { IpamPool parent = poolWith("10.0.0.0/16"); IpamPool child = service.createIpamPool(REGION, - service.describeIpamPools(REGION, List.of(parent.getIpamPoolId())) + service.describeIpamPools(REGION, List.of(parent.getIpamPoolId()), List.of()) .get(0).getIpamScopeId(), REGION, parent.getIpamPoolId(), "ipv4", "child"); service.provisionIpamPoolCidr(REGION, child.getIpamPoolId(), "10.0.0.0/24"); @@ -432,7 +484,7 @@ class Ec2IpamServiceTest { REGION, null, "ipv4", "second", "000000000000", "pool-token"); assertEquals(first.getIpamPoolId(), replay.getIpamPoolId()); - assertEquals(1, service.describeIpamPools(REGION, List.of()).size()); + assertEquals(1, service.describeIpamPools(REGION, List.of(), List.of()).size()); } @Test @@ -518,6 +570,55 @@ class Ec2IpamServiceTest { return new SharedPoolFixture(service, pools, ipams, caller, ipam, pool); } + @Test + void describingASharedPoolFiltersOnTheOwnersScopeAndIpam() { + SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount(); + List id = List.of(fixture.pool().getIpamPoolId()); + String scopeArn = fixture.ipam().getScopes().stream() + .filter(s -> s.getIpamScopeId().equals(fixture.pool().getIpamScopeId())) + .findFirst().orElseThrow().getIpamScopeArn(); + BiFunction count = (name, value) -> fixture.service() + .describeIpamPools(REGION, id, List.of(Map.entry(name, List.of(value)))).size(); + assertEquals(1, count.apply("ipam-scope-type", "private")); + assertEquals(1, count.apply("ipam-scope-arn", scopeArn)); + assertEquals(1, count.apply("ipam-arn", fixture.ipam().getIpamArn())); + assertEquals(1, count.apply("ipam-region", REGION)); + } + + @Test + @SuppressWarnings("unchecked") + void poolFieldFiltersDoNotScanTheIpamStore() { + EmulatorConfig config = mock(EmulatorConfig.class); + when(config.defaultAccountId()).thenReturn("000000000000"); + InMemoryStorage ipams = spy(new InMemoryStorage<>()); + Ec2IpamService spied = new Ec2IpamService(config, + ipams, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + Ipam ipam = spied.createIpam(REGION, null, List.of(REGION)); + spied.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), REGION, null, "ipv4", "d"); + clearInvocations(ipams); + assertEquals(1, spied.describeIpamPools(REGION, List.of(), List.of( + Map.entry("locale", List.of(REGION)), Map.entry("description", List.of("d")), + Map.entry("address-family", List.of("ipv4")))).size()); + verify(ipams, never()).scan(any()); + } + + @Test + void poolDepthFilterSurvivesADeletedParent() { + Ipam ipam = service.createIpam(REGION, null, List.of(REGION)); + String scope = ipam.getPrivateDefaultScopeId(); + IpamPool top = service.createIpamPool(REGION, scope, REGION, null, "ipv4", null); + IpamPool mid = service.createIpamPool(REGION, scope, REGION, top.getIpamPoolId(), "ipv4", null); + IpamPool leaf = service.createIpamPool(REGION, scope, REGION, mid.getIpamPoolId(), "ipv4", null); + service.deleteIpamPool(REGION, top.getIpamPoolId()); + // depth counts the ancestors still present: mid is now top-level, leaf sits under it + List depth1 = service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("pool-depth", List.of("1")))); + assertEquals(List.of(mid.getIpamPoolId()), depth1.stream().map(IpamPool::getIpamPoolId).toList()); + List depth2 = service.describeIpamPools(REGION, List.of(), + List.of(Map.entry("pool-depth", List.of("2")))); + assertEquals(List.of(leaf.getIpamPoolId()), depth2.stream().map(IpamPool::getIpamPoolId).toList()); + } + @Test void modifyingAnotherAccountsPoolIsRejected() { SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount(); @@ -627,7 +728,7 @@ class Ec2IpamServiceTest { () -> service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), REGION, null, "ipv5", "bad address family")); assertEquals("InvalidParameterValue", error.getErrorCode()); - assertTrue(service.describeIpamPools(REGION, List.of()).isEmpty(), + assertTrue(service.describeIpamPools(REGION, List.of(), List.of()).isEmpty(), "a rejected CreateIpamPool must not have stored a pool"); }