feat(ecs): issue task-role credentials and serve them over the AWS wire contract (#4160)

Adds EcsTaskRoleCredentials, which mints, rotates, and revokes an ECS task's
role session, and EcsTaskRoleCredentialsServer, a small Vert.x server that
serves it at GET /v2/credentials/<uuid> in the shape AWS_CONTAINER_CREDENTIALS_
RELATIVE_URI expects (RoleArn/AccessKeyId/SecretAccessKey/Token/Expiration).
The default 6-hour TTL and response shape are verified against
docs.aws.amazon.com and botocore's ContainerMetadataFetcher.

Builds on the session plumbing from #4143. The server binds a normal Floci
port, not 169.254.170.2: that address is hardcoded in every AWS SDK (unlike
EC2's configurable AWS_EC2_METADATA_SERVICE_ENDPOINT), and nothing in Floci's
own process can bind it without also owning it on a task's Docker network.
A follow-up piece adds the small proxy container that holds that address and
forwards here, and another wires this into EcsContainerManager so a task
actually gets one. Both are still off (feature flag defaults to false) since
neither exists yet.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-23 18:10:50 -05:00
1 parent acafe73a2c
commit 3f5741a965
6 files changed
+531

No files matched your search

@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.services.ecs.container;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.api.Test;
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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Exercises the real wire contract end to end: a role minted through the running app's IAM API,
* a real Vert.x server bound to a free port, and a plain {@link HttpClient} reading the response
* the way an AWS SDK's {@code ContainerMetadataFetcher} does. Modeled on
* {@code Ec2InstanceCredentialsIntegrationTest}.
*/
@QuarkusTest
class EcsTaskRoleCredentialsServerIntegrationTest {
@Inject
IamService iam;
@Test
void credentialsEndpointServesAnIssuedSessionAndStopsAfterRevoke() throws Exception {
String account = "356813579012";
String suffix = UUID.randomUUID().toString().substring(0, 8);
String role = "ecs-task-role-" + suffix;
String taskArn = "arn:aws:ecs:us-east-1:" + account + ":task/cluster/" + 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\":\"ecs-tasks.amazonaws.com\"},"
+ "\"Action\":\"sts:AssumeRole\"}]}")
.post("/").then().statusCode(200);
String roleArn = "arn:aws:iam::" + account + ":role/" + role;
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
int port;
try (ServerSocket socket = new ServerSocket(0)) {
port = socket.getLocalPort();
}
when(config.services().ecs().taskRoleCredentials().port()).thenReturn(port);
when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L);
Vertx vertx = Vertx.vertx();
EcsTaskRoleCredentials credentials = new EcsTaskRoleCredentials(iam, config);
EcsTaskRoleCredentialsServer server = new EcsTaskRoleCredentialsServer(vertx, config, credentials);
String endpoint = "http://127.0.0.1:" + port;
try (HttpClient client = HttpClient.newHttpClient()) {
server.start().get(10, TimeUnit.SECONDS);
String path = credentials.issue(taskArn, roleArn, account, Instant.now()).orElseThrow();
assertTrue(path.matches("^/v2/credentials/[0-9a-f-]{36}$"), path);
assertEquals(404, get(client, endpoint + "/v2/credentials/" + UUID.randomUUID()).statusCode());
HttpResponse<String> response = get(client, endpoint + path);
assertEquals(200, response.statusCode());
JsonObject body = new JsonObject(response.body());
assertEquals(roleArn, body.getString("RoleArn"));
assertTrue(Instant.parse(body.getString("Expiration")).isAfter(Instant.now()));
String key = body.getString("AccessKeyId");
String token = body.getString("Token");
assertTrue(key.startsWith("ASIA"));
assertEquals(body.getString("SecretAccessKey"), iam.findSecretKey(key, token).orElseThrow());
assertEquals(account, iam.resolveAccountId(key).orElseThrow());
credentials.revoke(taskArn);
assertNotEquals(200, get(client, endpoint + path).statusCode());
assertTrue(iam.findSecretKey(key, token).isEmpty());
} finally {
server.stop();
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
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) throws Exception {
return client.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(5)).GET().build(),
HttpResponse.BodyHandlers.ofString());
}
}
@@ -0,0 +1,144 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentials;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Uses a real {@link IamService} backed by in-memory storage, the same way
* {@code IamServiceTest} and {@code Ec2InstanceCredentialsTest} do: the behaviour under test is
* the interaction between the two, not either one in isolation.
*/
class EcsTaskRoleCredentialsTest {
private static final String TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/cluster/abc123";
private static final String OTHER_TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/cluster/def456";
private IamService iamService;
private EcsTaskRoleCredentials credentials;
private String roleArn;
@BeforeEach
void setUp() {
iamService = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false);
roleArn = iamService.createRole("ecsTaskRole", "/", "{}", null, 3600, null).getArn();
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L);
credentials = new EcsTaskRoleCredentials(iamService, config);
}
@Test
void issueMintsAResolvableSessionScopedToTheTask() {
Instant now = Instant.now();
String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow();
assertTrue(path.matches("^/v2/credentials/[0-9a-f-]{36}$"), path);
SessionCredential session = credentials.resolveByPath(path, now).orElseThrow();
assertEquals(roleArn, session.getRoleArn());
assertEquals(TASK_ARN, session.getEcsTaskArn());
assertEquals("000000000000", session.getOriginAccountId());
assertTrue(session.getAccessKeyId().startsWith("ASIA"));
assertEquals(now.plusSeconds(21600), session.getExpiration());
// Findable through the normal SigV4 path too, the same way ECS SDKs authenticate with it.
assertTrue(iamService.findSecretKey(session.getAccessKeyId(), session.getSessionToken()).isPresent());
}
@Test
void issueForUnknownRoleMintsNothing() {
assertTrue(credentials.issue(TASK_ARN, "arn:aws:iam::000000000000:role/does-not-exist",
"000000000000", Instant.now()).isEmpty());
}
@Test
void reissuingWellBeforeExpiryReturnsTheSamePath() {
Instant now = Instant.now();
String first = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow();
String second = credentials.issue(TASK_ARN, roleArn, "000000000000", now.plusSeconds(10)).orElseThrow();
assertEquals(first, second);
}
@Test
void reissuingInsideTheRotationWindowMintsAFreshGenerationAndRetiresTheOld() {
Instant now = Instant.now();
String first = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow();
SessionCredential firstSession = credentials.resolveByPath(first, now).orElseThrow();
// Inside the 300-second rotation window, so a fresh generation is minted.
Instant nearExpiry = firstSession.getExpiration().minusSeconds(60);
String second = credentials.issue(TASK_ARN, roleArn, "000000000000", nearExpiry).orElseThrow();
assertNotEquals(first, second);
assertTrue(credentials.resolveByPath(first, nearExpiry).isEmpty(), "retired generation must stop resolving");
assertTrue(credentials.resolveByPath(second, nearExpiry).isPresent());
assertTrue(iamService.findSecretKey(firstSession.getAccessKeyId(), firstSession.getSessionToken()).isEmpty(),
"the retired generation's access key must stop authenticating");
}
@Test
void separateTasksGetIndependentSessions() {
Instant now = Instant.now();
String taskAPath = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow();
String taskBPath = credentials.issue(OTHER_TASK_ARN, roleArn, "000000000000", now).orElseThrow();
assertNotEquals(taskAPath, taskBPath);
assertEquals(TASK_ARN, credentials.resolveByPath(taskAPath, now).orElseThrow().getEcsTaskArn());
assertEquals(OTHER_TASK_ARN, credentials.resolveByPath(taskBPath, now).orElseThrow().getEcsTaskArn());
credentials.revoke(TASK_ARN);
assertTrue(credentials.resolveByPath(taskAPath, now).isEmpty());
assertTrue(credentials.resolveByPath(taskBPath, now).isPresent(), "revoking one task must not touch another");
}
@Test
void revokeStopsTheAccessKeyFromAuthenticating() {
Instant now = Instant.now();
String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow();
SessionCredential session = credentials.resolveByPath(path, now).orElseThrow();
credentials.revoke(TASK_ARN);
assertTrue(credentials.resolveByPath(path, now).isEmpty());
assertTrue(iamService.findSecretKey(session.getAccessKeyId(), session.getSessionToken()).isEmpty());
}
@Test
void revokingAnUnknownTaskIsANoOp() {
credentials.revoke("arn:aws:ecs:us-east-1:000000000000:task/cluster/never-issued");
}
@Test
void resolveByPathExpiresAndRevokesOnceThePastExpirationIsSeen() {
Instant now = Instant.now();
String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow();
Optional<SessionCredential> pastExpiry = credentials.resolveByPath(path, now.plusSeconds(21601));
assertTrue(pastExpiry.isEmpty());
assertTrue(credentials.resolveByPath(path, now).isEmpty(), "an expired path must not come back");
}
@Test
void resolveByPathForUnknownPathIsEmpty() {
assertTrue(credentials.resolveByPath("/v2/credentials/does-not-exist", Instant.now()).isEmpty());
assertTrue(credentials.resolveByPath(null, Instant.now()).isEmpty());
}
}