mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
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:
1 parent
acafe73a2c
commit
3f5741a965
6 files changed
+531
No files matched your search
@@ -2011,6 +2011,38 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean allowUnsafeHostVolumes();
|
||||
|
||||
EcsTaskRoleCredentialsConfig taskRoleCredentials();
|
||||
}
|
||||
|
||||
interface EcsTaskRoleCredentialsConfig {
|
||||
/**
|
||||
* Opt-in: vends real task-role credentials over the AWS container-credentials wire
|
||||
* contract. Off by default: reaching it from a task container needs a Docker network the
|
||||
* task and Floci both have real access to, which the follow-up wiring this feeds into
|
||||
* establishes; this alone has no way to satisfy it.
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean enabled();
|
||||
|
||||
/**
|
||||
* Credential lifetime. AWS documents six hours as the default for task-role credentials,
|
||||
* rotated by the agent well before expiry; kept configurable for tests that want a short
|
||||
* TTL without waiting on the real one.
|
||||
*/
|
||||
@WithDefault("21600")
|
||||
long ttlSeconds();
|
||||
|
||||
/**
|
||||
* Port on the Floci host serving the credentials endpoint itself. Not the address a task
|
||||
* container talks to: real ECS SDKs hardcode 169.254.170.2, which nothing in Floci's own
|
||||
* process can bind without also owning that address on the task's Docker network. A
|
||||
* follow-up piece launches a small proxy container that holds that address and forwards
|
||||
* to this port, the same way Lambda and ECS containers already reach Floci's other
|
||||
* endpoints over {@code host.docker.internal}.
|
||||
*/
|
||||
@WithDefault("51679")
|
||||
int port();
|
||||
}
|
||||
|
||||
interface ResourceGroupsTaggingServiceConfig {
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
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 jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Mints, rotates, and revokes the IAM sessions vended through the ECS task-role credential
|
||||
* endpoint. Modeled on {@code Ec2InstanceCredentials}: unlike a persisted STS session, a task
|
||||
* credential is owned by one exact task and cannot outlive it or a Floci restart.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EcsTaskRoleCredentials {
|
||||
|
||||
private static final String UPPER_ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
/**
|
||||
* A session is rotated once less than this much of its lifetime remains, so an in-flight SDK
|
||||
* request never races a credential that expires mid-call. AWS rotates task credentials well
|
||||
* ahead of their advertised expiry for the same reason.
|
||||
*/
|
||||
private static final long ROTATE_WITHIN_SECONDS = 300;
|
||||
|
||||
private final IamService iamService;
|
||||
private final long ttlSeconds;
|
||||
|
||||
/** taskArn -> the task's current issued session and the relative URI it was published at. */
|
||||
private final Map<String, Issued> byTaskArn = new ConcurrentHashMap<>();
|
||||
/** relative URI path -> the session it resolves to, for the credentials endpoint's lookup. */
|
||||
private final Map<String, Issued> byPath = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public EcsTaskRoleCredentials(IamService iamService, EmulatorConfig config) {
|
||||
this.iamService = iamService;
|
||||
this.ttlSeconds = config.services().ecs().taskRoleCredentials().ttlSeconds();
|
||||
}
|
||||
|
||||
/**
|
||||
* Issues a session for the task's role, or returns its current one if it has not entered its
|
||||
* rotation window. Returns empty, minting nothing, for a role that does not exist under the
|
||||
* task's account: real ECS would fail the task launch outright on an unassumable role, but
|
||||
* this provider fails closed on the credential surface instead, since RunTask has already
|
||||
* created the task by the time containers are started.
|
||||
*/
|
||||
public synchronized Optional<String> issue(String taskArn, String roleArn, String accountId, Instant now) {
|
||||
if (taskArn == null || taskArn.isBlank() || roleArn == null || roleArn.isBlank()
|
||||
|| accountId == null || accountId.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Issued current = byTaskArn.get(taskArn);
|
||||
if (current != null && current.session.getRoleArn().equals(roleArn)
|
||||
&& current.session.getExpiration().isAfter(now.plusSeconds(ROTATE_WITHIN_SECONDS))) {
|
||||
return Optional.of(current.path);
|
||||
}
|
||||
|
||||
Optional<IamRole> role = resolveRole(roleArn, accountId);
|
||||
if (role.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
SessionCredential session = new SessionCredential(
|
||||
"ASIA" + random(UPPER_ALPHANUMERIC, 16), randomBase64(30), randomBase64(48),
|
||||
roleArn, now.plusSeconds(ttlSeconds), null, accountId);
|
||||
session.setEcsTaskArn(taskArn);
|
||||
iamService.registerEcsTaskRoleSession(session);
|
||||
|
||||
String path = "/v2/credentials/" + UUID.randomUUID();
|
||||
Issued issued = new Issued(session, path);
|
||||
byPath.put(path, issued);
|
||||
byTaskArn.put(taskArn, issued);
|
||||
if (current != null) {
|
||||
byPath.remove(current.path, current);
|
||||
iamService.unregisterSession(accountId, current.session.getAccessKeyId());
|
||||
}
|
||||
return Optional.of(path);
|
||||
}
|
||||
|
||||
/** Resolves the active session addressed by its relative URI path, for the endpoint handler. */
|
||||
public synchronized Optional<SessionCredential> resolveByPath(String path, Instant now) {
|
||||
Issued issued = path == null ? null : byPath.get(path);
|
||||
if (issued == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!issued.session.getExpiration().isAfter(now)) {
|
||||
revoke(issued);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(issued.session);
|
||||
}
|
||||
|
||||
/** Revokes the task's credentials on task stop, exit, or a launch that failed part way through. */
|
||||
public synchronized void revoke(String taskArn) {
|
||||
Issued issued = taskArn == null ? null : byTaskArn.get(taskArn);
|
||||
if (issued != null) {
|
||||
revoke(issued);
|
||||
}
|
||||
}
|
||||
|
||||
private void revoke(Issued issued) {
|
||||
byTaskArn.remove(issued.session.getEcsTaskArn(), issued);
|
||||
byPath.remove(issued.path, issued);
|
||||
iamService.unregisterSession(issued.session.getOriginAccountId(), issued.session.getAccessKeyId());
|
||||
}
|
||||
|
||||
private Optional<IamRole> resolveRole(String roleArn, String accountId) {
|
||||
AwsArnUtils.Arn parsed;
|
||||
try {
|
||||
parsed = AwsArnUtils.parse(roleArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
|
||||
if (roleName.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return iamService.findRole(accountId, roleName).filter(role -> roleArn.equals(role.getArn()));
|
||||
}
|
||||
|
||||
private static String random(String characters, int length) {
|
||||
StringBuilder value = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
value.append(characters.charAt(SECURE_RANDOM.nextInt(characters.length())));
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static String randomBase64(int byteLength) {
|
||||
byte[] bytes = new byte[byteLength];
|
||||
SECURE_RANDOM.nextBytes(bytes);
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private record Issued(SessionCredential session, String path) {}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
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 jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Serves the AWS container-credentials wire contract that
|
||||
* {@code AWS_CONTAINER_CREDENTIALS_RELATIVE_URI} points at: {@code GET /v2/credentials/<id>}
|
||||
* returning {@code RoleArn}/{@code AccessKeyId}/{@code SecretAccessKey}/{@code Token}/
|
||||
* {@code Expiration}.
|
||||
*
|
||||
* <p>Bound to a normal Floci-host port, not to 169.254.170.2: the AWS SDK hardcodes that address
|
||||
* (it is not configurable, unlike EC2's {@code AWS_EC2_METADATA_SERVICE_ENDPOINT}), and nothing in
|
||||
* Floci's own process can bind an address it does not otherwise own on a task's Docker network.
|
||||
* A follow-up piece is what actually holds 169.254.170.2, one small proxy container per ECS
|
||||
* network, forwarding here over {@code host.docker.internal}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EcsTaskRoleCredentialsServer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EcsTaskRoleCredentialsServer.class);
|
||||
private static final DateTimeFormatter ISO = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private final Vertx vertx;
|
||||
private final EmulatorConfig config;
|
||||
private final EcsTaskRoleCredentials credentials;
|
||||
|
||||
private volatile HttpServer httpServer;
|
||||
|
||||
@Inject
|
||||
public EcsTaskRoleCredentialsServer(Vertx vertx, EmulatorConfig config, EcsTaskRoleCredentials credentials) {
|
||||
this.vertx = vertx;
|
||||
this.config = config;
|
||||
this.credentials = credentials;
|
||||
}
|
||||
|
||||
public synchronized CompletableFuture<Void> start() {
|
||||
if (httpServer != null) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
||||
int port = config.services().ecs().taskRoleCredentials().port();
|
||||
|
||||
Router router = Router.router(vertx);
|
||||
router.get("/v2/credentials/:id").handler(this::handleCredentials);
|
||||
|
||||
httpServer = vertx.createHttpServer();
|
||||
httpServer.requestHandler(router).listen(port, result -> {
|
||||
if (result.succeeded()) {
|
||||
LOG.infof("ECS task-role credentials server listening on port %d", port);
|
||||
future.complete(null);
|
||||
} else {
|
||||
LOG.warnf("ECS task-role credentials server failed to start on port %d: %s",
|
||||
port, result.cause().getMessage());
|
||||
future.completeExceptionally(result.cause());
|
||||
}
|
||||
});
|
||||
return future;
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
if (httpServer != null) {
|
||||
httpServer.close();
|
||||
httpServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleCredentials(RoutingContext ctx) {
|
||||
String path = "/v2/credentials/" + ctx.pathParam("id");
|
||||
Optional<SessionCredential> session = credentials.resolveByPath(path, Instant.now());
|
||||
if (session.isEmpty()) {
|
||||
ctx.response().setStatusCode(404).end();
|
||||
return;
|
||||
}
|
||||
SessionCredential creds = session.get();
|
||||
ctx.response().putHeader("content-type", "application/json").end(new JsonObject()
|
||||
.put("RoleArn", creds.getRoleArn())
|
||||
.put("AccessKeyId", creds.getAccessKeyId())
|
||||
.put("SecretAccessKey", creds.getSecretAccessKey())
|
||||
.put("Token", creds.getSessionToken())
|
||||
.put("Expiration", ISO.format(creds.getExpiration())).encode());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user