mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(ec2): store instance metadata options and add ModifyInstanceMetadataOptions (#3215)
RunInstances stores the MetadataOptions it is given, with AWS's launch defaults for anything left out, and DescribeInstances reads the stored values back instead of a hardcoded block. A launch template's metadata options seed the launch and explicit request fields override them. ModifyInstanceMetadataOptions changes only the fields it names and returns the instanceMetadataOptions shape. Values outside the AWS enumerations and a hop limit outside 1 to 64 are InvalidParameterValue. Ported from lex00/floci#116, whose SSM half is floci-io/floci#3173.
This commit is contained in:
1 parent
d99675a512
commit
5eacd01636
8 files changed
+443
-20
No files matched your search
@@ -169,6 +169,7 @@ Floci seeds the following resources on first use in each region so Terraform, th
|
||||
| DescribeInstanceStatus | Returns status records for stored instances. |
|
||||
| DescribeInstanceAttribute | Returns a supported attribute for an instance. |
|
||||
| ModifyInstanceAttribute | Updates supported mutable attributes for an instance. |
|
||||
| ModifyInstanceMetadataOptions | Updates an instance's IMDS options, changing only the fields the request names. |
|
||||
|
||||
### VPCs
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ public class Ec2QueryHandler {
|
||||
case "DescribeInstanceStatus" -> handleDescribeInstanceStatus(params, region);
|
||||
case "DescribeInstanceAttribute" -> handleDescribeInstanceAttribute(params, region);
|
||||
case "ModifyInstanceAttribute" -> handleModifyInstanceAttribute(params, region);
|
||||
case "ModifyInstanceMetadataOptions" -> handleModifyInstanceMetadataOptions(params, region);
|
||||
// EBS encryption defaults
|
||||
case "GetEbsEncryptionByDefault" -> handleGetEbsEncryptionByDefault(region);
|
||||
case "EnableEbsEncryptionByDefault" -> handleEnableEbsEncryptionByDefault(region);
|
||||
@@ -658,8 +659,15 @@ public class Ec2QueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Absent fields stay null so the launch default, or the launch template's value, applies.
|
||||
LaunchTemplateData.MetadataOptions metadataOptions = parseMetadataOptions(p, "MetadataOptions.");
|
||||
|
||||
LaunchTemplateData launchTemplateData = resolveRunInstancesLaunchTemplateData(p, region);
|
||||
if (launchTemplateData != null) {
|
||||
if (launchTemplateData.getMetadataOptions() != null) {
|
||||
metadataOptions = LaunchTemplateData.MetadataOptions.merge(
|
||||
launchTemplateData.getMetadataOptions(), metadataOptions);
|
||||
}
|
||||
imageId = firstNonBlank(imageId, launchTemplateData.getImageId());
|
||||
instanceType = firstNonBlank(instanceType, launchTemplateData.getInstanceType());
|
||||
keyName = firstNonBlank(keyName, launchTemplateData.getKeyName());
|
||||
@@ -679,7 +687,7 @@ public class Ec2QueryHandler {
|
||||
|
||||
Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount,
|
||||
keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
|
||||
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex);
|
||||
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions);
|
||||
|
||||
if (!networkInterfaceTags.isEmpty()) {
|
||||
List<String> eniIds = new ArrayList<>();
|
||||
@@ -1264,6 +1272,43 @@ public class Ec2QueryHandler {
|
||||
return booleanResponse("ModifyInstanceAttribute");
|
||||
}
|
||||
|
||||
private Response handleModifyInstanceMetadataOptions(MultivaluedMap<String, String> p, String region) {
|
||||
String instanceId = p.getFirst("InstanceId");
|
||||
if (instanceId == null || instanceId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter InstanceId", 400);
|
||||
}
|
||||
Instance inst = service.modifyInstanceMetadataOptions(region, instanceId, parseMetadataOptions(p, ""));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ModifyInstanceMetadataOptionsResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.elem("instanceId", instanceId);
|
||||
appendMetadataOptions(xml, "instanceMetadataOptions", inst.effectiveMetadataOptions());
|
||||
xml.end("ModifyInstanceMetadataOptionsResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
/** Reads the MetadataOptions fields under {@code prefix}, leaving unspecified ones null. */
|
||||
private LaunchTemplateData.MetadataOptions parseMetadataOptions(MultivaluedMap<String, String> p, String prefix) {
|
||||
LaunchTemplateData.MetadataOptions options = new LaunchTemplateData.MetadataOptions();
|
||||
options.setHttpTokens(p.getFirst(prefix + "HttpTokens"));
|
||||
options.setHttpPutResponseHopLimit(intParam(p, prefix + "HttpPutResponseHopLimit"));
|
||||
options.setHttpEndpoint(p.getFirst(prefix + "HttpEndpoint"));
|
||||
options.setHttpProtocolIpv6(p.getFirst(prefix + "HttpProtocolIpv6"));
|
||||
options.setInstanceMetadataTags(p.getFirst(prefix + "InstanceMetadataTags"));
|
||||
return options;
|
||||
}
|
||||
|
||||
private void appendMetadataOptions(XmlBuilder xml, String element, LaunchTemplateData.MetadataOptions options) {
|
||||
xml.start(element)
|
||||
.elem("state", options.getState() != null ? options.getState() : "applied")
|
||||
.elem("httpTokens", options.getHttpTokens())
|
||||
.elem("httpPutResponseHopLimit", str(options.getHttpPutResponseHopLimit()))
|
||||
.elem("httpEndpoint", options.getHttpEndpoint())
|
||||
.elem("httpProtocolIpv6", options.getHttpProtocolIpv6())
|
||||
.elem("instanceMetadataTags", options.getInstanceMetadataTags())
|
||||
.end(element);
|
||||
}
|
||||
|
||||
// ─── VPC handlers ─────────────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateVpc(MultivaluedMap<String, String> p, String region) {
|
||||
@@ -4133,16 +4178,9 @@ public class Ec2QueryHandler {
|
||||
xml.start("cpuOptions")
|
||||
.elem("coreCount", "1")
|
||||
.elem("threadsPerCore", "1")
|
||||
.end("cpuOptions")
|
||||
.start("metadataOptions")
|
||||
.elem("state", "applied")
|
||||
.elem("httpTokens", "optional")
|
||||
.elem("httpPutResponseHopLimit", "1")
|
||||
.elem("httpEndpoint", "enabled")
|
||||
.elem("httpProtocolIpv6", "disabled")
|
||||
.elem("instanceMetadataTags", "disabled")
|
||||
.end("metadataOptions")
|
||||
.start("maintenanceOptions")
|
||||
.end("cpuOptions");
|
||||
appendMetadataOptions(xml, "metadataOptions", inst.effectiveMetadataOptions());
|
||||
xml.start("maintenanceOptions")
|
||||
.elem("autoRecovery", "default")
|
||||
.end("maintenanceOptions")
|
||||
.start("enclaveOptions")
|
||||
@@ -4678,13 +4716,7 @@ public class Ec2QueryHandler {
|
||||
data.setTagSpecifications(parseLaunchTemplateTagSpecifications(p, prefix));
|
||||
|
||||
if (anyParamStartsWith(p, prefix + ".MetadataOptions.")) {
|
||||
LaunchTemplateData.MetadataOptions options = new LaunchTemplateData.MetadataOptions();
|
||||
options.setHttpTokens(p.getFirst(prefix + ".MetadataOptions.HttpTokens"));
|
||||
options.setHttpPutResponseHopLimit(intParam(p, prefix + ".MetadataOptions.HttpPutResponseHopLimit"));
|
||||
options.setHttpEndpoint(p.getFirst(prefix + ".MetadataOptions.HttpEndpoint"));
|
||||
options.setHttpProtocolIpv6(p.getFirst(prefix + ".MetadataOptions.HttpProtocolIpv6"));
|
||||
options.setInstanceMetadataTags(p.getFirst(prefix + ".MetadataOptions.InstanceMetadataTags"));
|
||||
data.setMetadataOptions(options);
|
||||
data.setMetadataOptions(parseMetadataOptions(p, prefix + ".MetadataOptions."));
|
||||
}
|
||||
|
||||
Boolean monitoringEnabled = boolParam(p, prefix + ".Monitoring.Enabled");
|
||||
|
||||
@@ -2268,9 +2268,31 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
String userData, String iamInstanceProfileArn,
|
||||
Boolean associatePublicIp, String networkInterfaceId,
|
||||
int networkInterfaceDeviceIndex, String availabilityZone) {
|
||||
return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,
|
||||
securityGroupIds, subnetId, clientToken, instanceTags, userData,
|
||||
iamInstanceProfileArn, associatePublicIp, networkInterfaceId,
|
||||
networkInterfaceDeviceIndex, availabilityZone, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param metadataOptions the launch's MetadataOptions, with null fields for whatever the
|
||||
* request left unspecified so AWS's launch default applies to them,
|
||||
* or null when the request set none
|
||||
*/
|
||||
public Reservation runInstances(String region, String imageId, String instanceType,
|
||||
int minCount, int maxCount, String keyName,
|
||||
List<String> securityGroupIds, String subnetId,
|
||||
String clientToken, List<Tag> instanceTags,
|
||||
String userData, String iamInstanceProfileArn,
|
||||
Boolean associatePublicIp, String networkInterfaceId,
|
||||
int networkInterfaceDeviceIndex, String availabilityZone,
|
||||
LaunchTemplateData.MetadataOptions metadataOptions) {
|
||||
if (imageId == null || imageId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);
|
||||
}
|
||||
validateMetadataOptions(metadataOptions);
|
||||
LaunchTemplateData.MetadataOptions launchMetadataOptions = LaunchTemplateData.MetadataOptions.merge(
|
||||
LaunchTemplateData.MetadataOptions.launchDefaults(), metadataOptions);
|
||||
ensureDefaultResources(region);
|
||||
|
||||
// floci-kt9: a caller-supplied primary ENI (override-default-eni) governs its own
|
||||
@@ -2376,6 +2398,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
inst.setRegion(region);
|
||||
inst.setUserData(userData);
|
||||
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
|
||||
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
|
||||
if (instanceTags != null && !instanceTags.isEmpty()) {
|
||||
inst.setTags(new ArrayList<>(instanceTags));
|
||||
tags.put(instanceId, new ArrayList<>(instanceTags));
|
||||
@@ -2870,6 +2893,45 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ModifyInstanceMetadataOptions changes only the fields the caller names, as on AWS, so a
|
||||
* call that sets HttpTokens alone leaves HttpEndpoint and the hop limit as they were.
|
||||
*/
|
||||
public Instance modifyInstanceMetadataOptions(String region, String instanceId,
|
||||
LaunchTemplateData.MetadataOptions request) {
|
||||
ensureDefaultResources(region);
|
||||
validateMetadataOptions(request);
|
||||
Instance inst = getRequiredInstance(region, instanceId);
|
||||
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(inst.effectiveMetadataOptions(), request));
|
||||
instances.put(key(region, instanceId), inst);
|
||||
return inst;
|
||||
}
|
||||
|
||||
private static void validateMetadataOptions(LaunchTemplateData.MetadataOptions options) {
|
||||
if (options == null) {
|
||||
return;
|
||||
}
|
||||
requireMetadataOptionValue("HttpTokens", options.getHttpTokens(), "optional", "required");
|
||||
requireMetadataOptionValue("HttpEndpoint", options.getHttpEndpoint(), "enabled", "disabled");
|
||||
requireMetadataOptionValue("HttpProtocolIpv6", options.getHttpProtocolIpv6(), "enabled", "disabled");
|
||||
requireMetadataOptionValue("InstanceMetadataTags", options.getInstanceMetadataTags(), "enabled", "disabled");
|
||||
Integer hopLimit = options.getHttpPutResponseHopLimit();
|
||||
if (hopLimit != null && (hopLimit < 1 || hopLimit > 64)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Value (" + hopLimit + ") for parameter HttpPutResponseHopLimit is invalid. "
|
||||
+ "Valid values are between 1 and 64.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireMetadataOptionValue(String parameter, String value, String... allowed) {
|
||||
if (value == null || List.of(allowed).contains(value)) {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Value (" + value + ") for parameter " + parameter + " is invalid. Valid values are: "
|
||||
+ String.join(", ", allowed) + ".", 400);
|
||||
}
|
||||
|
||||
private Instance getRequiredInstance(String region, String instanceId) {
|
||||
Instance inst = instances.get(key(region, instanceId)).orElse(null);
|
||||
if (inst == null)
|
||||
|
||||
@@ -57,6 +57,10 @@ public class Instance {
|
||||
private boolean disableApiStop = false;
|
||||
private boolean disableApiTermination = false;
|
||||
|
||||
// Null for an instance persisted before metadata options were stored; reads fall back to
|
||||
// AWS's launch defaults through effectiveMetadataOptions().
|
||||
private LaunchTemplateData.MetadataOptions metadataOptions;
|
||||
|
||||
// Docker backing fields (not serialised to AWS wire format)
|
||||
private String dockerContainerId;
|
||||
private String containerBridgeIp;
|
||||
@@ -199,4 +203,12 @@ public class Instance {
|
||||
|
||||
public boolean isDisableApiTermination() { return disableApiTermination; }
|
||||
public void setDisableApiTermination(boolean disableApiTermination) { this.disableApiTermination = disableApiTermination; }
|
||||
|
||||
public LaunchTemplateData.MetadataOptions getMetadataOptions() { return metadataOptions; }
|
||||
public void setMetadataOptions(LaunchTemplateData.MetadataOptions metadataOptions) { this.metadataOptions = metadataOptions; }
|
||||
|
||||
/** The stored metadata options, or AWS's launch defaults for a record that has none. */
|
||||
public LaunchTemplateData.MetadataOptions effectiveMetadataOptions() {
|
||||
return metadataOptions != null ? metadataOptions : LaunchTemplateData.MetadataOptions.launchDefaults();
|
||||
}
|
||||
}
|
||||
@@ -435,6 +435,51 @@ public class LaunchTemplateData {
|
||||
|
||||
public String getInstanceMetadataTags() { return instanceMetadataTags; }
|
||||
public void setInstanceMetadataTags(String instanceMetadataTags) { this.instanceMetadataTags = instanceMetadataTags; }
|
||||
|
||||
/** The options AWS applies to a launch that specifies none. */
|
||||
public static MetadataOptions launchDefaults() {
|
||||
MetadataOptions defaults = new MetadataOptions();
|
||||
defaults.state = "applied";
|
||||
defaults.httpTokens = "optional";
|
||||
defaults.httpPutResponseHopLimit = 1;
|
||||
defaults.httpEndpoint = "enabled";
|
||||
defaults.httpProtocolIpv6 = "disabled";
|
||||
defaults.instanceMetadataTags = "disabled";
|
||||
return defaults;
|
||||
}
|
||||
|
||||
/**
|
||||
* A copy of {@code base} with every field {@code override} sets replacing the base value.
|
||||
* A null override or a null field leaves the base value alone.
|
||||
*/
|
||||
public static MetadataOptions merge(MetadataOptions base, MetadataOptions override) {
|
||||
MetadataOptions merged = new MetadataOptions();
|
||||
merged.state = base.state;
|
||||
merged.httpTokens = base.httpTokens;
|
||||
merged.httpPutResponseHopLimit = base.httpPutResponseHopLimit;
|
||||
merged.httpEndpoint = base.httpEndpoint;
|
||||
merged.httpProtocolIpv6 = base.httpProtocolIpv6;
|
||||
merged.instanceMetadataTags = base.instanceMetadataTags;
|
||||
if (override == null) {
|
||||
return merged;
|
||||
}
|
||||
if (override.httpTokens != null) {
|
||||
merged.httpTokens = override.httpTokens;
|
||||
}
|
||||
if (override.httpPutResponseHopLimit != null) {
|
||||
merged.httpPutResponseHopLimit = override.httpPutResponseHopLimit;
|
||||
}
|
||||
if (override.httpEndpoint != null) {
|
||||
merged.httpEndpoint = override.httpEndpoint;
|
||||
}
|
||||
if (override.httpProtocolIpv6 != null) {
|
||||
merged.httpProtocolIpv6 = override.httpProtocolIpv6;
|
||||
}
|
||||
if (override.instanceMetadataTags != null) {
|
||||
merged.instanceMetadataTags = override.instanceMetadataTags;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Instance metadata options on the Query wire. A launch that names MetadataOptions.* is
|
||||
* honoured per instance, DescribeInstances reads the stored values back, and
|
||||
* ModifyInstanceMetadataOptions changes only what it names. terraform-aws-modules'
|
||||
* ec2-instance module defaults to http_tokens = required, so a hardcoded "optional" on read
|
||||
* produced a permanent second plan.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class Ec2InstanceMetadataOptionsIntegrationTest {
|
||||
|
||||
private static final String AUTH_HEADER =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
|
||||
private static final String INSTANCE = "RunInstancesResponse.instancesSet.item.";
|
||||
private static final String DESCRIBED =
|
||||
"DescribeInstancesResponse.reservationSet.item.instancesSet.item.metadataOptions.";
|
||||
|
||||
private static String instanceId;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void aLaunchWithNoMetadataOptionsGetsAwsDefaults() {
|
||||
instanceId = given()
|
||||
.formParam("Action", "RunInstances")
|
||||
.formParam("ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("InstanceType", "t3.micro")
|
||||
.formParam("MinCount", "1")
|
||||
.formParam("MaxCount", "1")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(INSTANCE + "metadataOptions.state", equalTo("applied"))
|
||||
.body(INSTANCE + "metadataOptions.httpTokens", equalTo("optional"))
|
||||
.body(INSTANCE + "metadataOptions.httpPutResponseHopLimit", equalTo("1"))
|
||||
.body(INSTANCE + "metadataOptions.httpEndpoint", equalTo("enabled"))
|
||||
.body(INSTANCE + "metadataOptions.httpProtocolIpv6", equalTo("disabled"))
|
||||
.body(INSTANCE + "metadataOptions.instanceMetadataTags", equalTo("disabled"))
|
||||
.extract().path(INSTANCE + "instanceId");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void anExplicitLaunchRequestIsHonouredAndReadBack() {
|
||||
String id = given()
|
||||
.formParam("Action", "RunInstances")
|
||||
.formParam("ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("InstanceType", "t3.micro")
|
||||
.formParam("MinCount", "1")
|
||||
.formParam("MaxCount", "1")
|
||||
.formParam("MetadataOptions.HttpTokens", "required")
|
||||
.formParam("MetadataOptions.HttpPutResponseHopLimit", "2")
|
||||
.formParam("MetadataOptions.InstanceMetadataTags", "enabled")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(INSTANCE + "metadataOptions.httpTokens", equalTo("required"))
|
||||
.body(INSTANCE + "metadataOptions.httpPutResponseHopLimit", equalTo("2"))
|
||||
.body(INSTANCE + "metadataOptions.instanceMetadataTags", equalTo("enabled"))
|
||||
// Fields the launch left out keep the AWS default.
|
||||
.body(INSTANCE + "metadataOptions.httpEndpoint", equalTo("enabled"))
|
||||
.extract().path(INSTANCE + "instanceId");
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("InstanceId.1", id)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(DESCRIBED + "httpTokens", equalTo("required"))
|
||||
.body(DESCRIBED + "httpPutResponseHopLimit", equalTo("2"))
|
||||
.body(DESCRIBED + "instanceMetadataTags", equalTo("enabled"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void modifyInstanceMetadataOptionsChangesOnlyWhatItNames() {
|
||||
String response = "ModifyInstanceMetadataOptionsResponse.";
|
||||
given()
|
||||
.formParam("Action", "ModifyInstanceMetadataOptions")
|
||||
.formParam("InstanceId", instanceId)
|
||||
.formParam("HttpTokens", "required")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(response + "instanceId", equalTo(instanceId))
|
||||
.body(response + "instanceMetadataOptions.state", equalTo("applied"))
|
||||
.body(response + "instanceMetadataOptions.httpTokens", equalTo("required"))
|
||||
// Not named in the call, so the launch values stay.
|
||||
.body(response + "instanceMetadataOptions.httpPutResponseHopLimit", equalTo("1"))
|
||||
.body(response + "instanceMetadataOptions.httpEndpoint", equalTo("enabled"));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("InstanceId.1", instanceId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(DESCRIBED + "httpTokens", equalTo("required"))
|
||||
.body(DESCRIBED + "httpPutResponseHopLimit", equalTo("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void modifyInstanceMetadataOptionsRejectsAValueOutsideTheEnumeration() {
|
||||
given()
|
||||
.formParam("Action", "ModifyInstanceMetadataOptions")
|
||||
.formParam("InstanceId", instanceId)
|
||||
.formParam("HttpEndpoint", "sometimes")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void aLaunchTemplateSuppliesTheOptionsAndTheLaunchOverridesThem() {
|
||||
String templateName = "imds-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", templateName)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
|
||||
.formParam("LaunchTemplateData.MetadataOptions.HttpTokens", "required")
|
||||
.formParam("LaunchTemplateData.MetadataOptions.HttpPutResponseHopLimit", "3")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.formParam("Action", "RunInstances")
|
||||
.formParam("LaunchTemplate.LaunchTemplateName", templateName)
|
||||
.formParam("MinCount", "1")
|
||||
.formParam("MaxCount", "1")
|
||||
.formParam("MetadataOptions.HttpPutResponseHopLimit", "5")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(INSTANCE + "metadataOptions.httpTokens", equalTo("required"))
|
||||
.body(INSTANCE + "metadataOptions.httpPutResponseHopLimit", equalTo("5"))
|
||||
.body(INSTANCE + "metadataOptions.httpEndpoint", equalTo("enabled"));
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -57,7 +58,8 @@ class Ec2RunInstancesPublicIpParamTest {
|
||||
when(service.runInstances(anyString(), nullable(String.class), nullable(String.class),
|
||||
anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),
|
||||
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
|
||||
nullable(Boolean.class), nullable(String.class), anyInt())).thenReturn(new Reservation());
|
||||
nullable(Boolean.class), nullable(String.class), anyInt(), nullable(String.class),
|
||||
nullable(LaunchTemplateData.MetadataOptions.class))).thenReturn(new Reservation());
|
||||
|
||||
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
|
||||
mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class),
|
||||
@@ -68,7 +70,8 @@ class Ec2RunInstancesPublicIpParamTest {
|
||||
verify(service).runInstances(anyString(), nullable(String.class), nullable(String.class),
|
||||
anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),
|
||||
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
|
||||
associatePublicIp.capture(), nullable(String.class), anyInt());
|
||||
associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class),
|
||||
nullable(LaunchTemplateData.MetadataOptions.class));
|
||||
if (expected == null) {
|
||||
assertNull(associatePublicIp.getValue(),
|
||||
"an absent override must stay null so the subnet default decides");
|
||||
|
||||
@@ -3140,6 +3140,102 @@ class Ec2ServiceTest {
|
||||
.getInstances().getFirst().getInstanceId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runInstancesStoresAwsMetadataOptionDefaultsWhenTheLaunchSetsNone() {
|
||||
Ec2Service service = mockModeService();
|
||||
Instance inst = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), null, null, List.of(), null, null)
|
||||
.getInstances().getFirst();
|
||||
|
||||
LaunchTemplateData.MetadataOptions options = inst.effectiveMetadataOptions();
|
||||
assertEquals("applied", options.getState());
|
||||
assertEquals("optional", options.getHttpTokens());
|
||||
assertEquals(1, options.getHttpPutResponseHopLimit());
|
||||
assertEquals("enabled", options.getHttpEndpoint());
|
||||
assertEquals("disabled", options.getHttpProtocolIpv6());
|
||||
assertEquals("disabled", options.getInstanceMetadataTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runInstancesHonoursExplicitMetadataOptionsAndDefaultsTheRest() {
|
||||
Ec2Service service = mockModeService();
|
||||
LaunchTemplateData.MetadataOptions request = new LaunchTemplateData.MetadataOptions();
|
||||
request.setHttpTokens("required");
|
||||
request.setHttpPutResponseHopLimit(2);
|
||||
|
||||
Instance inst = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), null, null, List.of(), null, null, null, null, 0, null, request)
|
||||
.getInstances().getFirst();
|
||||
|
||||
LaunchTemplateData.MetadataOptions options = inst.effectiveMetadataOptions();
|
||||
assertEquals("required", options.getHttpTokens());
|
||||
assertEquals(2, options.getHttpPutResponseHopLimit());
|
||||
assertEquals("enabled", options.getHttpEndpoint());
|
||||
assertEquals("disabled", options.getInstanceMetadataTags());
|
||||
// The stored instance reads back the same values.
|
||||
assertEquals("required", service.describeInstances("us-east-1", List.of(inst.getInstanceId()), Map.of())
|
||||
.getFirst().getInstances().getFirst().effectiveMetadataOptions().getHttpTokens());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyInstanceMetadataOptionsChangesOnlyTheFieldsItNames() {
|
||||
Ec2Service service = mockModeService();
|
||||
LaunchTemplateData.MetadataOptions launch = new LaunchTemplateData.MetadataOptions();
|
||||
launch.setHttpPutResponseHopLimit(3);
|
||||
String instanceId = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), null, null, List.of(), null, null, null, null, 0, null, launch)
|
||||
.getInstances().getFirst().getInstanceId();
|
||||
|
||||
LaunchTemplateData.MetadataOptions change = new LaunchTemplateData.MetadataOptions();
|
||||
change.setHttpTokens("required");
|
||||
Instance modified = service.modifyInstanceMetadataOptions("us-east-1", instanceId, change);
|
||||
|
||||
LaunchTemplateData.MetadataOptions options = modified.effectiveMetadataOptions();
|
||||
assertEquals("required", options.getHttpTokens());
|
||||
assertEquals(3, options.getHttpPutResponseHopLimit());
|
||||
assertEquals("enabled", options.getHttpEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataOptionsRejectValuesOutsideTheAwsEnumerations() {
|
||||
Ec2Service service = mockModeService();
|
||||
String instanceId = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), null, null, List.of(), null, null)
|
||||
.getInstances().getFirst().getInstanceId();
|
||||
|
||||
LaunchTemplateData.MetadataOptions badTokens = new LaunchTemplateData.MetadataOptions();
|
||||
badTokens.setHttpTokens("mandatory");
|
||||
AwsException tokensError = assertThrows(AwsException.class,
|
||||
() -> service.modifyInstanceMetadataOptions("us-east-1", instanceId, badTokens));
|
||||
assertEquals("InvalidParameterValue", tokensError.getErrorCode());
|
||||
|
||||
LaunchTemplateData.MetadataOptions badHopLimit = new LaunchTemplateData.MetadataOptions();
|
||||
badHopLimit.setHttpPutResponseHopLimit(65);
|
||||
AwsException hopError = assertThrows(AwsException.class, () -> service.runInstances(
|
||||
"us-east-1", "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), null, null, List.of(), null, null, null, null, 0, null, badHopLimit));
|
||||
assertEquals("InvalidParameterValue", hopError.getErrorCode());
|
||||
|
||||
// The failed modify left the stored options untouched.
|
||||
assertEquals("optional", service.describeInstances("us-east-1", List.of(instanceId), Map.of())
|
||||
.getFirst().getInstances().getFirst().effectiveMetadataOptions().getHttpTokens());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyInstanceMetadataOptionsRequiresAnExistingInstance() {
|
||||
Ec2Service service = mockModeService();
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.modifyInstanceMetadataOptions(
|
||||
"us-east-1", "i-0123456789abcdef0", new LaunchTemplateData.MetadataOptions()));
|
||||
assertEquals("InvalidInstanceID.NotFound", error.getErrorCode());
|
||||
}
|
||||
|
||||
private static Ec2Service mockModeService() {
|
||||
return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
}
|
||||
|
||||
private static EmulatorConfig mockConfig(boolean ec2Mock) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
|
||||
Reference in new issue
Block a user