mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): issue instance-profile role credentials through IMDS (#3742)
* fix(ec2): issue instance-profile role credentials through IMDS * test(ec2): cover null IMDS unregister and shutdown revocation
This commit is contained in:
1 parent
ef03c59864
commit
d4a96913df
13 files changed
+504
-74
No files matched your search
@@ -151,6 +151,7 @@ class EmulatorLifecycleTest {
|
||||
inOrder.verify(initLifecycleState).markBootCompleted();
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
inOrder.verify(iamService).sweepOrphanedLambdaExecutionRoleSessions();
|
||||
inOrder.verify(iamService).sweepOrphanedEc2InstanceSessions();
|
||||
inOrder.verify(rdsService).restorePersistedRuntime();
|
||||
}
|
||||
|
||||
|
||||
@@ -893,6 +893,16 @@ class Ec2ContainerManagerTest {
|
||||
assertTrue(command[2].contains("http://169.254.169.254/latest/meta-data/instance-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceProfileEnvironmentLetsTheSdkUseImds() {
|
||||
List<String> environment = Ec2ContainerManager.localAwsEnvironment(
|
||||
"us-west-2", "http://floci:4566", "http://floci:9169", true);
|
||||
assertTrue(environment.contains("AWS_EC2_METADATA_SERVICE_ENDPOINT=http://floci:9169"));
|
||||
assertTrue(environment.contains("AWS_ENDPOINT_URL=http://floci:4566"));
|
||||
assertFalse(environment.stream().anyMatch(value -> value.startsWith("AWS_ACCESS_KEY_ID=")
|
||||
|| value.startsWith("AWS_SECRET_ACCESS_KEY=") || value.startsWith("AWS_SESSION_TOKEN=")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void localAwsEnvironmentProvidesCliCredentialsAndFlociEndpoint() {
|
||||
assertEquals(
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@QuarkusTest
|
||||
class Ec2InstanceCredentialsIntegrationTest {
|
||||
@Inject
|
||||
IamService iam;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void imdsCredentialsResolveToTheAttachedRoleAndAreRevokedOnCleanup(boolean stopServer) throws Exception {
|
||||
String account = "246813579012";
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String role = "worker-" + suffix;
|
||||
String profile = "profile-" + suffix;
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=" + account
|
||||
+ "/20260916/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateRole").formParam("RoleName", role)
|
||||
.formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}")
|
||||
.post("/").then().statusCode(200);
|
||||
given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", profile)
|
||||
.post("/").then().statusCode(200);
|
||||
given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "AddRoleToInstanceProfile").formParam("InstanceProfileName", profile)
|
||||
.formParam("RoleName", role).post("/").then().statusCode(200);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
int port;
|
||||
try (ServerSocket socket = new ServerSocket(0)) {
|
||||
port = socket.getLocalPort();
|
||||
}
|
||||
when(config.services().ec2().imdsPort()).thenReturn(port);
|
||||
Vertx vertx = Vertx.vertx();
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(vertx, config, iam);
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-credentials");
|
||||
instance.setIamInstanceProfileArn("arn:aws:iam::" + account + ":instance-profile/" + profile);
|
||||
String endpoint = "http://127.0.0.1:" + port;
|
||||
try (HttpClient client = HttpClient.newHttpClient()) {
|
||||
server.start().get(10, TimeUnit.SECONDS);
|
||||
server.registerContainer("127.0.0.1", instance.getInstanceId(), instance);
|
||||
HttpResponse<String> token = client.send(HttpRequest.newBuilder(URI.create(endpoint + "/latest/api/token"))
|
||||
.timeout(Duration.ofSeconds(5)).header("X-aws-ec2-metadata-token-ttl-seconds", "60")
|
||||
.PUT(HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, token.statusCode());
|
||||
String path = "/latest/meta-data/iam/security-credentials/";
|
||||
assertEquals(role, get(client, endpoint + path, token.body()).body());
|
||||
assertEquals(404, get(client, endpoint + path + "wrong-role", token.body()).statusCode());
|
||||
HttpResponse<String> response = get(client, endpoint + path + role, token.body());
|
||||
assertEquals(200, response.statusCode());
|
||||
JsonObject credential = new JsonObject(response.body());
|
||||
assertEquals("Success", credential.getString("Code"));
|
||||
assertEquals("AWS-HMAC", credential.getString("Type"));
|
||||
assertTrue(Instant.parse(credential.getString("Expiration")).isAfter(Instant.now()));
|
||||
String key = credential.getString("AccessKeyId");
|
||||
String sessionToken = credential.getString("Token");
|
||||
assertEquals(credential.getString("SecretAccessKey"), iam.findSecretKey(key, sessionToken).orElseThrow());
|
||||
assertEquals(account, iam.resolveAccountId(key).orElseThrow());
|
||||
assertEquals("arn:aws:sts::" + account + ":assumed-role/" + role + "/i-credentials",
|
||||
iam.resolveCallerArn(key).orElseThrow());
|
||||
assertEquals(response.body(), get(client, endpoint + path + role, token.body()).body());
|
||||
if (stopServer) {
|
||||
server.stop();
|
||||
} else {
|
||||
server.unregisterInstance(instance);
|
||||
assertNotEquals(200, get(client, endpoint + path + role, token.body()).statusCode());
|
||||
}
|
||||
assertTrue(iam.findSecretKey(key, sessionToken).isEmpty());
|
||||
assertTrue(server.registeredContainer("127.0.0.1").isEmpty());
|
||||
} finally {
|
||||
server.stop();
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profile)
|
||||
.formParam("RoleName", role).post("/").then().statusCode(200);
|
||||
given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteInstanceProfile").formParam("InstanceProfileName", profile)
|
||||
.post("/").then().statusCode(200);
|
||||
given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteRole").formParam("RoleName", role)
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpResponse<String> get(HttpClient client, String url, String token) throws Exception {
|
||||
return client.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(5))
|
||||
.header("X-aws-ec2-metadata-token", token).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class Ec2InstanceCredentialsTest {
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String PROFILE = "arn:aws:iam::123456789012:instance-profile/path/profile";
|
||||
private static final Instant NOW = Instant.parse("2026-09-16T10:00:00Z");
|
||||
|
||||
@Test
|
||||
void credentialsAreRegisteredStableAndRotateWithOverlap() {
|
||||
Fixture fixture = fixture();
|
||||
SessionCredential first = fixture.get(NOW);
|
||||
assertTrue(first.getAccessKeyId().matches("ASIA[A-F0-9]{16}"));
|
||||
assertEquals(40, first.getSecretAccessKey().length());
|
||||
assertEquals(ACCOUNT, first.getOriginAccountId());
|
||||
assertEquals("i-first", first.getEc2InstanceId());
|
||||
assertEquals(NOW.plusSeconds(3600), first.getExpiration());
|
||||
verify(fixture.iam).registerEc2InstanceSession(first);
|
||||
assertSame(first, fixture.get(NOW.plusSeconds(3299)));
|
||||
SessionCredential second = fixture.get(NOW.plusSeconds(3300));
|
||||
assertNotEquals(first.getAccessKeyId(), second.getAccessKeyId());
|
||||
assertNotEquals(first.getSessionToken(), second.getSessionToken());
|
||||
verify(fixture.iam, never()).unregisterSession(ACCOUNT, first.getAccessKeyId());
|
||||
fixture.get(NOW.plusSeconds(3600));
|
||||
verify(fixture.iam).unregisterSession(ACCOUNT, first.getAccessKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unregisterRevokesEveryGenerationAndPreventsLateIssuance() {
|
||||
Fixture fixture = fixture();
|
||||
SessionCredential first = fixture.get(NOW);
|
||||
SessionCredential second = fixture.get(NOW.plusSeconds(3300));
|
||||
fixture.instance.setIamInstanceProfileArn(null);
|
||||
fixture.credentials.unregister(fixture.instance);
|
||||
verify(fixture.iam).unregisterSession(ACCOUNT, first.getAccessKeyId());
|
||||
verify(fixture.iam).unregisterSession(ACCOUNT, second.getAccessKeyId());
|
||||
fixture.instance.setIamInstanceProfileArn(PROFILE);
|
||||
assertTrue(fixture.credentials.get(fixture.instance, "worker", NOW).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleRemovalAndRecreationDoNotReuseOldCredentials() {
|
||||
Fixture fixture = fixture();
|
||||
SessionCredential first = fixture.get(NOW);
|
||||
fixture.role.setRoleId("AROA-recreated");
|
||||
SessionCredential second = fixture.get(NOW.plusSeconds(1));
|
||||
assertNotEquals(first.getAccessKeyId(), second.getAccessKeyId());
|
||||
verify(fixture.iam).unregisterSession(ACCOUNT, first.getAccessKeyId());
|
||||
when(fixture.iam.findInstanceProfile(ACCOUNT, "profile")).thenReturn(Optional.empty());
|
||||
assertTrue(fixture.credentials.get(fixture.instance, "worker", NOW.plusSeconds(2)).isEmpty());
|
||||
verify(fixture.iam).unregisterSession(ACCOUNT, second.getAccessKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongRoleMissingProfileAndMismatchedProfileArnDoNotIssueCredentials() {
|
||||
Fixture fixture = fixture();
|
||||
assertTrue(fixture.credentials.get(fixture.instance, "other", NOW).isEmpty());
|
||||
fixture.instance.setIamInstanceProfileArn(PROFILE.replace("path/", "other/"));
|
||||
assertTrue(fixture.credentials.get(fixture.instance, "worker", NOW).isEmpty());
|
||||
fixture.instance.setIamInstanceProfileArn(null);
|
||||
assertTrue(fixture.credentials.get(fixture.instance, "worker", NOW).isEmpty());
|
||||
verify(fixture.iam, never()).registerEc2InstanceSession(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentRequestsShareOneSessionAndInstancesRemainIndependent() throws Exception {
|
||||
Fixture fixture = fixture();
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(8)) {
|
||||
List<Callable<SessionCredential>> requests = IntStream.range(0, 32)
|
||||
.mapToObj(index -> (Callable<SessionCredential>) () -> fixture.get(NOW)).toList();
|
||||
List<Future<SessionCredential>> results = executor.invokeAll(requests);
|
||||
SessionCredential first = results.getFirst().get();
|
||||
for (Future<SessionCredential> result : results) {
|
||||
assertSame(first, result.get());
|
||||
}
|
||||
verify(fixture.iam, times(1)).registerEc2InstanceSession(any());
|
||||
Instance other = new Instance();
|
||||
other.setInstanceId("i-second");
|
||||
other.setIamInstanceProfileArn(PROFILE);
|
||||
fixture.credentials.register(other);
|
||||
SessionCredential second = fixture.credentials.get(other, "worker", NOW).orElseThrow();
|
||||
assertNotEquals(first.getAccessKeyId(), second.getAccessKeyId());
|
||||
fixture.credentials.unregister(fixture.instance);
|
||||
assertSame(second, fixture.credentials.get(other, "worker", NOW).orElseThrow());
|
||||
fixture.credentials.clear();
|
||||
verify(fixture.iam).unregisterSession(ACCOUNT, second.getAccessKeyId());
|
||||
}
|
||||
}
|
||||
|
||||
private static Fixture fixture() {
|
||||
IamService iam = mock(IamService.class);
|
||||
InstanceProfile profile = new InstanceProfile();
|
||||
profile.setArn(PROFILE);
|
||||
profile.setRoleNames(List.of("worker"));
|
||||
IamRole role = new IamRole("AROA-first", "worker", "/nodes/",
|
||||
"arn:aws:iam::123456789012:role/nodes/worker", "{}");
|
||||
when(iam.findInstanceProfile(ACCOUNT, "profile")).thenReturn(Optional.of(profile));
|
||||
when(iam.findRole(ACCOUNT, "worker")).thenReturn(Optional.of(role));
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-first");
|
||||
instance.setIamInstanceProfileArn(PROFILE);
|
||||
Ec2InstanceCredentials credentials = new Ec2InstanceCredentials(iam);
|
||||
credentials.register(instance);
|
||||
return new Fixture(iam, role, instance, credentials);
|
||||
}
|
||||
|
||||
private record Fixture(IamService iam, IamRole role, Instance instance, Ec2InstanceCredentials credentials) {
|
||||
SessionCredential get(Instant now) {
|
||||
return credentials.get(instance, "worker", now).orElseThrow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@ package io.github.hectorvent.floci.services.ec2;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Placement;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
@@ -12,8 +10,6 @@ import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class Ec2MetadataServerTest {
|
||||
|
||||
@@ -29,6 +25,8 @@ class Ec2MetadataServerTest {
|
||||
server.reconcileContainerAddresses(Set.of("192.0.2.4"), first);
|
||||
assertTrue(server.registeredContainer("192.0.2.1").isEmpty());
|
||||
assertEquals(second, server.registeredContainer("192.0.2.2").orElseThrow());
|
||||
server.unregisterInstance(null);
|
||||
assertEquals(first, server.registeredContainer("192.0.2.4").orElseThrow());
|
||||
server.unregisterInstance(first);
|
||||
assertTrue(server.registeredContainer("192.0.2.4").isEmpty());
|
||||
assertEquals(second, server.registeredContainer("192.0.2.3").orElseThrow());
|
||||
@@ -117,17 +115,4 @@ class Ec2MetadataServerTest {
|
||||
assertTrue(message.contains("SSM managed instance"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamCredentialRoleNameComesFromInstanceProfileRole() {
|
||||
IamService iamService = mock(IamService.class);
|
||||
InstanceProfile profile = new InstanceProfile();
|
||||
profile.setInstanceProfileName("sample-profile");
|
||||
profile.setRoleNames(List.of("sample-role"));
|
||||
when(iamService.getInstanceProfile("sample-profile")).thenReturn(profile);
|
||||
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(null, null, iamService);
|
||||
|
||||
assertEquals("sample-role", server.resolveRoleName(
|
||||
"arn:aws:iam::000000000000:instance-profile/sample-profile"));
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,49 @@ class IamServiceTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2SessionUsesInstanceIdentityTokenAndOwningAccount() {
|
||||
SessionCredential session = new SessionCredential("ASIAEC2SESSION", "secret", "token",
|
||||
"arn:aws:iam::123456789012:role/path/worker", Instant.now().plusSeconds(3600), null, "123456789012");
|
||||
session.setEc2InstanceId("i-worker");
|
||||
AccountAwareStorageBackend<SessionCredential> stored = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "000000000000");
|
||||
iamService = iamService(false, new InMemoryStorage<>(), stored);
|
||||
iamService.registerEc2InstanceSession(session);
|
||||
assertTrue(stored.getForAccount("000000000000", session.getAccessKeyId()).isEmpty());
|
||||
assertEquals("i-worker", stored.getForAccount("123456789012", session.getAccessKeyId())
|
||||
.orElseThrow().getEc2InstanceId());
|
||||
assertEquals("123456789012", iamService.resolveAccountId(session.getAccessKeyId()).orElseThrow());
|
||||
assertEquals("arn:aws:sts::123456789012:assumed-role/worker/i-worker",
|
||||
iamService.resolveCallerArn(session.getAccessKeyId()).orElseThrow());
|
||||
assertEquals("secret", iamService.findSecretKey(session.getAccessKeyId(), "token").orElseThrow());
|
||||
assertTrue(iamService.findSecretKey(session.getAccessKeyId(), "wrong-token").isEmpty());
|
||||
assertTrue(iamService.findSecretKey(session.getAccessKeyId(), null).isEmpty());
|
||||
iamService.registerSession("ASIAOTHER", "other-secret", "other-token", session.getRoleArn(),
|
||||
Instant.now().plusSeconds(3600), null);
|
||||
assertEquals(1, iamService.sweepOrphanedEc2InstanceSessions());
|
||||
assertTrue(iamService.findSecretKey(session.getAccessKeyId(), "token").isEmpty());
|
||||
assertTrue(iamService.findSecretKey("ASIAOTHER", "other-token").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2SessionMarkerSurvivesPersistenceAndExpiredCredentialsCannotAuthenticate() throws Exception {
|
||||
SessionCredential expired = new SessionCredential("ASIAEXPIREDEC2", "secret", "token",
|
||||
"arn:aws:iam::123456789012:role/worker", Instant.now().minusSeconds(1), null, "123456789012");
|
||||
expired.setEc2InstanceId("i-expired");
|
||||
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
|
||||
SessionCredential restored = mapper.readValue(mapper.writeValueAsBytes(expired), SessionCredential.class);
|
||||
assertEquals("i-expired", restored.getEc2InstanceId());
|
||||
AccountAwareStorageBackend<SessionCredential> stored = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "000000000000");
|
||||
IamService service = iamService(false, new InMemoryStorage<>(), stored);
|
||||
service.registerEc2InstanceSession(restored);
|
||||
assertTrue(service.findSecretKey(restored.getAccessKeyId(), "token").isEmpty());
|
||||
IamService restarted = iamService(false, new InMemoryStorage<>(), stored);
|
||||
assertEquals(1, restarted.sweepOrphanedEc2InstanceSessions());
|
||||
assertTrue(stored.getForAccount("123456789012", restored.getAccessKeyId()).isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Users
|
||||
// =========================================================================
|
||||
|
||||
Reference in new issue
Block a user