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:
lex00 authored and GitHub committed 2026-09-07 21:50:06 -05:00
1 parent d99675a512
commit 5eacd01636
8 files changed
+443 -20

No files matched your search

@@ -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"));
}
}
@@ -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);