feat(ec2): support DHCP options lifecycle (#6428)

* feat(ec2): support DHCP options lifecycle

* fix(ec2): validate DHCP options lifecycle edge cases

* fix(ec2): reuse region-aware private DNS domain for DHCP defaults

* fix(ec2): isolate DHCP options review regressions
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-24 15:39:22 -04:00
1 parent 781a68b6cb
commit 4a95c1bb95
8 files changed
+832 -4

No files matched your search

+4
View File
@@ -299,6 +299,10 @@ naming different VPCs find nothing.
| DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, an attached internet gateway or egress-only internet gateway, a transit gateway attachment, an Elastic Load Balancing v2 load balancer, or anything still holding a network interface in one of its subnets: an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone network interface, or an interface endpoint. |
| ModifyVpcAttribute | Updates supported VPC attributes. |
| DescribeVpcAttribute | Returns a supported VPC attribute. |
| CreateDhcpOptions | Creates a DHCP options set with the supplied configurations and optional tags. |
| DescribeDhcpOptions | Lists DHCP options sets by ID or filters, with paginated results. |
| AssociateDhcpOptions | Associates an options set with a VPC; `default` leaves the VPC with no DHCP options. |
| DeleteDhcpOptions | Deletes an unassociated DHCP options set. |
| DescribeVpcEndpointServices | Lists common AWS interface endpoint services and S3 (gateway and interface) in every availability zone, named per partition (see [Partitions](../configuration/partitions.md)). A `ServiceName` filter is echoed back as asked. |
| CreateVpcEndpoint | Creates a VPC endpoint record, including its `PolicyDocument` and the per-subnet IPv4 and IPv6 addresses named by `SubnetConfiguration.N`. `IpAddressType` defaults to `ipv4`. Interface and gateway address types are stored as metadata. Synthesized endpoint interfaces still carry IPv4 only; IPv6 networking is not emulated. An `Ipv4` value outside the named subnet's CIDR, or among the first four or the last address AWS reserves in it, is rejected with `InvalidParameterValue`. |
| DescribeVpcEndpoints | Lists or returns stored VPC endpoints, including their IP address type. |
+1 -1
View File
@@ -84,7 +84,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 |
| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 59 |
| [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 26 |
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 198 |
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 202 |
| [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions |
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 |
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 30 |
@@ -106,6 +106,10 @@ public class Ec2QueryHandler {
case "DeleteVpc" -> handleDeleteVpc(params, region);
case "ModifyVpcAttribute" -> handleModifyVpcAttribute(params, region);
case "DescribeVpcAttribute" -> handleDescribeVpcAttribute(params, region);
case "CreateDhcpOptions" -> handleCreateDhcpOptions(params, region);
case "DescribeDhcpOptions" -> handleDescribeDhcpOptions(params, region);
case "AssociateDhcpOptions" -> handleAssociateDhcpOptions(params, region);
case "DeleteDhcpOptions" -> handleDeleteDhcpOptions(params, region);
case "DescribeVpcEndpointServices" -> handleDescribeVpcEndpointServices(params, region);
case "CreateVpcEndpoint" -> handleCreateVpcEndpoint(params, region);
case "DescribeVpcEndpoints" -> handleDescribeVpcEndpoints(params, region);
@@ -1684,6 +1688,109 @@ public class Ec2QueryHandler {
return booleanResponse("DeleteVpc");
}
private Response handleCreateDhcpOptions(MultivaluedMap<String, String> p, String region) {
List<DhcpConfiguration> configurations = new ArrayList<>();
for (int i : numberedIndices(p, "DhcpConfiguration.")) {
String prefix = "DhcpConfiguration." + i;
String key = p.getFirst(prefix + ".Key");
if (key == null) {
throw new AwsException("MissingParameter", prefix + ".Key is required", 400);
}
List<String> values = numberedIndices(p, prefix + ".Value.").stream()
.map(index -> p.getFirst(prefix + ".Value." + index)).toList();
configurations.add(new DhcpConfiguration(key, values));
}
List<Tag> tags = parseTagsForResource(p, "dhcp-options");
DhcpOptions options = service.createDhcpOptions(region, configurations);
try {
applyResourceTags(tags, region, options.getDhcpOptionsId());
} catch (RuntimeException failure) {
try {
service.deleteDhcpOptions(region, options.getDhcpOptionsId());
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
throw failure;
}
return xmlResponse(new XmlBuilder()
.start("CreateDhcpOptionsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("dhcpOptions").raw(dhcpOptionsXml(region, options)).end("dhcpOptions")
.end("CreateDhcpOptionsResponse").build());
}
private SortedSet<Integer> numberedIndices(MultivaluedMap<String, String> params, String prefix) {
SortedSet<Integer> indices = new TreeSet<>();
for (String name : params.keySet()) {
if (!name.startsWith(prefix)) {
continue;
}
String suffix = name.substring(prefix.length());
int dot = suffix.indexOf('.');
String number = dot < 0 ? suffix : suffix.substring(0, dot);
try {
int index = Integer.parseInt(number);
if (index < 1) {
throw new NumberFormatException(number);
}
indices.add(index);
} catch (NumberFormatException invalid) {
throw new AwsException("InvalidParameterValue", "Invalid parameter index in " + name, 400);
}
}
return indices;
}
private Response handleDescribeDhcpOptions(MultivaluedMap<String, String> p, String region) {
int maxResults = parseIntParam(p, "MaxResults", 0);
if (p.containsKey("MaxResults") && maxResults == 0) {
throw new AwsException("InvalidMaxResults", "MaxResults must be between 5 and 1000", 400);
}
PaginatedResult<DhcpOptions> result = service.describeDhcpOptions(region, getList(p, "DhcpOptionsId"),
getFiltersList(p), maxResults, p.getFirst("NextToken"));
XmlBuilder xml = new XmlBuilder()
.start("DescribeDhcpOptionsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("dhcpOptionsSet");
for (DhcpOptions options : result.items()) {
xml.start("item").raw(dhcpOptionsXml(region, options)).end("item");
}
xml.end("dhcpOptionsSet");
if (result.nextToken() != null) {
xml.elem("nextToken", result.nextToken());
}
return xmlResponse(xml.end("DescribeDhcpOptionsResponse").build());
}
private Response handleAssociateDhcpOptions(MultivaluedMap<String, String> p, String region) {
service.associateDhcpOptions(region, p.getFirst("DhcpOptionsId"), p.getFirst("VpcId"));
return booleanResponse("AssociateDhcpOptions");
}
private Response handleDeleteDhcpOptions(MultivaluedMap<String, String> p, String region) {
service.deleteDhcpOptions(region, p.getFirst("DhcpOptionsId"));
return booleanResponse("DeleteDhcpOptions");
}
private String dhcpOptionsXml(String region, DhcpOptions options) {
XmlBuilder xml = new XmlBuilder()
.elem("dhcpOptionsId", options.getDhcpOptionsId())
.elem("ownerId", options.getOwnerId())
.start("dhcpConfigurationSet");
for (DhcpConfiguration configuration : options.getConfigurations()) {
xml.start("item").elem("key", configuration.getKey()).start("valueSet");
for (String value : configuration.getValues()) {
xml.start("item").elem("value", value).end("item");
}
xml.end("valueSet").end("item");
}
xml.end("dhcpConfigurationSet").start("tagSet");
for (Tag tag : service.resourceTags(region, options.getDhcpOptionsId())) {
xml.start("item").elem("key", tag.getKey()).elem("value", tag.getValue()).end("item");
}
return xml.end("tagSet").build();
}
private Response handleModifyVpcAttribute(MultivaluedMap<String, String> p, String region) {
String vpcId = p.getFirst("VpcId");
if (p.containsKey("EnableDnsSupport.Value")) {
@@ -27,6 +27,8 @@ import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogIns
import io.github.hectorvent.floci.services.ec2.model.Address;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
import io.github.hectorvent.floci.services.ec2.model.DhcpConfiguration;
import io.github.hectorvent.floci.services.ec2.model.DhcpOptions;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.EgressOnlyInternetGateway;
import io.github.hectorvent.floci.services.ec2.model.EgressOnlyInternetGatewayListResult;
@@ -111,6 +113,7 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -279,6 +282,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// persistent/hybrid/wal modes; see #1297 — CloudFormation persists stacks/exports that
// reference these EC2 ids, so the ids must survive too)
private final StorageBackend<String, Vpc> vpcs;
private final StorageBackend<String, DhcpOptions> dhcpOptions;
private final StorageBackend<String, Subnet> subnets;
private final StorageBackend<String, SecurityGroup> securityGroups;
private final StorageBackend<String, SecurityGroupRule> securityGroupRules;
@@ -562,7 +566,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
storageFactory.create("ec2", "ec2-transit-gateway-peering-attachments.json",
new TypeReference<Map<String, TransitGatewayPeeringAttachment>>() {}),
storageFactory.create("ec2", "ec2-egress-only-internet-gateways.json",
new TypeReference<Map<String, EgressOnlyInternetGateway>>() {}));
new TypeReference<Map<String, EgressOnlyInternetGateway>>() {}),
storageFactory.create("ec2", "ec2-dhcp-options.json",
new TypeReference<Map<String, DhcpOptions>>() {}));
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -589,13 +595,46 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags, new InMemoryStorage<>());
}
// Package-private for persistence tests that need the DHCP store to survive a service restart.
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog,
StorageBackend<String, Vpc> vpcs,
StorageBackend<String, Subnet> subnets,
StorageBackend<String, SecurityGroup> securityGroups,
StorageBackend<String, SecurityGroupRule> securityGroupRules,
StorageBackend<String, InternetGateway> internetGateways,
StorageBackend<String, RouteTable> routeTables,
StorageBackend<String, KeyPair> keyPairs,
StorageBackend<String, Address> addresses,
StorageBackend<String, Instance> instances,
StorageBackend<String, Volume> volumes,
StorageBackend<String, Image> registeredImages,
StorageBackend<String, Snapshot> snapshots,
StorageBackend<String, LaunchTemplate> launchTemplates,
StorageBackend<String, VpcEndpoint> vpcEndpoints,
StorageBackend<String, NatGateway> natGateways,
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags,
StorageBackend<String, DhcpOptions> dhcpOptions) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), null);
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), dhcpOptions);
}
// Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its
@@ -814,6 +853,56 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
StorageBackend<String, Host> hosts,
StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments,
StorageBackend<String, EgressOnlyInternetGateway> egressOnlyInternetGateways) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections,
networkInterfaces, capacityReservations, volumeModifications,
requestContextInstance, iamService, volumeBlockDeviceManager, hosts,
transitGatewayPeeringAttachments, egressOnlyInternetGateways, new InMemoryStorage<>());
}
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog,
StorageBackend<String, Vpc> vpcs,
StorageBackend<String, Subnet> subnets,
StorageBackend<String, SecurityGroup> securityGroups,
StorageBackend<String, SecurityGroupRule> securityGroupRules,
StorageBackend<String, InternetGateway> internetGateways,
StorageBackend<String, RouteTable> routeTables,
StorageBackend<String, KeyPair> keyPairs,
StorageBackend<String, Address> addresses,
StorageBackend<String, Instance> instances,
StorageBackend<String, Volume> volumes,
StorageBackend<String, Image> registeredImages,
StorageBackend<String, Snapshot> snapshots,
StorageBackend<String, LaunchTemplate> launchTemplates,
StorageBackend<String, VpcEndpoint> vpcEndpoints,
StorageBackend<String, NatGateway> natGateways,
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags,
StorageBackend<String, TransitGateway> transitGateways,
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,
StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments,
StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,
StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections,
StorageBackend<String, NetworkInterface> networkInterfaces,
StorageBackend<String, CapacityReservation> capacityReservations,
StorageBackend<String, VolumeModification> volumeModifications,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
IamService iamService,
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager,
StorageBackend<String, Host> hosts,
StorageBackend<String, TransitGatewayPeeringAttachment> transitGatewayPeeringAttachments,
StorageBackend<String, EgressOnlyInternetGateway> egressOnlyInternetGateways,
StorageBackend<String, DhcpOptions> dhcpOptions) {
this.hosts = hosts;
this.egressOnlyInternetGateways = egressOnlyInternetGateways;
this.transitGatewayPeeringAttachments = transitGatewayPeeringAttachments;
@@ -828,6 +917,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
this.imageCatalog = imageCatalog;
this.instanceTypeCatalog = instanceTypeCatalog;
this.vpcs = vpcs;
this.dhcpOptions = dhcpOptions;
this.subnets = subnets;
this.securityGroups = securityGroups;
this.securityGroupRules = securityGroupRules;
@@ -1307,6 +1397,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (!seededAccountRegions.add(seedScope)) {
return;
}
String defaultOptionsId = "dopt-default";
if (dhcpOptions.get(key(region, defaultOptionsId)).isEmpty()) {
DhcpOptions defaultOptions = new DhcpOptions();
defaultOptions.setDhcpOptionsId(defaultOptionsId);
defaultOptions.setRegion(region);
defaultOptions.setOwnerId(ownerAccountId);
defaultOptions.setConfigurations(List.of(
new DhcpConfiguration("domain-name", List.of(AwsRegions.ec2PrivateDnsDomain(region))),
new DhcpConfiguration("domain-name-servers", List.of("AmazonProvidedDNS")),
new DhcpConfiguration("ipv6-address-preferred-lease-time", List.of("140"))));
dhcpOptions.put(key(region, defaultOptionsId), defaultOptions);
}
// Already provisioned in a previous run and reloaded from persistent storage: the default
// VPC (and everything else) is present, so don't re-seed and create duplicates (#1297).
if (!vpcs.scan(k -> k.startsWith(region + "::")).isEmpty()) {
@@ -5754,6 +5856,185 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// ─── VPCs ──────────────────────────────────────────────────────────────────
public DhcpOptions createDhcpOptions(String region, List<DhcpConfiguration> configurations) {
if (configurations == null || configurations.isEmpty()) {
throw new AwsException("MissingParameter", "DhcpConfiguration is required", 400);
}
Set<String> keys = Set.of("domain-name", "domain-name-servers", "ntp-servers",
"netbios-name-servers", "netbios-node-type", "ipv6-address-preferred-lease-time");
Set<String> seen = new HashSet<>();
List<DhcpConfiguration> validated = new ArrayList<>();
for (DhcpConfiguration configuration : configurations) {
if (configuration.getKey() == null || !keys.contains(configuration.getKey())
|| !seen.add(configuration.getKey()) || configuration.getValues() == null
|| configuration.getValues().isEmpty()
|| configuration.getValues().stream().anyMatch(value -> value == null || value.isBlank())) {
throw new AwsException("InvalidParameterValue", "Invalid DHCP configuration", 400);
}
String optionKey = configuration.getKey();
List<String> values = configuration.getValues();
if (Set.of("domain-name-servers", "ntp-servers", "netbios-name-servers").contains(optionKey)) {
values = values.stream().flatMap(value -> Arrays.stream(value.split(",", -1)))
.map(String::trim).toList();
}
if (!validDhcpValues(optionKey, values)) {
throw new AwsException("InvalidParameterValue", "Invalid value for DHCP option " + optionKey, 400);
}
validated.add(new DhcpConfiguration(optionKey, List.copyOf(values)));
}
DhcpOptions options = new DhcpOptions();
options.setDhcpOptionsId("dopt-" + randomHex(17));
options.setRegion(region);
options.setOwnerId(callerAccountId());
options.setConfigurations(validated);
dhcpOptions.put(key(region, options.getDhcpOptionsId()), options);
return options;
}
private boolean validDhcpValues(String optionKey, List<String> values) {
if (values.isEmpty() || values.stream().anyMatch(String::isBlank)) {
return false;
}
return switch (optionKey) {
case "domain-name-servers" -> values.size() <= 4 &&
(values.equals(List.of("AmazonProvidedDNS")) || values.stream().allMatch(this::isLiteralIp));
case "ntp-servers" -> values.size() <= 8 && values.stream().allMatch(this::isLiteralIp)
&& values.stream().filter(value -> !value.contains(":")).count() <= 4
&& values.stream().filter(value -> value.contains(":")).count() <= 4;
case "netbios-name-servers" -> values.size() <= 4 && values.stream().allMatch(this::isLiteralIp);
case "netbios-node-type" -> values.size() == 1 && Set.of("1", "2", "4", "8").contains(values.getFirst());
case "ipv6-address-preferred-lease-time" -> values.size() == 1 && validIpv6LeaseTime(values.getFirst());
default -> true;
};
}
private boolean isLiteralIp(String value) {
try {
InetAddress.ofLiteral(value);
return true;
} catch (IllegalArgumentException invalid) {
return false;
}
}
private boolean validIpv6LeaseTime(String value) {
try {
long seconds = Long.parseLong(value);
return seconds >= 140 && seconds <= Integer.MAX_VALUE;
} catch (NumberFormatException invalid) {
return false;
}
}
public PaginatedResult<DhcpOptions> describeDhcpOptions(String region, List<String> ids,
List<Map.Entry<String, List<String>>> filters, int maxResults, String nextToken) {
ensureDefaultResources(region);
requireSupportedFilters(filterNames(filters), Set.of("dhcp-options-id", "owner-id", "key", "value",
"tag-key", "tag-value"));
if (maxResults != 0 && (maxResults < 5 || maxResults > 1000)) {
throw new AwsException("InvalidMaxResults", "MaxResults must be between 5 and 1000", 400);
}
if (maxResults != 0 && !ids.isEmpty()) {
throw new AwsException("InvalidParameterCombination",
"DhcpOptionsId cannot be used with MaxResults", 400);
}
String afterId = decodeDhcpOptionsToken(nextToken);
List<DhcpOptions> all = new ArrayList<>(dhcpOptions.scan(k -> k.startsWith(region + "::")));
all.sort(Comparator.comparing(DhcpOptions::getDhcpOptionsId));
for (String id : ids) {
getRequiredDhcpOptions(region, id);
}
List<DhcpOptions> matching = all.stream()
.filter(options -> ids.isEmpty() || ids.contains(options.getDhcpOptionsId()))
.filter(options -> filters.stream().allMatch(filter -> matchesDhcpOptionsFilter(region, options, filter)))
.filter(options -> afterId == null || options.getDhcpOptionsId().compareTo(afterId) > 0)
.toList();
int end = maxResults == 0 ? matching.size() : Math.min(matching.size(), maxResults);
return new PaginatedResult<>(matching.subList(0, end),
end < matching.size() ? encodeDhcpOptionsToken(matching.get(end - 1).getDhcpOptionsId()) : null);
}
private String encodeDhcpOptionsToken(String lastId) {
return Base64.getEncoder().encodeToString(lastId.getBytes(StandardCharsets.UTF_8));
}
private String decodeDhcpOptionsToken(String token) {
if (token == null || token.isEmpty()) {
return null;
}
try {
String id = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
if (!id.matches("dopt-(default|[0-9a-f]{17})")) {
throw new IllegalArgumentException("Invalid DHCP options cursor");
}
return id;
} catch (IllegalArgumentException invalid) {
throw new AwsException("InvalidParameterValue", "Invalid NextToken", 400);
}
}
private boolean matchesDhcpOptionsFilter(String region, DhcpOptions options,
Map.Entry<String, List<String>> filter) {
List<String> values = filter.getValue();
String name = filter.getKey();
List<Tag> resourceTags = resourceTags(region, options.getDhcpOptionsId());
if (name.startsWith("tag:")) {
return resourceTags.stream().anyMatch(tag -> name.substring(4).equals(tag.getKey())
&& matchesFilterValue(values, tag.getValue()));
}
return switch (name) {
case "dhcp-options-id" -> matchesFilterValue(values, options.getDhcpOptionsId());
case "owner-id" -> matchesFilterValue(values, options.getOwnerId());
case "key" -> options.getConfigurations().stream()
.anyMatch(configuration -> matchesFilterValue(values, configuration.getKey()));
case "value" -> options.getConfigurations().stream()
.flatMap(configuration -> configuration.getValues().stream())
.anyMatch(value -> matchesFilterValue(values, value));
case "tag-key" -> resourceTags.stream().anyMatch(tag -> matchesFilterValue(values, tag.getKey()));
case "tag-value" -> resourceTags.stream().anyMatch(tag -> matchesFilterValue(values, tag.getValue()));
default -> false;
};
}
public void associateDhcpOptions(String region, String dhcpOptionsId, String vpcId) {
if (dhcpOptionsId == null || dhcpOptionsId.isBlank()) {
throw new AwsException("MissingParameter", "DhcpOptionsId is required", 400);
}
if (vpcId == null || vpcId.isBlank()) {
throw new AwsException("MissingParameter", "VpcId is required", 400);
}
synchronized (attachmentTopologyLock(region)) {
Vpc vpc = getRequiredVpc(region, vpcId);
if (!"default".equals(dhcpOptionsId)) {
getRequiredDhcpOptions(region, dhcpOptionsId);
}
vpc.setDhcpOptionsId(dhcpOptionsId);
vpcs.put(key(region, vpcId), vpc);
}
}
public void deleteDhcpOptions(String region, String dhcpOptionsId) {
if (dhcpOptionsId == null || dhcpOptionsId.isBlank()) {
throw new AwsException("MissingParameter", "DhcpOptionsId is required", 400);
}
synchronized (attachmentTopologyLock(region)) {
getRequiredDhcpOptions(region, dhcpOptionsId);
if (vpcs.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(vpc -> dhcpOptionsId.equals(vpc.getDhcpOptionsId()))) {
throw new AwsException("DependencyViolation",
"The DHCP options set is associated with a VPC", 400);
}
dhcpOptions.delete(key(region, dhcpOptionsId));
removeTags(region, dhcpOptionsId);
}
}
private DhcpOptions getRequiredDhcpOptions(String region, String dhcpOptionsId) {
return dhcpOptions.get(key(region, dhcpOptionsId))
.orElseThrow(() -> new AwsException("InvalidDhcpOptionsID.NotFound",
"The DHCP options ID '" + dhcpOptionsId + "' does not exist", 400));
}
public Vpc createVpc(String region, String cidrBlock, boolean isDefault) {
return createVpc(region, cidrBlock, isDefault, false);
}
@@ -9556,6 +9837,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
switch (prefix.group(1)) {
case "i" -> getRequiredInstance(region, resourceId);
case "vpc" -> getRequiredVpc(region, resourceId);
case "dopt" -> getRequiredDhcpOptions(region, resourceId);
case "subnet" -> requireSubnet(region, resourceId);
case "sg" -> getRequiredSecurityGroup(region, resourceId);
case "sgr" -> requireFound(!describeSecurityGroupRules(region, List.of(), List.of(resourceId)).isEmpty(),
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class DhcpConfiguration {
private String key;
private List<String> values = new ArrayList<>();
public DhcpConfiguration() {}
public DhcpConfiguration(String key, List<String> values) {
this.key = key;
this.values = new ArrayList<>(values);
}
public String getKey() { return key; }
public void setKey(String key) { this.key = key; }
public List<String> getValues() { return values; }
public void setValues(List<String> values) { this.values = values; }
}
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class DhcpOptions {
private String dhcpOptionsId;
private String ownerId;
private String region;
private List<DhcpConfiguration> configurations = new ArrayList<>();
public DhcpOptions() {}
public String getDhcpOptionsId() { return dhcpOptionsId; }
public void setDhcpOptionsId(String dhcpOptionsId) { this.dhcpOptionsId = dhcpOptionsId; }
public String getOwnerId() { return ownerId; }
public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public List<DhcpConfiguration> getConfigurations() { return configurations; }
public void setConfigurations(List<DhcpConfiguration> configurations) { this.configurations = configurations; }
}
@@ -0,0 +1,367 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DhcpOptions;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class Ec2DhcpOptionsIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/ec2/aws4_request";
@Test
void createDhcpOptionsReturnsAwsQueryResource() {
String id = given()
.formParam("Action", "CreateDhcpOptions")
.formParam("DhcpConfiguration.1.Key", "domain-name")
.formParam("DhcpConfiguration.1.Value.1", "example.com")
.formParam("DhcpConfiguration.2.Key", "domain-name-servers")
.formParam("DhcpConfiguration.2.Value.1", "10.2.5.1")
.formParam("DhcpConfiguration.2.Value.2", "10.2.5.2")
.header("Authorization", AUTH_HEADER)
.when().post("/").then()
.statusCode(200)
.body("CreateDhcpOptionsResponse.dhcpOptions.dhcpOptionsId", startsWith("dopt-"))
.body(containsString("<key>domain-name</key>"))
.body(containsString("<value>example.com</value>"))
.body(containsString("<key>domain-name-servers</key>"))
.extract().xmlPath().getString("CreateDhcpOptionsResponse.dhcpOptions.dhcpOptionsId");
deleteOptions(id);
}
@Test
void describeFiltersCreatedOptionsAndDeleteRemovesThem() {
String id = createOptions("describe.example");
given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("Filter.1.Name", "value")
.formParam("Filter.1.Value.1", "describe.example")
.header("Authorization", AUTH_HEADER)
.when().post("/").then()
.statusCode(200)
.body("DescribeDhcpOptionsResponse.dhcpOptionsSet.item.dhcpOptionsId", equalTo(id));
deleteOptions(id);
given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("DhcpOptionsId.1", id)
.header("Authorization", AUTH_HEADER)
.when().post("/").then()
.statusCode(400)
.body(containsString("InvalidDhcpOptionsID.NotFound"));
}
@Test
void associatedOptionsCannotBeDeletedUntilVpcUsesDefault() {
String id = createOptions("association.example");
String vpcId = given()
.formParam("Action", "DescribeVpcs")
.formParam("Filter.1.Name", "is-default")
.formParam("Filter.1.Value.1", "true")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract()
.xmlPath().getString("DescribeVpcsResponse.vpcSet.item.vpcId");
String originalOptionsId = given()
.formParam("Action", "DescribeVpcs")
.formParam("VpcId.1", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract()
.xmlPath().getString("DescribeVpcsResponse.vpcSet.item.dhcpOptionsId");
try {
given()
.formParam("Action", "AssociateDhcpOptions")
.formParam("DhcpOptionsId", id)
.formParam("VpcId", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then()
.statusCode(200)
.body("AssociateDhcpOptionsResponse.return", equalTo("true"));
given()
.formParam("Action", "DescribeVpcs")
.formParam("VpcId.1", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then()
.statusCode(200)
.body("DescribeVpcsResponse.vpcSet.item.dhcpOptionsId", equalTo(id));
given()
.formParam("Action", "DeleteDhcpOptions")
.formParam("DhcpOptionsId", id)
.header("Authorization", AUTH_HEADER)
.when().post("/").then()
.statusCode(400)
.body(containsString("DependencyViolation"));
} finally {
given()
.formParam("Action", "AssociateDhcpOptions")
.formParam("DhcpOptionsId", originalOptionsId)
.formParam("VpcId", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
deleteOptions(id);
}
given()
.formParam("Action", "DescribeVpcs")
.formParam("VpcId.1", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeVpcsResponse.vpcSet.item.dhcpOptionsId", equalTo(originalOptionsId));
}
@Test
void describePagesFiveOptionsUsingNextToken() {
List<String> ids = new ArrayList<>();
try {
for (int i = 0; i < 6; i++) {
ids.add(createOptions("pagination.example"));
}
Response first = given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("Filter.1.Name", "value")
.formParam("Filter.1.Value.1", "pagination.example")
.formParam("MaxResults", "5")
.header("Authorization", AUTH_HEADER)
.when().post("/");
first.then().statusCode(200);
String token = first.xmlPath().getString("DescribeDhcpOptionsResponse.nextToken");
given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("Filter.1.Name", "value")
.formParam("Filter.1.Value.1", "pagination.example")
.formParam("MaxResults", "5")
.formParam("NextToken", token)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeDhcpOptionsResponse.dhcpOptionsSet.item.size()", equalTo(1));
} finally {
ids.forEach(this::deleteOptions);
}
}
@Test
void rejectedTagsDoNotLeaveAnOptionsSet() {
given()
.formParam("Action", "CreateDhcpOptions")
.formParam("DhcpConfiguration.1.Key", "domain-name")
.formParam("DhcpConfiguration.1.Value.1", "tag-rollback.example")
.formParam("TagSpecification.1.ResourceType", "dhcp-options")
.formParam("TagSpecification.1.Tag.1.Key", "oversized")
.formParam("TagSpecification.1.Tag.1.Value", "x".repeat(257))
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(400);
given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("Filter.1.Name", "value")
.formParam("Filter.1.Value.1", "tag-rollback.example")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeDhcpOptionsResponse.dhcpOptionsSet.item.size()", equalTo(0));
}
@Test
void missingRequiredIdsReturnMissingParameter() {
for (String action : List.of("AssociateDhcpOptions", "DeleteDhcpOptions")) {
given().formParam("Action", action).header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(400).body(containsString("MissingParameter"));
}
}
@Test
void defaultVpcOptionsCanBeDescribed() {
String defaultId = given()
.formParam("Action", "DescribeVpcs")
.formParam("Filter.1.Name", "is-default")
.formParam("Filter.1.Value.1", "true")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract()
.xmlPath().getString("DescribeVpcsResponse.vpcSet.item.dhcpOptionsId");
given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("DhcpOptionsId.1", defaultId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeDhcpOptionsResponse.dhcpOptionsSet.item.dhcpOptionsId", equalTo(defaultId))
.body(containsString("AmazonProvidedDNS"));
}
@Test
void associatingDefaultMeansNoOptionsInsteadOfTheRegionalDefaultSet() {
String vpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.253.0.0/16")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract()
.xmlPath().getString("CreateVpcResponse.vpc.vpcId");
try {
given()
.formParam("Action", "AssociateDhcpOptions")
.formParam("DhcpOptionsId", "default")
.formParam("VpcId", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
given()
.formParam("Action", "DescribeVpcs")
.formParam("VpcId.1", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeVpcsResponse.vpcSet.item.dhcpOptionsId", equalTo("default"));
} finally {
given()
.formParam("Action", "DeleteVpc")
.formParam("VpcId", vpcId)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
}
}
@Test
void numberedConfigurationsDoNotSilentlyDiscardLaterEntries() {
String id = given()
.formParam("Action", "CreateDhcpOptions")
.formParam("DhcpConfiguration.1.Key", "domain-name")
.formParam("DhcpConfiguration.1.Value.1", "numbered.example")
.formParam("DhcpConfiguration.3.Key", "netbios-node-type")
.formParam("DhcpConfiguration.3.Value.1", "2")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body(containsString("<key>netbios-node-type</key>"))
.extract().xmlPath().getString("CreateDhcpOptionsResponse.dhcpOptions.dhcpOptionsId");
deleteOptions(id);
}
@Test
void invalidNetbiosNodeTypeIsRejected() {
given()
.formParam("Action", "CreateDhcpOptions")
.formParam("DhcpConfiguration.1.Key", "netbios-node-type")
.formParam("DhcpConfiguration.1.Value.1", "3")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(400).body(containsString("InvalidParameterValue"));
}
@Test
void invalidDnsAddressAndLeaseTimeAreRejected() {
for (String[] configuration : List.of(
new String[] {"domain-name-servers", "not-an-ip"},
new String[] {"ipv6-address-preferred-lease-time", "139"})) {
given()
.formParam("Action", "CreateDhcpOptions")
.formParam("DhcpConfiguration.1.Key", configuration[0])
.formParam("DhcpConfiguration.1.Value.1", configuration[1])
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(400).body(containsString("InvalidParameterValue"));
}
}
@Test
void commaSeparatedDnsAddressesAreReturnedAsSeparateValues() {
String id = given()
.formParam("Action", "CreateDhcpOptions")
.formParam("DhcpConfiguration.1.Key", "domain-name-servers")
.formParam("DhcpConfiguration.1.Value.1", "10.2.5.1,10.2.5.2")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body(containsString("<value>10.2.5.1</value>"))
.body(containsString("<value>10.2.5.2</value>"))
.extract().xmlPath().getString("CreateDhcpOptionsResponse.dhcpOptions.dhcpOptionsId");
deleteOptions(id);
}
@Test
void deletingAnEarlierPageItemDoesNotSkipTheNextPage() {
List<String> ids = new ArrayList<>();
try {
for (int i = 0; i < 6; i++) {
ids.add(createOptions("deletion-page.example"));
}
Response first = given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("Filter.1.Name", "value")
.formParam("Filter.1.Value.1", "deletion-page.example")
.formParam("MaxResults", "5")
.header("Authorization", AUTH_HEADER)
.when().post("/");
first.then().statusCode(200);
List<String> firstIds = first.xmlPath().getList(
"DescribeDhcpOptionsResponse.dhcpOptionsSet.item.dhcpOptionsId");
String unseenId = ids.stream().filter(id -> !firstIds.contains(id)).findFirst().orElseThrow();
String token = first.xmlPath().getString("DescribeDhcpOptionsResponse.nextToken");
deleteOptions(firstIds.getFirst());
ids.remove(firstIds.getFirst());
given()
.formParam("Action", "DescribeDhcpOptions")
.formParam("Filter.1.Name", "value")
.formParam("Filter.1.Value.1", "deletion-page.example")
.formParam("MaxResults", "5")
.formParam("NextToken", token)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeDhcpOptionsResponse.dhcpOptionsSet.item.dhcpOptionsId", equalTo(unseenId));
} finally {
ids.forEach(this::deleteOptions);
}
}
@Test
void awsSdkParsesCreatedAndDescribedOptions() {
try (Ec2Client client = Ec2Client.builder()
.endpointOverride(URI.create("http://localhost:" + RestAssured.port))
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.httpClientBuilder(UrlConnectionHttpClient.builder()).build()) {
DhcpOptions created = client.createDhcpOptions(request -> request
.dhcpConfigurations(configuration -> configuration.key("domain-name")
.values("sdk.example"))).dhcpOptions();
String id = created.dhcpOptionsId();
assertTrue(id.startsWith("dopt-"));
assertEquals("sdk.example", created.dhcpConfigurations().getFirst().values().getFirst().value());
try {
DhcpOptions described = client.describeDhcpOptions(request -> request.dhcpOptionsIds(id))
.dhcpOptions().getFirst();
assertEquals(id, described.dhcpOptionsId());
assertEquals("sdk.example", described.dhcpConfigurations().getFirst().values().getFirst().value());
} finally {
client.deleteDhcpOptions(request -> request.dhcpOptionsId(id));
}
}
}
private String createOptions(String domain) {
return given()
.formParam("Action", "CreateDhcpOptions")
.formParam("DhcpConfiguration.1.Key", "domain-name")
.formParam("DhcpConfiguration.1.Value.1", domain)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200).extract()
.xmlPath().getString("CreateDhcpOptionsResponse.dhcpOptions.dhcpOptionsId");
}
private void deleteOptions(String id) {
given()
.formParam("Action", "DeleteDhcpOptions")
.formParam("DhcpOptionsId", id)
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
}
}
@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.ec2.model.Address;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.DhcpConfiguration;
import io.github.hectorvent.floci.services.ec2.model.DhcpOptions;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.Instance;
@@ -68,6 +70,18 @@ class Ec2ServicePersistenceTest {
private static final String REGION = "us-east-1";
@Test
void dhcpOptionsSurviveRestart(@TempDir Path dir) {
Ec2Service original = newService(dir);
String id = original.createDhcpOptions(REGION,
List.of(new DhcpConfiguration("domain-name", List.of("persistent.example")))).getDhcpOptionsId();
DhcpOptions restored = newService(dir).describeDhcpOptions(REGION, List.of(id), List.of(), 0, null)
.items().getFirst();
assertEquals(id, restored.getDhcpOptionsId());
assertEquals("persistent.example", restored.getConfigurations().getFirst().getValues().getFirst());
}
@Test
void elasticIpMetadataSurvivesRestart(@TempDir Path dir) {
String region = "us-west-2";
@@ -685,7 +699,8 @@ class Ec2ServicePersistenceTest {
load(dir, "ec2-spot-instance-requests.json", new TypeReference<Map<String, SpotInstanceRequest>>() {}),
load(dir, "ec2-network-acls.json", new TypeReference<Map<String, NetworkAcl>>() {}),
load(dir, "ec2-managed-prefix-lists.json", new TypeReference<Map<String, ManagedPrefixList>>() {}),
load(dir, "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}));
load(dir, "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}),
load(dir, "ec2-dhcp-options.json", new TypeReference<Map<String, DhcpOptions>>() {}));
}
private <V> StorageBackend<String, V> load(Path dir, String file, TypeReference<Map<String, V>> type) {