fix(ec2): keep IPAM pool and allocation tags (#8158)

This commit is contained in:
soreavis authored and GitHub committed 2026-11-14 15:16:29 -04:00
1 parent 9cd601fea9
commit 66bec3b89b
7 files changed
+461 -53

No files matched your search

+5 -3
View File
@@ -1414,13 +1414,13 @@ All three actions honor `DryRun`. A request that would otherwise succeed returns
| DescribeIpams | Lists or returns stored IPAMs. |
| ModifyIpam | Updates an IPAM's description, tier, metered account and operating regions. |
| DeleteIpam | Deletes an IPAM and, leniently, the pools that belong to it. |
| CreateIpamPool | Creates a pool under a scope, optionally sourced from a parent pool. |
| CreateIpamPool | Creates a pool under a scope, optionally sourced from a parent pool. An `ipam-pool` `TagSpecification` tags it. |
| DescribeIpamPools | Lists or returns stored pools. |
| ModifyIpamPool | Updates a pool's description, auto-import flag and netmask-length bounds. |
| DeleteIpamPool | Deletes a pool. |
| ProvisionIpamPoolCidr | Provisions a CIDR onto a pool, validated against its source pool. |
| GetIpamPoolCidrs | Returns a pool's provisioned CIDRs. |
| AllocateIpamPoolCidr | Allocates a CIDR from a pool, by explicit CIDR or by netmask length. |
| AllocateIpamPoolCidr | Allocates a CIDR from a pool, by explicit CIDR or by netmask length. An `ipam-pool-allocation` `TagSpecification` tags the allocation. |
| ReleaseIpamPoolAllocation | Releases an allocation, returning its space to the pool. |
| GetIpamPoolAllocations | Returns a pool's live allocations. |
| AssociateIpamByoasn | Associates a BYOASN with a CIDR. |
@@ -1431,9 +1431,11 @@ This is what LZA needs end to end: the Organization stage delegates the IPAM adm
Allocation is real rather than recorded. `AllocateIpamPoolCidr` by netmask length hands out the first free block that fits, skipping both live allocations and any space already provisioned onward to child pools, and reports `InsufficientCidrBlocks` when nothing fits. An explicit `Cidr` must fall inside a provisioned CIDR and must not overlap an existing allocation. `ProvisionIpamPoolCidr` on a pool with a source pool requires the CIDR to sit inside one of the parent's provisioned CIDRs. Releasing an allocation returns its space, so the next allocation of the same size reuses it.
Pool and allocation tags are kept with the other EC2 tags, in the pool's own region even when an IPAM action is called from another region, so `CreateTags`, `DeleteTags` and `DescribeTags` in the pool's region work on them. `DescribeIpamPools` returns a pool's tags and its `tag:<key>` and `tag-key` filters match them; `AllocateIpamPoolCidr` and `GetIpamPoolAllocations` return an allocation's. Releasing an allocation removes its tags, and deleting a pool, directly or through `DeleteIpam`, removes the pool's tags and those of the allocations it still held. Tags are per account, as for every EC2 resource: the tags another account gives an allocation it makes from a shared pool stay in that account, so the owner's `GetIpamPoolAllocations` does not show them. The allocation records that account as its `resourceOwner`, and releasing the allocation or deleting its pool removes its tags both there and in the pool owner's account.
`CreateIpam`, `CreateIpamPool`, `ProvisionIpamPoolCidr` and `AllocateIpamPoolCidr` honour `ClientToken` — the four IPAM operations that model it. A replay returns what the first call produced rather than creating a second resource: the same pool, the same provisioned CIDR, the same allocation id and CIDR, with pool consumption unchanged. This matters most on `AllocateIpamPoolCidr`, which LZA's `get-ipam-subnet-cidr` Lambda retries; without it each retry would burn another distinct CIDR out of the pool. Parameter differences on a replay are ignored rather than rejected as `IdempotentParameterMismatch`, and the token is not echoed in the response, matching the AWS output shapes. A token is scoped to the account that used it.
Pool lookups deliberately fall back to an id-only scan across accounts, so a RAM-shared pool resolves from a workload account and region. That fallback covers reads and allocation only: `AllocateIpamPoolCidr` from an account that does not own the pool succeeds and writes the allocation back to the owner's partition rather than forking a copy into the caller's. Mutations of the pool itself — `ModifyIpamPool`, `DeleteIpamPool`, `ProvisionIpamPoolCidr` — are owner-only, as are `ModifyIpam` and `DeleteIpam`, and a non-owner gets `InvalidIpamPoolId.NotFound` or `InvalidIpamId.NotFound`, which is what AWS returns for a resource you cannot act on. `ReleaseIpamPoolAllocation` stays on the cross-account path, since no per-allocation caller is tracked to check ownership against.
Pool lookups deliberately fall back to an id-only scan across accounts, so a RAM-shared pool resolves from a workload account and region. That fallback covers reads and allocation only: `AllocateIpamPoolCidr` from an account that does not own the pool succeeds and writes the allocation back to the owner's partition rather than forking a copy into the caller's. Mutations of the pool itself — `ModifyIpamPool`, `DeleteIpamPool`, `ProvisionIpamPoolCidr` — are owner-only, as are `ModifyIpam` and `DeleteIpam`, and a non-owner gets `InvalidIpamPoolId.NotFound` or `InvalidIpamId.NotFound`, which is what AWS returns for a resource you cannot act on. `ReleaseIpamPoolAllocation` stays on the cross-account path and does not check which account made the allocation.
The delegated administrator is stored organization-wide rather than per account, so every member account reads the same value and delegating a second, different account conflicts with `InvalidParameterValue` no matter which account asks.
@@ -70,17 +70,19 @@ public class Ec2IpamService {
// org-wide settings, e.g. the delegated admin account
private final StorageBackend<String, String> settings;
private final StorageBackend<String, AsnAssociation> asnAssociations;
// Pool and allocation tags live in EC2's tag store, so CreateTags, DeleteTags and DescribeTags see them.
private final Ec2Service ec2;
private final Instance<RequestContext> requestContextInstance;
@Inject
public Ec2IpamService(EmulatorConfig config, StorageFactory storageFactory,
public Ec2IpamService(EmulatorConfig config, StorageFactory storageFactory, Ec2Service ec2,
Instance<RequestContext> requestContextInstance) {
this(config,
storageFactory.create("ec2", "ec2-ipams.json", new TypeReference<Map<String, Ipam>>() {}),
storageFactory.create("ec2", "ec2-ipam-pools.json", new TypeReference<Map<String, IpamPool>>() {}),
storageFactory.create("ec2", "ec2-ipam-settings.json", new TypeReference<Map<String, String>>() {}),
storageFactory.create("ec2", "ec2-ipam-asn-associations.json", new TypeReference<Map<String, AsnAssociation>>() {}),
requestContextInstance);
ec2, requestContextInstance);
}
// Package-private for hermetic tests (pass in-memory StorageBackends directly).
@@ -88,8 +90,9 @@ public class Ec2IpamService {
StorageBackend<String, Ipam> ipams,
StorageBackend<String, IpamPool> pools,
StorageBackend<String, String> settings,
StorageBackend<String, AsnAssociation> asnAssociations) {
this(config, ipams, pools, settings, asnAssociations, null);
StorageBackend<String, AsnAssociation> asnAssociations,
Ec2Service ec2) {
this(config, ipams, pools, settings, asnAssociations, ec2, null);
}
Ec2IpamService(EmulatorConfig config,
@@ -97,12 +100,14 @@ public class Ec2IpamService {
StorageBackend<String, IpamPool> pools,
StorageBackend<String, String> settings,
StorageBackend<String, AsnAssociation> asnAssociations,
Ec2Service ec2,
Instance<RequestContext> requestContextInstance) {
this.config = config;
this.ipams = ipams;
this.pools = pools;
this.settings = settings;
this.asnAssociations = asnAssociations;
this.ec2 = ec2;
this.requestContextInstance = requestContextInstance;
}
@@ -411,6 +416,7 @@ public class Ec2IpamService {
for (IpamPool pool : pools.scan(k -> true)) {
if (ipamId.equals(pool.getIpamId())) {
pools.delete(key(pool.getRegion(), pool.getIpamPoolId()));
deletePoolTags(ownedIpam.accountId(), pool);
}
}
ipam.setState("delete-complete");
@@ -472,7 +478,7 @@ public class Ec2IpamService {
String sourceIpamPoolId, String addressFamily, String description,
String ownerId) {
return createIpamPool(region, ipamScopeId, locale, sourceIpamPoolId, addressFamily,
description, ownerId, null);
description, ownerId, null, List.of());
}
/**
@@ -482,7 +488,7 @@ public class Ec2IpamService {
*/
public IpamPool createIpamPool(String region, String ipamScopeId, String locale,
String sourceIpamPoolId, String addressFamily, String description,
String requestedOwnerId, String clientToken) {
String requestedOwnerId, String clientToken, List<Tag> tags) {
// Same null-means-caller resolution as createIpam.
String ownerId = requestedOwnerId != null ? requestedOwnerId : callerAccountId();
if (ipamScopeId == null || ipamScopeId.isBlank()) {
@@ -516,6 +522,9 @@ public class Ec2IpamService {
pool.setState("create-complete");
pool.setClientToken(clientToken != null && !clientToken.isBlank() ? clientToken : null);
pools.put(key(region, pool.getIpamPoolId()), pool);
if (!tags.isEmpty()) {
ec2.createTags(region, List.of(pool.getIpamPoolId()), tags);
}
LOG.infov("Created IPAM pool {0} (scope {1}, source {2})",
pool.getIpamPoolId(), ipamScopeId, sourceIpamPoolId);
return pool;
@@ -607,7 +616,8 @@ public class Ec2IpamService {
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);
return Ec2Service.matchesTagFilter(ec2.resourceTags(pool.getRegion(), pool.getIpamPoolId()), name, values,
Ec2Service::matchesFilterValue);
}
String value = switch (name) {
case "address-family" -> pool.getAddressFamily();
@@ -656,10 +666,29 @@ public class Ec2IpamService {
OwnedPool ownedPool = requireOwnedPoolForMutation(region, ipamPoolId);
IpamPool pool = ownedPool.pool();
deletePool(ownedPool);
deletePoolTags(ownedPool.accountId(), pool);
pool.setState("delete-complete");
return pool;
}
/** A pool's tags go with it, and so do those of the allocations it still held. */
private void deletePoolTags(String ownerAccountId, IpamPool pool) {
ec2.removeTags(ownerAccountId, pool.getRegion(), pool.getIpamPoolId());
for (IpamPoolAllocation allocation : pool.getAllocations()) {
deleteAllocationTags(ownerAccountId, pool.getRegion(), allocation);
}
}
/** The pool's owner and the account that made the allocation each keep their own tags on it; both go. */
private void deleteAllocationTags(String ownerAccountId, String region, IpamPoolAllocation allocation) {
String id = allocation.getIpamPoolAllocationId();
ec2.removeTags(ownerAccountId, region, id);
String maker = allocation.getResourceOwner();
if (maker != null && !maker.equals(ownerAccountId)) {
ec2.removeTags(maker, region, id);
}
}
public IpamPoolCidr provisionIpamPoolCidr(String region, String ipamPoolId, String cidr) {
return provisionIpamPoolCidr(region, ipamPoolId, cidr, null);
}
@@ -708,7 +737,7 @@ public class Ec2IpamService {
public IpamPoolAllocation allocateIpamPoolCidr(String region, String ipamPoolId,
Integer netmaskLength, String cidr,
String description) {
return allocateIpamPoolCidr(region, ipamPoolId, netmaskLength, cidr, description, null);
return allocateIpamPoolCidr(region, ipamPoolId, netmaskLength, cidr, description, null, List.of());
}
/**
@@ -718,7 +747,7 @@ public class Ec2IpamService {
*/
public IpamPoolAllocation allocateIpamPoolCidr(String region, String ipamPoolId,
Integer netmaskLength, String cidr,
String description, String clientToken) {
String description, String clientToken, List<Tag> tags) {
OwnedPool ownedPool = requireOwnedPool(region, ipamPoolId);
IpamPool pool = ownedPool.pool();
Optional<IpamPoolAllocation> replay = Ec2ClientTokens.replay(clientToken, () -> pool.getAllocations().stream(),
@@ -759,10 +788,13 @@ public class Ec2IpamService {
allocation.setCidr(chosen);
allocation.setDescription(description);
allocation.setResourceType("custom");
allocation.setResourceOwner(config.defaultAccountId());
allocation.setResourceOwner(callerAccountId());
allocation.setClientToken(clientToken != null && !clientToken.isBlank() ? clientToken : null);
pool.getAllocations().add(allocation);
savePool(ownedPool);
if (!tags.isEmpty()) {
ec2.createTags(pool.getRegion(), List.of(allocation.getIpamPoolAllocationId()), tags);
}
LOG.infov("Allocated {0} from IPAM pool {1}", chosen, ipamPoolId);
return allocation;
}
@@ -771,17 +803,22 @@ public class Ec2IpamService {
String ipamPoolAllocationId, String cidr) {
OwnedPool ownedPool = requireOwnedPool(region, ipamPoolId);
IpamPool pool = ownedPool.pool();
boolean removed = pool.getAllocations().removeIf(a ->
(ipamPoolAllocationId != null && ipamPoolAllocationId.equals(a.getIpamPoolAllocationId()))
|| (ipamPoolAllocationId == null && cidr != null && cidr.equals(a.getCidr())));
if (!removed) {
List<IpamPoolAllocation> released = pool.getAllocations().stream()
.filter(a -> (ipamPoolAllocationId != null && ipamPoolAllocationId.equals(a.getIpamPoolAllocationId()))
|| (ipamPoolAllocationId == null && cidr != null && cidr.equals(a.getCidr())))
.toList();
if (released.isEmpty()) {
String identifier = ipamPoolAllocationId != null
? ipamPoolAllocationId
: "for CIDR " + cidr;
throw new AwsException("InvalidIpamPoolAllocationId.NotFound",
"Allocation " + identifier + " not found in pool " + ipamPoolId + ".", 400);
}
pool.getAllocations().removeAll(released);
savePool(ownedPool);
for (IpamPoolAllocation allocation : released) {
deleteAllocationTags(ownedPool.accountId(), pool.getRegion(), allocation);
}
return true;
}
@@ -789,6 +826,11 @@ public class Ec2IpamService {
return requirePool(region, ipamPoolId).getAllocations();
}
/** The pool's own region, where its tags and its allocations' tags live, whichever region the caller is in. */
public String poolRegion(String region, String ipamPoolId) {
return requirePool(region, ipamPoolId).getRegion();
}
/**
* Space already unavailable in a pool: live allocations plus every CIDR
* provisioned onward to child pools.
@@ -2426,7 +2426,8 @@ public class Ec2QueryHandler {
p.getFirst("AddressFamily"),
p.getFirst("Description"),
null,
p.getFirst("ClientToken"));
p.getFirst("ClientToken"),
parseTagsForResource(p, "ipam-pool"));
XmlBuilder xml = new XmlBuilder()
.start("CreateIpamPoolResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString());
@@ -2517,11 +2518,13 @@ public class Ec2QueryHandler {
parseOptionalInt(p.getFirst("NetmaskLength"), "NetmaskLength"),
p.getFirst("Cidr"),
p.getFirst("Description"),
p.getFirst("ClientToken"));
p.getFirst("ClientToken"),
parseTagsForResource(p, "ipam-pool-allocation"));
XmlBuilder xml = new XmlBuilder()
.start("AllocateIpamPoolCidrResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString());
writeIpamPoolAllocation(xml, "ipamPoolAllocation", allocation);
writeIpamPoolAllocation(xml, "ipamPoolAllocation", allocation,
ipamService.poolRegion(region, p.getFirst("IpamPoolId")));
xml.end("AllocateIpamPoolCidrResponse");
return xmlResponse(xml.build());
}
@@ -2540,13 +2543,14 @@ public class Ec2QueryHandler {
}
private Response handleGetIpamPoolAllocations(MultivaluedMap<String, String> p, String region) {
String poolRegion = ipamService.poolRegion(region, p.getFirst("IpamPoolId"));
XmlBuilder xml = new XmlBuilder()
.start("GetIpamPoolAllocationsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("ipamPoolAllocationSet");
for (IpamPoolAllocation allocation
: ipamService.getIpamPoolAllocations(region, p.getFirst("IpamPoolId"))) {
writeIpamPoolAllocation(xml, "item", allocation);
writeIpamPoolAllocation(xml, "item", allocation, poolRegion);
}
xml.end("ipamPoolAllocationSet").end("GetIpamPoolAllocationsResponse");
return xmlResponse(xml.build());
@@ -2607,18 +2611,22 @@ public class Ec2QueryHandler {
if (pool.getAllocationDefaultNetmaskLength() != null) {
xml.elem("allocationDefaultNetmaskLength", String.valueOf(pool.getAllocationDefaultNetmaskLength()));
}
xml.end(wrapper);
xml.raw(tagSetXml(service.resourceTags(pool.getRegion(), pool.getIpamPoolId())))
.end(wrapper);
}
private void writeIpamPoolAllocation(XmlBuilder xml, String wrapper, IpamPoolAllocation allocation) {
private void writeIpamPoolAllocation(XmlBuilder xml, String wrapper, IpamPoolAllocation allocation,
String poolRegion) {
xml.start(wrapper)
.elem("ipamPoolAllocationId", allocation.getIpamPoolAllocationId())
.elem("cidr", allocation.getCidr())
.elem("resourceType", allocation.getResourceType());
.elem("resourceType", allocation.getResourceType())
.elem("resourceOwner", allocation.getResourceOwner());
if (allocation.getDescription() != null) {
xml.elem("description", allocation.getDescription());
}
xml.end(wrapper);
xml.raw(tagSetXml(service.resourceTags(poolRegion, allocation.getIpamPoolAllocationId())))
.end(wrapper);
}
private Response handleCreateVpcEndpoint(MultivaluedMap<String, String> p, String region) {
@@ -11099,6 +11099,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
tags.delete(key(region, resourceId));
}
/** Drops a deleted resource's tags in {@code accountId}, or in the caller's account when that is null. */
public void removeTags(String accountId, String region, String resourceId) {
if (tags instanceof AccountAwareStorageBackend<?> tagsByAccount && accountId != null) {
tagsByAccount.deleteForAccount(accountId, key(region, resourceId));
} else {
removeTags(region, resourceId);
}
}
/** The tags currently on one resource in {@code region}, as CreateTags and DeleteTags maintain them. */
public List<Tag> resourceTags(String region, String resourceId) {
return List.copyOf(tagsOf(region, resourceId).orElse(List.of()));
@@ -11267,6 +11276,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (resourceId.startsWith("sir-")) {
return "spot-instances-request";
}
// Checked before the pool prefix, which it starts with.
if (resourceId.startsWith("ipam-pool-alloc-")) {
return "ipam-pool-allocation";
}
if (resourceId.startsWith("ipam-pool-")) {
return "ipam-pool";
}
return "unknown";
}
@@ -27,7 +27,6 @@ public class IpamPool {
private Integer allocationDefaultNetmaskLength;
private List<IpamPoolCidr> provisionedCidrs = new ArrayList<>();
private List<IpamPoolAllocation> allocations = new ArrayList<>();
private List<Tag> tags = new ArrayList<>();
/** Idempotency token of the CreateIpamPool call that created this pool. */
private String clientToken;
@@ -90,9 +89,6 @@ public class IpamPool {
public List<IpamPoolAllocation> getAllocations() { return allocations; }
public void setAllocations(List<IpamPoolAllocation> allocations) { this.allocations = allocations; }
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
}
@@ -58,6 +58,9 @@ class Ec2IntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
/** A second account, which reaches the default account's IPAM pools by id. */
private static final String WORKLOAD_AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=000000000002/20260205/us-east-1/ec2/aws4_request";
private static String instanceId;
private static String vpcId;
@@ -5966,6 +5969,219 @@ class Ec2IntegrationTest {
assertEquals(expectPool ? List.of(poolId) : List.of(), ids, name + "=" + value);
}
@Test
@Order(3226)
void ipamPoolAndAllocationTagsRoundTripOverQuery() {
String ipamId = given()
.formParam("Action", "CreateIpam")
.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("TagSpecification.1.ResourceType", "ipam-pool")
.formParam("TagSpecification.1.Tag.1.Key", "team")
.formParam("TagSpecification.1.Tag.1.Value", "red")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("CreateIpamPoolResponse.ipamPool.tagSet.item.key", equalTo("team"))
.extract().path("CreateIpamPoolResponse.ipamPool.ipamPoolId");
given()
.formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id")
.formParam("Filter.1.Value.1", poolId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DescribeTagsResponse.tagSet.item.key", equalTo("team"))
.body("DescribeTagsResponse.tagSet.item.value", equalTo("red"))
.body("DescribeTagsResponse.tagSet.item.resourceType", equalTo("ipam-pool"));
given()
.formParam("Action", "CreateTags")
.formParam("ResourceId.1", poolId)
.formParam("Tag.1.Key", "env")
.formParam("Tag.1.Value", "dev")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200);
// Read back from another region: the pool resolves there by id, and its tags come with it.
String otherRegionAuth = "AWS4-HMAC-SHA256 Credential=test/20260205/us-west-2/ec2/aws4_request";
given()
.formParam("Action", "DescribeIpamPools")
.formParam("IpamPoolId.1", poolId)
.header("Authorization", otherRegionAuth)
.when().post("/")
.then().statusCode(200)
.body("DescribeIpamPoolsResponse.ipamPoolSet.item.tagSet.item.key", containsInAnyOrder("team", "env"));
assertIpamPoolFilter("tag:env", "dev", scopeId, poolId, true);
assertIpamPoolFilter("tag-key", "team", scopeId, poolId, true);
given()
.formParam("Action", "ProvisionIpamPoolCidr")
.formParam("IpamPoolId", poolId)
.formParam("Cidr", "10.0.0.0/16")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200);
String allocationId = given()
.formParam("Action", "AllocateIpamPoolCidr")
.formParam("IpamPoolId", poolId)
.formParam("NetmaskLength", "24")
.formParam("TagSpecification.1.ResourceType", "ipam-pool-allocation")
.formParam("TagSpecification.1.Tag.1.Key", "team")
.formParam("TagSpecification.1.Tag.1.Value", "red")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("AllocateIpamPoolCidrResponse.ipamPoolAllocation.tagSet.item.key", equalTo("team"))
.extract().path("AllocateIpamPoolCidrResponse.ipamPoolAllocation.ipamPoolAllocationId");
given()
.formParam("Action", "GetIpamPoolAllocations")
.formParam("IpamPoolId", poolId)
.header("Authorization", otherRegionAuth)
.when().post("/")
.then().statusCode(200)
.body("GetIpamPoolAllocationsResponse.ipamPoolAllocationSet.item.tagSet.item.value", equalTo("red"));
given()
.formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id")
.formParam("Filter.1.Value.1", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DescribeTagsResponse.tagSet.item.resourceType", equalTo("ipam-pool-allocation"));
given()
.formParam("Action", "DeleteIpamPool")
.formParam("IpamPoolId", poolId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200);
given()
.formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id")
.formParam("Filter.1.Value.1", poolId)
.formParam("Filter.1.Value.2", allocationId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DescribeTagsResponse.tagSet.item.size()", equalTo(0));
}
@Test
@Order(3227)
void anotherAccountsAllocationTagsGoWhenTheOwnerReleasesItOrDeletesThePool() {
String ipamId = given()
.formParam("Action", "CreateIpam")
.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")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200).extract().path("CreateIpamPoolResponse.ipamPool.ipamPoolId");
given()
.formParam("Action", "ProvisionIpamPoolCidr")
.formParam("IpamPoolId", poolId)
.formParam("Cidr", "10.0.0.0/16")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200);
String released = allocateTaggedFromSharedPool(poolId);
given()
.formParam("Action", "GetIpamPoolAllocations")
.formParam("IpamPoolId", poolId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("GetIpamPoolAllocationsResponse.ipamPoolAllocationSet.item.resourceOwner", equalTo("000000000002"));
given()
.formParam("Action", "CreateTags")
.formParam("ResourceId.1", released)
.formParam("Tag.1.Key", "team")
.formParam("Tag.1.Value", "owner")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200);
given()
.formParam("Action", "ReleaseIpamPoolAllocation")
.formParam("IpamPoolId", poolId)
.formParam("IpamPoolAllocationId", released)
.formParam("Cidr", "10.0.0.0/24")
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200);
assertNoTagsInEitherAccount(released);
String heldByThePool = allocateTaggedFromSharedPool(poolId);
given()
.formParam("Action", "DeleteIpamPool")
.formParam("IpamPoolId", poolId)
.header("Authorization", AUTH_HEADER)
.when().post("/")
.then().statusCode(200);
assertNoTagsInEitherAccount(heldByThePool);
}
/** The second account allocates from the default account's pool and tags the allocation in its own account. */
private String allocateTaggedFromSharedPool(String poolId) {
String allocationId = given()
.formParam("Action", "AllocateIpamPoolCidr")
.formParam("IpamPoolId", poolId)
.formParam("NetmaskLength", "24")
.formParam("TagSpecification.1.ResourceType", "ipam-pool-allocation")
.formParam("TagSpecification.1.Tag.1.Key", "team")
.formParam("TagSpecification.1.Tag.1.Value", "workload")
.header("Authorization", WORKLOAD_AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("AllocateIpamPoolCidrResponse.ipamPoolAllocation.resourceOwner", equalTo("000000000002"))
.extract().path("AllocateIpamPoolCidrResponse.ipamPoolAllocation.ipamPoolAllocationId");
given()
.formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id")
.formParam("Filter.1.Value.1", allocationId)
.header("Authorization", WORKLOAD_AUTH_HEADER)
.when().post("/")
.then().statusCode(200)
.body("DescribeTagsResponse.tagSet.item.value", equalTo("workload"));
return allocationId;
}
private void assertNoTagsInEitherAccount(String resourceId) {
for (String auth : new String[] {AUTH_HEADER, WORKLOAD_AUTH_HEADER}) {
given()
.formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id")
.formParam("Filter.1.Value.1", resourceId)
.header("Authorization", auth)
.when().post("/")
.then().statusCode(200)
.body("DescribeTagsResponse.tagSet.item.size()", equalTo(0));
}
}
@Test
@Order(323)
void associateIpamByoasnSuccess() {
@@ -11,15 +11,19 @@ import io.floci.aws.services.ec2.model.IpamPool;
import io.floci.aws.services.ec2.model.IpamPoolAllocation;
import io.floci.aws.services.ec2.model.IpamPoolCidr;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.testing.Ec2ServiceFixtures;
import io.floci.aws.testing.InMemoryStorageFactory;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -37,14 +41,17 @@ class Ec2IpamServiceTest {
private static final String REGION = "us-east-1";
private Ec2Service ec2;
private Ec2IpamService service;
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
ec2 = Ec2ServiceFixtures.mockModeService();
service = new Ec2IpamService(config,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
ec2);
}
// --- organization admin delegation (the Organization-stage blocker, LZA
@@ -88,7 +95,7 @@ class Ec2IpamServiceTest {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("222222222222");
Ec2IpamService orgService = new Ec2IpamService(config, new InMemoryStorage<>(),
new InMemoryStorage<>(), settings, new InMemoryStorage<>(), contextInstance);
new InMemoryStorage<>(), settings, new InMemoryStorage<>(), mock(Ec2Service.class), contextInstance);
orgService.enableIpamOrganizationAdminAccount("333333333333");
@@ -120,7 +127,7 @@ class Ec2IpamServiceTest {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("222222222222");
Ec2IpamService orgService = new Ec2IpamService(config, new InMemoryStorage<>(),
new InMemoryStorage<>(), settings, new InMemoryStorage<>(), contextInstance);
new InMemoryStorage<>(), settings, new InMemoryStorage<>(), mock(Ec2Service.class), contextInstance);
orgService.enableIpamOrganizationAdminAccount("333333333333");
@@ -206,10 +213,10 @@ class Ec2IpamServiceTest {
when(config.defaultAccountId()).thenReturn("000000000000");
InMemoryStorage<String, AsnAssociation> backend = new InMemoryStorage<>();
Ec2IpamService firstService = new Ec2IpamService(config,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), backend);
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), backend, mock(Ec2Service.class));
firstService.associateIpamByoasn("us-west-2", "65001", "192.168.0.0/16");
Ec2IpamService secondService = new Ec2IpamService(config,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), backend);
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), backend, mock(Ec2Service.class));
assertTrue(secondService.hasAsnAssociation("us-west-2", "65001", "192.168.0.0/16"));
}
@@ -281,9 +288,7 @@ class Ec2IpamServiceTest {
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"));
REGION, null, "ipv4", null, null, null, List.of(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(),
@@ -294,10 +299,86 @@ class Ec2IpamServiceTest {
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());
// the filters read EC2's tag store, so a tag added later with CreateTags counts too
ec2.createTags(REGION, List.of(pool.getIpamPoolId()), List.of(new Tag("Team", "red")));
assertEquals(1, service.describeIpamPools(REGION, List.of(),
List.of(Map.entry("tag-key", List.of("Team")))).size());
}
@Test
void createIpamPoolTagsOnlyThePoolItCreates() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", null, null, "pool-token", List.of(new Tag("team", "red")));
assertEquals("red", ec2.resourceTags(REGION, pool.getIpamPoolId()).getFirst().getValue());
ec2.deleteTags(REGION, List.of(pool.getIpamPoolId()), List.of());
service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", null, null, "pool-token", List.of(new Tag("team", "red")));
assertTrue(ec2.resourceTags(REGION, pool.getIpamPoolId()).isEmpty(),
"a ClientToken replay returns the pool without tagging it again");
}
@Test
void allocationTagsLastUntilTheAllocationIsReleased() {
IpamPool pool = poolWith("10.0.0.0/16");
IpamPoolAllocation allocation = service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24,
null, null, null, List.of(new Tag("team", "red")));
assertEquals("red", ec2.resourceTags(REGION, allocation.getIpamPoolAllocationId()).getFirst().getValue());
service.releaseIpamPoolAllocation(REGION, pool.getIpamPoolId(), allocation.getIpamPoolAllocationId(), null);
assertTrue(ec2.resourceTags(REGION, allocation.getIpamPoolAllocationId()).isEmpty());
}
@Test
void deletingAPoolOrItsIpamDropsThePoolAndAllocationTags() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
List<String> tagged = new ArrayList<>();
for (int i = 0; i < 2; i++) {
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", null, null, null, List.of(new Tag("team", "red")));
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10." + i + ".0.0/16");
IpamPoolAllocation allocation = service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24,
null, null, null, List.of(new Tag("team", "red")));
tagged.add(pool.getIpamPoolId());
tagged.add(allocation.getIpamPoolAllocationId());
}
service.deleteIpamPool(REGION, tagged.getFirst());
assertTrue(ec2.resourceTags(REGION, tagged.get(0)).isEmpty());
assertTrue(ec2.resourceTags(REGION, tagged.get(1)).isEmpty());
assertEquals(1, ec2.resourceTags(REGION, tagged.get(2)).size());
service.deleteIpam(REGION, ipam.getIpamId());
assertTrue(ec2.resourceTags(REGION, tagged.get(2)).isEmpty());
assertTrue(ec2.resourceTags(REGION, tagged.get(3)).isEmpty());
}
@Test
void deletingAnIpamDropsTheTagsOfItsPoolsInOtherRegions() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION, "us-west-2"));
IpamPool pool = service.createIpamPool("us-west-2", ipam.getPrivateDefaultScopeId(),
"us-west-2", null, "ipv4", null, null, null, List.of(new Tag("team", "red")));
service.deleteIpam(REGION, ipam.getIpamId());
assertTrue(ec2.resourceTags("us-west-2", pool.getIpamPoolId()).isEmpty());
}
@Test
void allocationTagsAndTagFiltersUseThePoolsOwnRegion() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION, "us-west-2"));
IpamPool pool = service.createIpamPool("us-west-2", ipam.getPrivateDefaultScopeId(),
"us-west-2", null, "ipv4", null, null, null, List.of(new Tag("team", "red")));
String poolId = pool.getIpamPoolId();
service.provisionIpamPoolCidr("us-west-2", poolId, "10.0.0.0/16");
IpamPoolAllocation allocation = service.allocateIpamPoolCidr(REGION, poolId, 24,
null, null, null, List.of(new Tag("team", "red")));
String allocationId = allocation.getIpamPoolAllocationId();
assertEquals(1, ec2.resourceTags("us-west-2", allocationId).size());
service.releaseIpamPoolAllocation(REGION, poolId, allocationId, null);
assertTrue(ec2.resourceTags("us-west-2", allocationId).isEmpty());
assertEquals(1, service.describeIpamPools(REGION, List.of(poolId),
List.of(Map.entry("tag:team", List.of("red")))).size());
}
@Test
@@ -442,9 +523,9 @@ class Ec2IpamServiceTest {
void replayingAnAllocationClientTokenReturnsTheOriginalAllocation() {
IpamPool pool = poolWith("10.0.0.0/16");
IpamPoolAllocation first = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, "subnet-a", "alloc-token");
REGION, pool.getIpamPoolId(), 24, null, "subnet-a", "alloc-token", List.of());
IpamPoolAllocation replay = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, "subnet-a", "alloc-token");
REGION, pool.getIpamPoolId(), 24, null, "subnet-a", "alloc-token", List.of());
assertEquals(first.getIpamPoolAllocationId(), replay.getIpamPoolAllocationId());
assertEquals(first.getCidr(), replay.getCidr());
@@ -456,9 +537,9 @@ class Ec2IpamServiceTest {
void distinctAllocationClientTokensStillConsumeDistinctCidrs() {
IpamPool pool = poolWith("10.0.0.0/16");
IpamPoolAllocation first = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, null, "token-a");
REGION, pool.getIpamPoolId(), 24, null, null, "token-a", List.of());
IpamPoolAllocation second = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, null, "token-b");
REGION, pool.getIpamPoolId(), 24, null, null, "token-b", List.of());
assertEquals("10.0.0.0/24", first.getCidr());
assertEquals("10.0.1.0/24", second.getCidr());
}
@@ -479,9 +560,9 @@ class Ec2IpamServiceTest {
void replayingAPoolCreateClientTokenReturnsTheOriginalPool() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool first = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "first", "000000000000", "pool-token");
REGION, null, "ipv4", "first", "000000000000", "pool-token", List.of());
IpamPool replay = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "second", "000000000000", "pool-token");
REGION, null, "ipv4", "second", "000000000000", "pool-token", List.of());
assertEquals(first.getIpamPoolId(), replay.getIpamPoolId());
assertEquals(1, service.describeIpamPools(REGION, List.of(), List.of()).size());
@@ -511,7 +592,7 @@ class Ec2IpamServiceTest {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn(workloadAccount);
Ec2IpamService accountAwareService = new Ec2IpamService(
config, ipams, pools, new InMemoryStorage<>(), new InMemoryStorage<>(),
config, ipams, pools, new InMemoryStorage<>(), new InMemoryStorage<>(), mock(Ec2Service.class),
contextInstance);
Ipam ipam = accountAwareService.createIpam(REGION, null, List.of(REGION), ownerAccount);
@@ -539,7 +620,8 @@ class Ec2IpamServiceTest {
@SuppressWarnings("unchecked")
private record SharedPoolFixture(Ec2IpamService service, AccountAwareStorageBackend<IpamPool> pools,
AccountAwareStorageBackend<Ipam> ipams, AtomicReference<String> caller,
Ipam ipam, IpamPool pool) {}
Ipam ipam, IpamPool pool, Ec2Service ec2,
AccountAwareStorageBackend<List<Tag>> tags) {}
@SuppressWarnings("unchecked")
private SharedPoolFixture sharedPoolOwnedByAnotherAccount() {
@@ -555,11 +637,14 @@ class Ec2IpamServiceTest {
new InMemoryStorage<>(), contextInstance, "000000000000");
AccountAwareStorageBackend<IpamPool> pools = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
AccountAwareStorageBackend<List<Tag>> tags = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
Ec2Service ec2 = Ec2ServiceFixtures.mockModeService(
new InMemoryStorageFactory(Ec2ServiceFixtures.ACCOUNT).withStore("ec2-tags.json", tags));
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn(workloadAccount);
Ec2IpamService service = new Ec2IpamService(
config, ipams, pools, new InMemoryStorage<>(), new InMemoryStorage<>(),
contextInstance);
config, ipams, pools, new InMemoryStorage<>(), new InMemoryStorage<>(), ec2, contextInstance);
Ipam ipam = service.createIpam(REGION, null, List.of(REGION), ownerAccount);
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
@@ -567,7 +652,50 @@ class Ec2IpamServiceTest {
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10.0.0.0/16");
caller.set(workloadAccount);
return new SharedPoolFixture(service, pools, ipams, caller, ipam, pool);
return new SharedPoolFixture(service, pools, ipams, caller, ipam, pool, ec2, tags);
}
@Test
void anotherAccountsAllocationTagsLeaveNoEntryInEitherAccount() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
String poolId = fixture.pool().getIpamPoolId();
List<String> ids = new ArrayList<>(List.of(poolId));
for (int i = 0; i < 2; i++) {
IpamPoolAllocation allocation = fixture.service().allocateIpamPoolCidr(REGION, poolId, 24,
null, null, null, List.of(new Tag("team", "workload")));
assertEquals("222222222222", allocation.getResourceOwner());
ids.add(allocation.getIpamPoolAllocationId());
}
fixture.caller().set("111111111111");
fixture.ec2().createTags(REGION, ids, List.of(new Tag("team", "owner")));
Function<String, Integer> entries = id ->
fixture.tags().scanAllAccountEntries(key -> key.endsWith(id)).size();
assertEquals(2, entries.apply(ids.get(1)));
fixture.service().releaseIpamPoolAllocation(REGION, poolId, ids.get(1), null);
assertEquals(0, entries.apply(ids.get(1)));
assertEquals(2, entries.apply(ids.get(2)));
fixture.service().deleteIpamPool(REGION, poolId);
for (String id : ids) {
assertEquals(0, entries.apply(id), id);
}
}
@Test
void anAllocationStoredWithoutAResourceOwnerFallsBackToThePoolOwnersAccount() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
String poolId = fixture.pool().getIpamPoolId();
fixture.caller().set("111111111111");
String allocationId = fixture.service().allocateIpamPoolCidr(REGION, poolId, 24,
null, null, null, List.of(new Tag("team", "owner"))).getIpamPoolAllocationId();
fixture.pools().getForAccount("111111111111", REGION + "|" + poolId).orElseThrow()
.getAllocations().getFirst().setResourceOwner(null);
fixture.caller().set("222222222222");
fixture.service().releaseIpamPoolAllocation(REGION, poolId, allocationId, null);
assertTrue(fixture.tags().scanAllAccountEntries(key -> key.endsWith(allocationId)).isEmpty());
}
@Test
@@ -592,7 +720,7 @@ class Ec2IpamServiceTest {
when(config.defaultAccountId()).thenReturn("000000000000");
InMemoryStorage<String, Ipam> ipams = spy(new InMemoryStorage<>());
Ec2IpamService spied = new Ec2IpamService(config,
ipams, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
ipams, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), mock(Ec2Service.class));
Ipam ipam = spied.createIpam(REGION, null, List.of(REGION));
spied.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), REGION, null, "ipv4", "d");
clearInvocations(ipams);