Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ec2): issue instance-profile role credentials through IMDS (#3742)
luisetercd4a96913df27
diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 13bdedca92..f0448e1ce3 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -140,7 +140,11 @@ curl -s -H "x-aws-ec2-metadata-token: $TOKEN" \| `GET /latest/user-data` | UserData script || `GET /latest/dynamic/instance-identity/document` | Identity document JSON |-IAM credentials are served when the instance has an `IamInstanceProfile.Arn` set at launch. The container can then call other Floci services with full SigV4 validation using the standard AWS SDK credential chain.+IAM credentials are served when the instance has an `IamInstanceProfile.Arn` that resolves to an existing instance profile with one role in the profile's account. The role list uses the role name, which can differ from the profile name. Missing profiles, missing roles, and requests for another role return `404`.++Each registered instance receives its own temporary IAM session. Credentials last one hour and refresh on retrieval during the final five minutes; the previous generation remains valid until expiration. Floci revokes tracked sessions when the instance is unregistered or IMDS shuts down, and discards persisted EC2 sessions when Floci restarts. Restored guests obtain fresh credentials after metadata registration is rebuilt.++Guests with an instance profile receive endpoint and region settings without Floci's static `test` credentials, allowing the standard SDK credential chain to reach IMDS. Guests without an instance profile retain the existing local `test` credential environment. Custom images can still override the SDK chain with their own credentials. This does not add EKS access-entry authorization or change Floci's global IAM enforcement configuration.### IMDS and SSM managed instancesdiff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.javaindex 95d0b2db9c..b658c07e20 100644--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java@@ -193,6 +193,10 @@ public class EmulatorLifecycle {if (sweptSessions > 0) {LOG.infov("Removed {0} orphaned Lambda execution-role session(s)", sweptSessions);}+ int sweptEc2Sessions = iamService.sweepOrphanedEc2InstanceSessions();+ if (sweptEc2Sessions > 0) {+ LOG.infov("Removed {0} orphaned EC2 instance session(s)", sweptEc2Sessions);+ }schemaCreationWorker.recoverOrphans();schemaCreationWorker.rehydrateSchemas();stepFunctionsService.abortAbandonedExecutions();diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.javaindex 6b33720db1..4cbc3f6083 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java@@ -582,7 +582,7 @@ public class Ec2ContainerManager {namespace.helperId(), prefixLists);}ContainerSpec spec = buildContainerSpec(containerName, image, region, serviceEndpoint, imdsEndpoint,- instanceId, sshHostPort, namespace);+ instanceId, sshHostPort, namespace, instance.getIamInstanceProfileArn() != null);containerId = image.dockerPlatform() == null? lifecycleManager.create(spec): lifecycleManager.create(spec, image.dockerPlatform());@@ -636,13 +636,15 @@ public class Ec2ContainerManager {private ContainerSpec buildContainerSpec(String containerName, ResolvedAmiImage image, String region,String serviceEndpoint, String imdsEndpoint, String instanceId,- int sshHostPort, SecurityGroupFirewallManager.Namespace namespace) {+ int sshHostPort, SecurityGroupFirewallManager.Namespace namespace,+ boolean hasInstanceProfile) {// Minimal images keep the historic tail command, while cloud-image AMI guests can boot their init.ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image.dockerImage()).withName(containerName).withEmbeddedDns().withDockerNetwork(Optional.empty())- .withEnv(localAwsEnvironment(region, serviceEndpoint, imdsEndpoint))+ .withEnv(localAwsEnvironment(region, serviceEndpoint, imdsEndpoint,+ hasInstanceProfile)).withEnv("AWS_EC2_INSTANCE_ID", instanceId).withHostDockerInternalOnLinux().withLogRotation()@@ -1797,14 +1799,21 @@ public class Ec2ContainerManager {static List<String> localAwsEnvironment(String region, String serviceEndpoint, String imdsEndpoint) {- return List.of(+ return localAwsEnvironment(region, serviceEndpoint, imdsEndpoint, false);+ }++ static List<String> localAwsEnvironment(String region, String serviceEndpoint, String imdsEndpoint,+ boolean hasInstanceProfile) {+ List<String> environment = new ArrayList<>(List.of("AWS_EC2_METADATA_SERVICE_ENDPOINT=" + imdsEndpoint,"AWS_ENDPOINT_URL=" + serviceEndpoint,"AWS_DEFAULT_REGION=" + region,- "AWS_REGION=" + region,- "AWS_ACCESS_KEY_ID=test",- "AWS_SECRET_ACCESS_KEY=test",- "AWS_SESSION_TOKEN=test-session-token");+ "AWS_REGION=" + region));+ if (!hasInstanceProfile) {+ environment.addAll(List.of("AWS_ACCESS_KEY_ID=test", "AWS_SECRET_ACCESS_KEY=test",+ "AWS_SESSION_TOKEN=test-session-token"));+ }+ return environment;}static String summarizeUserDataOutput(BoundedOutput output) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.javanew file mode 100644index 0000000000..18fa63993a--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java@@ -0,0 +1,114 @@+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.SessionCredential;++import java.security.SecureRandom;+import java.time.Instant;+import java.util.ArrayList;+import java.util.Base64;+import java.util.HexFormat;+import java.util.IdentityHashMap;+import java.util.List;+import java.util.Map;+import java.util.Objects;+import java.util.Optional;++/** Owns credentials for the lifetime of each registered EC2 guest. */+final class Ec2InstanceCredentials {+ private final IamService iam;+ private final SecureRandom random = new SecureRandom();+ private final Map<Instance, List<Issued>> sessions = new IdentityHashMap<>();++ Ec2InstanceCredentials(IamService iam) {+ this.iam = iam;+ }++ synchronized void register(Instance instance) {+ sessions.computeIfAbsent(instance, ignored -> new ArrayList<>());+ }++ synchronized void unregister(Instance instance) {+ List<Issued> issued = sessions.remove(instance);+ if (issued != null) {+ issued.forEach(this::revoke);+ }+ }++ synchronized void clear() {+ sessions.values().forEach(issued -> issued.forEach(this::revoke));+ sessions.clear();+ }++ synchronized Optional<IamRole> role(Instance instance) {+ String arn = instance.getIamInstanceProfileArn();+ if (!sessions.containsKey(instance) || arn == null) {+ return Optional.empty();+ }+ String[] parts = arn.split(":", 6);+ if (parts.length != 6 || !"arn".equals(parts[0]) || !"iam".equals(parts[2])+ || !parts[3].isEmpty() || !parts[4].matches("[0-9]{12}")+ || !parts[5].startsWith("instance-profile/")) {+ return Optional.empty();+ }+ String name = arn.substring(arn.lastIndexOf('/') + 1);+ return iam.findInstanceProfile(parts[4], name)+ .filter(profile -> arn.equals(profile.getArn()))+ .filter(profile -> profile.getRoleNames() != null && profile.getRoleNames().size() == 1)+ .flatMap(profile -> iam.findRole(parts[4], profile.getRoleNames().getFirst()))+ .filter(role -> role.getArn() != null && role.getArn().startsWith(+ "arn:" + parts[1] + ":iam::" + parts[4] + ":role/"));+ }++ synchronized Optional<SessionCredential> get(Instance instance, String roleName, Instant now) {+ List<Issued> history = sessions.get(instance);+ if (history == null) {+ return Optional.empty();+ }+ Optional<IamRole> resolved = role(instance);+ history.removeIf(issued -> {+ boolean obsolete = !issued.session().getExpiration().isAfter(now) || resolved.isEmpty()+ || !Objects.equals(issued.roleId(), resolved.get().getRoleId())+ || !Objects.equals(issued.session().getRoleArn(), resolved.get().getArn())+ || !Objects.equals(issued.profileArn(), instance.getIamInstanceProfileArn());+ if (obsolete) {+ revoke(issued);+ }+ return obsolete;+ });+ if (resolved.isEmpty() || !resolved.get().getRoleName().equals(roleName)) {+ return Optional.empty();+ }+ if (!history.isEmpty()) {+ SessionCredential current = history.getLast().session();+ if (current.getExpiration().isAfter(now.plusSeconds(300))) {+ return Optional.of(current);+ }+ }+ IamRole role = resolved.get();+ String account = role.getArn().split(":", 6)[4];+ byte[] key = new byte[10];+ random.nextBytes(key);+ String accessKey = "ASIA" + HexFormat.of().withUpperCase().formatHex(key).substring(0, 16);+ SessionCredential session = new SessionCredential(accessKey, randomString(30), randomString(48),+ role.getArn(), now.plusSeconds(3600), null, account);+ session.setEc2InstanceId(instance.getInstanceId());+ iam.registerEc2InstanceSession(session);+ history.add(new Issued(session, role.getRoleId(), instance.getIamInstanceProfileArn()));+ return Optional.of(session);+ }++ private String randomString(int size) {+ byte[] bytes = new byte[size];+ random.nextBytes(bytes);+ return Base64.getEncoder().encodeToString(bytes);+ }++ private void revoke(Issued issued) {+ iam.unregisterSession(issued.session().getOriginAccountId(), issued.session().getAccessKeyId());+ }++ private record Issued(SessionCredential session, String roleId, String profileArn) {}+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.javaindex cd3c9ebd57..d7b63cf787 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java@@ -1,11 +1,13 @@package io.github.hectorvent.floci.services.ec2;import io.github.hectorvent.floci.config.EmulatorConfig;-import io.github.hectorvent.floci.core.common.AwsException;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.SessionCredential;import io.vertx.core.Vertx;import io.vertx.core.http.HttpServer;+import io.vertx.core.json.JsonObject;import io.vertx.ext.web.Router;import io.vertx.ext.web.RoutingContext;import io.vertx.ext.web.handler.BodyHandler;@@ -43,7 +45,7 @@ public class Ec2MetadataServer {private final Vertx vertx;private final EmulatorConfig config;- private final IamService iamService;+ private final Ec2InstanceCredentials credentials;/** IMDSv2: token value → Instance */private final Map<String, Instance> tokenToInstance = new ConcurrentHashMap<>();@@ -56,12 +58,13 @@ public class Ec2MetadataServer {public Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService) {this.vertx = vertx;this.config = config;- this.iamService = iamService;+ this.credentials = new Ec2InstanceCredentials(iamService);}/** Called by Ec2ContainerManager after a container starts to register its IP. */public void registerContainer(String containerIp, String instanceId, Instance instance) {if (containerIp != null && !containerIp.isBlank()) {+ credentials.register(instance);containerIpToInstance.put(containerIp, instance);LOG.debugv("IMDS: registered container {0} → instance {1}", containerIp, instanceId);}@@ -85,6 +88,8 @@ public class Ec2MetadataServer {public void unregisterInstance(Instance instance) {if (instance != null) {+ credentials.unregister(instance);+ tokenToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);}}@@ -143,6 +148,9 @@ public class Ec2MetadataServer {}public synchronized void stop() {+ credentials.clear();+ tokenToInstance.clear();+ containerIpToInstance.clear();if (httpServer != null) {httpServer.close();httpServer = null;@@ -250,15 +258,12 @@ public class Ec2MetadataServer {if (inst == null) {return;}- String profileArn = inst.getIamInstanceProfileArn();- if (profileArn == null) {+ Optional<IamRole> role = credentials.role(inst);+ if (role.isEmpty()) {ctx.response().setStatusCode(404).end();return;}- String roleName = resolveRoleName(profileArn);- ctx.response().setStatusCode(200)- .putHeader("content-type", "text/plain")- .end(roleName);+ ctx.response().putHeader("content-type", "text/plain").end(role.get().getRoleName());}private void handleCredentials(RoutingContext ctx) {@@ -266,22 +271,20 @@ public class Ec2MetadataServer {if (inst == null) {return;}- if (inst.getIamInstanceProfileArn() == null) {+ Optional<SessionCredential> result = credentials.get(inst, ctx.pathParam("role"), Instant.now());+ if (result.isEmpty()) {ctx.response().setStatusCode(404).end();return;}-- String expiration = ISO.format(Instant.now().plusSeconds(3600));- String body = "{\"Code\":\"Success\","- + "\"LastUpdated\":\"" + now() + "\","- + "\"Type\":\"AWS-HMAC\","- + "\"AccessKeyId\":\"test\","- + "\"SecretAccessKey\":\"test\","- + "\"Token\":\"test-session-token\","- + "\"Expiration\":\"" + expiration + "\"}";- ctx.response().setStatusCode(200)- .putHeader("content-type", "application/json")- .end(body);+ SessionCredential session = result.get();+ ctx.response().putHeader("content-type", "application/json").end(new JsonObject()+ .put("Code", "Success")+ .put("LastUpdated", ISO.format(session.getExpiration().minusSeconds(3600)))+ .put("Type", "AWS-HMAC")+ .put("AccessKeyId", session.getAccessKeyId())+ .put("SecretAccessKey", session.getSecretAccessKey())+ .put("Token", session.getSessionToken())+ .put("Expiration", ISO.format(session.getExpiration())).encode());}private void handleInstanceTagKeys(RoutingContext ctx) {@@ -404,31 +407,6 @@ public class Ec2MetadataServer {// ── Utilities ─────────────────────────────────────────────────────────────- String resolveRoleName(String profileArn) {- if (iamService != null) {- String profileName = extractProfileName(profileArn);- try {- var profile = iamService.getInstanceProfile(profileName);- if (profile.getRoleNames() != null && !profile.getRoleNames().isEmpty()) {- return profile.getRoleNames().getFirst();- }- } catch (AwsException e) {- LOG.debugf(e, "IMDS: instance profile %s unavailable; falling back to profile name", profileName);- // Fall back to the profile name when only the EC2 profile ARN was modeled.- }- }- return extractProfileName(profileArn);- }-- private static String extractProfileName(String profileArn) {- // arn:aws:iam::000000000000:instance-profile/my-role- int lastSlash = profileArn.lastIndexOf('/');- if (lastSlash >= 0 && lastSlash < profileArn.length() - 1) {- return profileArn.substring(lastSlash + 1);- }- return "instance-role";- }-private static String now() {return ISO.format(Instant.now());}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex f3d6331d35..b3ee30084d 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -1424,6 +1424,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {return profile;}+ public Optional<InstanceProfile> findInstanceProfile(String accountId, String profileName) {+ if (instanceProfiles instanceof AccountAwareStorageBackend<InstanceProfile> aware) {+ return aware.getForAccount(accountId, profileName);+ }+ return instanceProfiles.get(profileName);+ }+public InstanceProfile getInstanceProfile(String instanceProfileName) {return instanceProfiles.get(instanceProfileName).orElseThrow(() -> new AwsException("NoSuchEntity",@@ -2020,6 +2027,33 @@ public class IamService implements SessionAccountLookup, ResourceProvider {sessionAccessKeyId, accountId, roleArn);}+ /** Registers an IMDS session in the profile's account, outside request scope. */+ public void registerEc2InstanceSession(SessionCredential session) {+ if (session.getOriginAccountId() == null || session.getOriginAccountId().isBlank()+ || session.getEc2InstanceId() == null || session.getEc2InstanceId().isBlank()) {+ throw new IllegalArgumentException("EC2 session account and instance ID must not be blank");+ }+ if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {+ aware.putForAccount(session.getOriginAccountId(), session.getAccessKeyId(), session);+ } else {+ sessions.put(session.getAccessKeyId(), session);+ }+ }++ /** IMDS registrations are rebuilt on startup; discard credentials from the previous server. */+ public int sweepOrphanedEc2InstanceSessions() {+ List<SessionCredential> stored = sessions instanceof AccountAwareStorageBackend<SessionCredential> aware+ ? aware.scanAllAccounts() : sessions.scan(key -> true);+ int removed = 0;+ for (SessionCredential session : stored) {+ if (session.getEc2InstanceId() != null) {+ deleteSession(session.getAccessKeyId(), session);+ removed++;+ }+ }+ return removed;+ }+/** Removes a session from an explicit account namespace. */public void unregisterSession(String accountId, String sessionAccessKeyId) {if (sessionAccessKeyId == null || sessionAccessKeyId.isBlank()) {@@ -2190,7 +2224,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());- return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/floci-session").toString());+ return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/"+ + (session.getEc2InstanceId() != null ? session.getEc2InstanceId() : "floci-session")).toString());}return Optional.empty();diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.javaindex e1f92a748a..9b33b4563c 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java@@ -23,6 +23,7 @@ public class SessionCredential {private String originAccountId;/** True when this session belongs to a Floci-launched Lambda container. */private boolean lambdaExecutionRole;+ private String ec2InstanceId;public SessionCredential() {}@@ -91,6 +92,9 @@ public class SessionCredential {public String getOriginAccountId() { return originAccountId; }public void setOriginAccountId(String originAccountId) { this.originAccountId = originAccountId; }+ public String getEc2InstanceId() { return ec2InstanceId; }+ public void setEc2InstanceId(String ec2InstanceId) { this.ec2InstanceId = ec2InstanceId; }+public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }public void setLambdaExecutionRole(boolean lambdaExecutionRole) { this.lambdaExecutionRole = lambdaExecutionRole; }}diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.javaindex ffe0b40c4e..75a1b5874b 100644--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java@@ -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();}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.javaindex 83b0e83cca..3ec52e905f 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java@@ -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=")));+ }+@Testvoid localAwsEnvironmentProvidesCliCredentialsAndFlociEndpoint() {assertEquals(diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsIntegrationTest.javanew file mode 100644index 0000000000..3e943dd83a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsIntegrationTest.java@@ -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());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsTest.javanew file mode 100644index 0000000000..4b79863785--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentialsTest.java@@ -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();+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.javaindex f61f3abe99..344964fac6 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.java@@ -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"));- }}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.javaindex 2007654e67..cf4396abb9 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java@@ -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// =========================================================================