fix(ec2): apply DescribeIpamPools filters (#7039)

* fix(ec2): apply DescribeIpamPools filters

* fix(ec2): resolve DescribeIpamPools scope filters from the pool owner's IPAM

- ipam-scope-type, ipam-scope-arn, ipam-arn and ipam-region now resolve the
  scope through the pool's own IPAM across account partitions, so a
  RAM-shared pool described by id matches them.
- pool-depth stops at a deleted ancestor instead of failing the request
  with InvalidIpamPoolId.NotFound; an orphaned pool counts as top-level.
- The scope lookup runs only for filters that need it, once per scope per
  request, so pool-field filters no longer scan the IPAM store.

* fix(ec2): log the tolerated NotFound in IPAM pool scope and depth lookups

AGENTS.md requires a tolerated exception to be logged. Both catches can
only see InvalidIpamId.NotFound / InvalidIpamPoolId.NotFound (create
rejects a blank source id), so they stay unnarrowed and log at debug.

* refactor(ec2): reuse Ec2Service.matchesTagFilter for IPAM pool tag filters

matchesTagFilter holds no instance state, so make it static and
package-private and let matchesPoolFilter call it instead of repeating
the tag:<key> / tag-key branch. The shared helper also treats a null tag
list as no tags, so a pool restored with tags=null no longer fails
DescribeIpamPools with a NullPointerException.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-31 10:00:34 -04:00
1 parent 01ecd4f8da
commit 759b6d1f4b
5 files changed
+278 -21

No files matched your search

@@ -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<IpamPool> describeIpamPools(String region, List<String> ipamPoolIds) {
/** DescribeIpamPools filter names, tag:&lt;key&gt; 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<String> 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<IpamPool> describeIpamPools(String region, List<String> ipamPoolIds,
List<Map.Entry<String, List<String>>> filters) {
Ec2Service.requireSupportedFilters(filters.stream().map(Map.Entry::getKey).toList(), POOL_FILTERS);
List<IpamPool> candidates;
if (ipamPoolIds != null && !ipamPoolIds.isEmpty()) {
List<IpamPool> result = new ArrayList<>();
candidates = new ArrayList<>();
for (String id : ipamPoolIds) {
result.add(requirePool(region, id));
candidates.add(requirePool(region, id));
}
return result;
}
List<IpamPool> 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<String, Optional<ScopeOfIpam>> 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<ScopeOfIpam> 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<String> values,
Supplier<Optional<ScopeOfIpam>> 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) {
@@ -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");
@@ -6398,7 +6398,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
private void requireSupportedFilters(Collection<String> filterNames, Set<String> supportedFilters) {
static void requireSupportedFilters(Collection<String> filterNames, Set<String> 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<Tag> resourceTags, String filterName, List<String> values,
BiPredicate<List<String>, String> valueMatcher) {
static boolean matchesTagFilter(List<Tag> resourceTags, String filterName, List<String> values,
BiPredicate<List<String>, String> valueMatcher) {
List<Tag> 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<String> patterns, String value) {
static boolean matchesFilterValue(List<String> patterns, String value) {
if (patterns == null || patterns.isEmpty()) {
return true;
}
@@ -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<String> 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<String> 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() {
@@ -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<Map.Entry<String, List<String>>> inScope = List.of(Map.entry("ipam-scope-id", List.of(scope)));
BiFunction<String, String, Integer> 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<String> id = List.of(fixture.pool().getIpamPoolId());
String scopeArn = fixture.ipam().getScopes().stream()
.filter(s -> s.getIpamScopeId().equals(fixture.pool().getIpamScopeId()))
.findFirst().orElseThrow().getIpamScopeArn();
BiFunction<String, String, Integer> 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<String, Ipam> 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<IpamPool> 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<IpamPool> 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");
}