fix(codebuild): run a build as its project's service role (#7844)

* fix(codebuild): run a build as its project's service role
* fix(codebuild): fail a build whose role does not exist in PROVISIONING, and share confirmed removal
This commit is contained in:
Charles Swanberg authored and GitHub committed 2026-11-18 21:10:52 -04:00
1 parent 26dc6d79ed
commit 8d005d70d0
24 files changed
+1148 -69

No files matched your search

@@ -772,6 +772,23 @@ public class ContainerLifecycleManager {
stopAndRemoveStrict(containerId, logStream, stopTimeoutSeconds, false);
}
/**
* Stops and removes a container, reporting whether Docker confirmed it gone, for a caller that
* holds something of the container's, such as a link-local address, that must not be handed on
* while the container survives. A failure is logged rather than thrown, and the log stream is
* left open, as {@link #stopAndRemoveStrict(String, Closeable)} leaves it.
*/
public boolean stopAndConfirmRemoved(String containerId, Closeable logStream, int stopTimeoutSeconds,
boolean removeAnonymousVolumes) {
try {
stopAndRemoveStrict(containerId, logStream, stopTimeoutSeconds, removeAnonymousVolumes);
return true;
} catch (RuntimeException e) {
LOG.warnv("Container {0} was not confirmed removed: {1}", containerId, e.getMessage());
return false;
}
}
/** Strict teardown that can also reclaim the container's anonymous volumes. */
public void stopAndRemoveStrict(String containerId, Closeable logStream, int stopTimeoutSeconds,
boolean removeAnonymousVolumes) {
@@ -435,9 +435,18 @@ public record ContainerSpec(
return deviceRequests != null && !deviceRequests.isEmpty();
}
/**
* Whether a container on this network can be given a link-local address: only a user-defined
* network can, never Docker's default bridge, {@code host}, {@code none} or another container's
* namespace.
*/
public static boolean acceptsLinkLocalIps(String networkMode) {
return networkMode != null && !networkMode.isBlank()
&& !NETWORKS_WITHOUT_ENDPOINT_IPAM.contains(networkMode) && !networkMode.startsWith("container:");
}
private static void requireUserDefinedNetwork(String networkMode) {
if (networkMode == null || networkMode.isBlank()
|| NETWORKS_WITHOUT_ENDPOINT_IPAM.contains(networkMode) || networkMode.startsWith("container:")) {
if (!acceptsLinkLocalIps(networkMode)) {
throw new IllegalArgumentException(
"Link-local addresses need a user-defined Docker network, but the network is '"
+ networkMode + "'");
@@ -428,7 +428,8 @@ public class EmulatorLifecycle {
}
});
runCleanup("ECS task-role credentials server", () -> {
if (config.services().ecs().taskRoleCredentials().enabled()) {
// A CodeBuild build starts it on its need whether or not ECS's setting is on.
if (config.services().ecs().taskRoleCredentials().enabled() || ecsTaskRoleCredentialsServer.isRunning()) {
ecsTaskRoleCredentialsServer.stop();
}
});
@@ -0,0 +1,135 @@
package io.floci.aws.services.codebuild;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.services.ecs.container.EcsCredentialsProxy;
import io.floci.aws.services.ecs.container.EcsTaskLinkLocalAddresses;
import io.floci.aws.services.ecs.container.EcsTaskRoleCredentials;
import io.floci.aws.services.ecs.container.EcsTaskRoleCredentialsServer;
import io.floci.aws.services.iam.model.SessionCredential;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Hands a build a session of its project's service role, as CodeBuild does: "CodeBuild uses the
* service role for all operations that are performed on your behalf" (AWS CodeBuild User Guide,
* Allow CodeBuild to interact with other AWS services). CodeBuild hands it through the container
* credentials provider, one variable, {@code AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}, whose path
* the SDKs read at {@code http://169.254.170.2}, and no keys in the build's environment.
*
* <p>The session is the role's, minted in the project's account and named
* {@code AWSCodeBuild-<the build id after the project's name>}, as CodeBuild names it, so
* {@code GetCallerIdentity} answers its {@code assumed-role} ARN and IAM enforcement evaluates the
* role's policies. It is served by the same credentials server and per-network proxy as an ECS
* task's role, which start on a build's need whatever ECS's own setting says. On Docker's default
* bridge no container can hold the link-local address that reaches the proxy, so there the same
* session is handed as keys instead, and the build still runs as its role.
*
* <p>The role's trust policy is not evaluated: like an ECS task's, the session is minted for any
* role that exists. A role that does not exist mints nothing, and the build fails before its first
* command, as CodeBuild cannot assume it; a network whose endpoint cannot be served hands the
* session as keys.
*/
@ApplicationScoped
public class CodeBuildRoleCredentials {
static final String RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
private static final Logger LOG = Logger.getLogger(CodeBuildRoleCredentials.class);
private static final String SESSION_PREFIX = "AWSCodeBuild-";
private static final long SERVER_START_SECONDS = 30;
private final EcsTaskRoleCredentials sessions;
private final EcsTaskRoleCredentialsServer server;
private final EcsCredentialsProxy proxy;
private final EcsTaskLinkLocalAddresses addresses;
@Inject
public CodeBuildRoleCredentials(EcsTaskRoleCredentials sessions, EcsTaskRoleCredentialsServer server,
EcsCredentialsProxy proxy, EcsTaskLinkLocalAddresses addresses) {
this.sessions = sessions;
this.server = server;
this.proxy = proxy;
this.addresses = addresses;
}
/**
* Mints the build's session and readies what serves it on the build's network, before the
* build's container is made.
*
* @param buildArn the build's ARN, which owns the session and its address until {@link #releaseAddress}
* @param network the Docker network the build's container joins, empty for the default bridge
* @throws RoleNotFoundException when the role names no role in the account; nothing is minted
*/
public BuildCredentials provision(String buildArn, String buildId, String roleArn, String accountId,
Optional<String> network) {
String sessionName = SESSION_PREFIX + buildId.substring(buildId.indexOf(':') + 1);
Optional<String> path = sessions.issue(buildArn, roleArn, accountId, sessionName, Instant.now());
if (path.isEmpty()) {
throw new RoleNotFoundException("CodeBuild is not authorized to perform: sts:AssumeRole on " + roleArn);
}
Optional<String> endpointNetwork = network.filter(ContainerSpec::acceptsLinkLocalIps);
if (endpointNetwork.isPresent()) {
try {
startServer();
proxy.ensureProxyOn(endpointNetwork.get());
String address = addresses.allocate(endpointNetwork.get(), buildArn);
return new BuildCredentials(Map.of(RELATIVE_URI, path.get()), address);
} catch (IllegalStateException e) {
LOG.warnv("Build {0}: the container credentials endpoint cannot be served on network {1} ({2}), "
+ "so the build's session is handed as keys instead", buildId, endpointNetwork.get(),
e.getMessage());
}
}
SessionCredential session = sessions.resolveByPath(path.get(), Instant.now()).orElseThrow(() ->
new IllegalStateException("The session of " + roleArn + " was revoked as it was minted"));
Map<String, String> env = new LinkedHashMap<>();
env.put("AWS_ACCESS_KEY_ID", session.getAccessKeyId());
env.put("AWS_SECRET_ACCESS_KEY", session.getSecretAccessKey());
env.put("AWS_SESSION_TOKEN", session.getSessionToken());
return new BuildCredentials(env, null);
}
/** Revokes every generation of the build's session, however the build ended. */
public void revoke(String buildArn) {
sessions.revoke(buildArn);
}
/** Returns the build's address to its network's pool, once its container is gone. */
public void releaseAddress(String buildArn) {
addresses.releaseAll(buildArn);
}
private void startServer() {
try {
server.start().get(SERVER_START_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while starting the container credentials server", e);
} catch (ExecutionException | TimeoutException e) {
Throwable cause = e instanceof ExecutionException && e.getCause() != null ? e.getCause() : e;
throw new IllegalStateException("The container credentials server did not start: " + cause.getMessage(), e);
}
}
/**
* What the build's container is given: the variables that hand it its session, and its own
* link-local address on the network, null on the default bridge.
*/
public record BuildCredentials(Map<String, String> env, String linkLocalAddress) {
}
/** A project's service role that names no role in the project's account. */
public static final class RoleNotFoundException extends RuntimeException {
RoleNotFoundException(String message) {
super(message);
}
}
}
@@ -90,6 +90,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
private final VpcContainerLeases vpcLeases;
/** This run's build containers, so a later run knows the ones a crash leaves for leftovers. */
private final RunLabelledContainers runContainers;
private final CodeBuildRoleCredentials roleCredentials;
private final ConcurrentHashMap<String, String> runningContainers = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
@@ -106,7 +107,8 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
ContainerDetector containerDetector,
RegionResolver regionResolver,
ContainerReachableEndpoint containerEndpoint,
Ec2Service ec2Service) {
Ec2Service ec2Service,
CodeBuildRoleCredentials roleCredentials) {
this.dockerClient = dockerClient;
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
@@ -120,6 +122,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
this.containerEndpoint = containerEndpoint;
this.vpcLeases = new VpcContainerLeases(ec2Service, "CodeBuild build", () -> dockerClient);
this.runContainers = new RunLabelledContainers(lifecycleManager, config, "codebuild", RUN_LABEL, LOG);
this.roleCredentials = roleCredentials;
}
/**
@@ -184,10 +187,24 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
if (stopFlag.get()) { finishStopped(build); return; }
// PROVISIONING
// PROVISIONING: the build's own session of its project's service role, before
// anything of its buildspec runs.
beginPhase(build, "PROVISIONING");
build.setCurrentPhase("PROVISIONING");
workspace = Files.createTempDirectory("floci-codebuild-");
Optional<String> network = containerBuilder.resolveDockerNetwork(config.services().codebuild().dockerNetwork());
CodeBuildRoleCredentials.BuildCredentials credentials;
try {
credentials = roleCredentials.provision(executionId, buildId, project.getServiceRole(),
accountOf(project), network);
} catch (CodeBuildRoleCredentials.RoleNotFoundException e) {
completePhaseWithError(build, "PROVISIONING", "FAILED", "CLIENT_ERROR", e.getMessage());
finishFailed(build);
return;
} catch (RuntimeException e) {
completePhaseWithError(build, "PROVISIONING", "FAILED", "FAULT_ERROR", e.getMessage());
throw e;
}
completePhase(build, "PROVISIONING", "SUCCEEDED");
if (stopFlag.get()) { finishStopped(build); return; }
@@ -236,11 +253,11 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
logsMap.put("cloudWatchLogsArn", AwsArnUtils.Arn.of("logs", region, regionResolver.getAccountId(), "log-group:" + logGroup + ":log-stream:" + logStream).toString());
build.setLogs(logsMap);
List<String> envList = buildEnvList(region, build, project, buildspec, logStream);
List<String> envList = buildEnvList(region, build, project, buildspec, logStream, credentials.env());
// Keep the container alive so each phase can be run with docker exec.
// No bind mount needed — source and artifacts are transferred with docker cp.
ContainerSpec spec = containerBuilder.newContainer(image)
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withCmd(List.of("sh", "-c", "tail -f /dev/null"))
.withEnv(envList)
.withDockerNetwork(config.services().codebuild().dockerNetwork())
@@ -248,8 +265,13 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
.withHostDockerInternalOnLinux()
.withPrivileged(privileged)
.withLogRotation()
.withLabels(buildLabels(buildId, region))
.build();
.withLabels(buildLabels(buildId, region));
// Its own address in 169.254.0.0/16, without which the container has no route to the
// credentials endpoint's 169.254.170.2.
if (credentials.linkLocalAddress() != null) {
specBuilder.withLinkLocalIp(credentials.linkLocalAddress());
}
ContainerSpec spec = specBuilder.build();
// Build state does not outlive the process, so a crash's build containers have nothing left to finish.
runContainers.removeLeftovers();
@@ -407,8 +429,15 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
}
} finally {
stopFlags.remove(executionId);
// However the build ended, its session ends with it.
roleCredentials.revoke(executionId);
boolean containerGone = true;
if (containerId != null && runningContainers.remove(executionId, containerId)) {
lifecycleManager.stopAndRemove(containerId, logHandle);
containerGone = lifecycleManager.stopAndConfirmRemoved(containerId, logHandle, 5, false);
// A failed removal leaves the log stream open for a retry, and a build has none.
if (!containerGone && logHandle != null) {
try { logHandle.close(); } catch (Exception ignored) {}
}
} else if (logHandle != null) {
try { logHandle.close(); } catch (Exception ignored) {}
}
@@ -416,6 +445,11 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
if (containerId != null) {
vpcLeases.releaseIfGone(containerId);
}
// The address goes back to its network's pool only once no container holds it, as an
// ECS task's does; a container that survived removal keeps it reserved.
if (containerGone) {
roleCredentials.releaseAddress(executionId);
}
if (workspace != null) {
deleteDirectory(workspace);
}
@@ -501,8 +535,20 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
throw new AwsException("InvalidInputException", "No buildspec found in source or request", 400);
}
/** The account the project is in, which its role is looked up and its session minted in. */
private String accountOf(Project project) {
try {
return AwsArnUtils.parse(project.getArn()).accountId();
} catch (IllegalArgumentException e) {
LOG.warnv("Project {0} has no parsable ARN ({1}), so its service role is looked up in the default "
+ "account {2}", project.getName(), project.getArn(), regionResolver.getAccountId());
return regionResolver.getAccountId();
}
}
private List<String> buildEnvList(String region, Build build, Project project,
ParsedBuildspec buildspec, String logStream) {
ParsedBuildspec buildspec, String logStream,
Map<String, String> credentials) {
Map<String, String> env = new LinkedHashMap<>();
env.put("CODEBUILD_BUILD_ID", build.getId());
@@ -515,9 +561,10 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
env.put("CODEBUILD_LOG_PATH", logStream);
env.put("AWS_DEFAULT_REGION", region);
env.put("AWS_REGION", region);
env.put("AWS_ACCESS_KEY_ID", "test");
env.put("AWS_SECRET_ACCESS_KEY", "test");
env.put("AWS_ENDPOINT_URL", resolveEndpointUrl());
// The project's role, ahead of everything a project, its buildspec or the build's start
// sets, which still reaches the build as CodeBuild's own variables do.
env.putAll(credentials);
env.putAll(buildspec.envVariables());
@@ -880,6 +927,11 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
}
private void completePhaseWithError(Build build, String phaseType, String status, String message) {
completePhaseWithError(build, phaseType, status, "COMMAND_EXECUTION_ERROR", message);
}
private void completePhaseWithError(Build build, String phaseType, String status, String statusCode,
String message) {
findPhase(build, phaseType).ifPresent(p -> {
double end = EpochSeconds.fromMillis(System.currentTimeMillis());
p.setPhaseStatus(status);
@@ -887,7 +939,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
p.setDurationInSeconds(Math.round(end - p.getStartTime()));
if (message != null) {
String truncated = message.substring(0, Math.min(message.length(), 1024));
p.setContexts(List.of(Map.of("statusCode", "COMMAND_EXECUTION_ERROR", "message", truncated)));
p.setContexts(List.of(Map.of("statusCode", statusCode, "message", truncated)));
}
});
}
@@ -1568,7 +1568,9 @@ public class EcsContainerManager {
}
boolean allRemoved = true;
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
if (stopAndConfirmRemoved(entry.getValue())) {
// A container that survived removal still holds its link-local address, which must not
// go to the next task.
if (lifecycleManager.stopAndConfirmRemoved(entry.getValue(), null, 5, true)) {
handle.recordContainerRemoved(entry.getKey());
} else {
allRemoved = false;
@@ -1592,25 +1594,6 @@ public class EcsContainerManager {
}
}
/**
* Stops and removes a container, reporting whether it is really gone.
*
* <p>{@code stopAndRemove} logs a failed removal and returns normally, which is the right
* default for callers that only want the container off the machine on a best-effort basis. It
* is not enough here: a container that survived removal still holds its link-local address,
* and releasing it would hand the same address to the next task. The strict variant throws on
* that case, which is the signal this needs.
*/
private boolean stopAndConfirmRemoved(String dockerId) {
try {
lifecycleManager.stopAndRemoveStrict(dockerId, null, 5, true);
return true;
} catch (RuntimeException e) {
LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage());
return false;
}
}
/**
* Stops all containers, captures their exit codes, then removes them.
* Stop happens before inspect so the exit code reflects the actual stop
@@ -20,9 +20,11 @@ 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.
* Mints, rotates, and revokes the IAM sessions vended through the container credentials endpoint
* ({@code AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}), for an ECS task's role and for a CodeBuild
* build's service role alike. Modeled on {@code Ec2InstanceCredentials}: unlike a persisted STS
* session, such a credential is owned by one exact workload, a task or a build, keyed by its ARN,
* and cannot outlive it or a Floci restart.
*/
@ApplicationScoped
public class EcsTaskRoleCredentials {
@@ -39,8 +41,8 @@ public class EcsTaskRoleCredentials {
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<>();
/** workload ARN -> the workload's current issued session and the relative URI it was published at. */
private final Map<String, Issued> byWorkloadArn = new ConcurrentHashMap<>();
/** relative URI path -> the session it resolves to, for the credentials endpoint's lookup. */
private final Map<String, Issued> byPath = new ConcurrentHashMap<>();
@@ -58,14 +60,30 @@ public class EcsTaskRoleCredentials {
* created the task by the time containers are started.
*/
public synchronized Optional<String> issue(String taskArn, String roleArn, String accountId, Instant now) {
Issued current = taskArn == null ? null : byTaskArn.get(taskArn);
String taskSessionName = taskArn == null || !taskArn.contains("/")
? taskArn : taskArn.substring(taskArn.lastIndexOf('/') + 1);
return issue(taskArn, roleArn, accountId, taskSessionName, now);
}
/**
* Issues a session for a container workload's role, named {@code sessionName}, or returns its
* current one if it has not entered its rotation window, as {@link #issue(String, String, String,
* Instant)} does for a task. Returns empty, minting nothing, for a role that does not exist under
* the workload's account.
*
* @param workloadArn the ARN of the one task or build the session belongs to, which revokes it
* @param sessionName the role session name {@code GetCallerIdentity} answers the session under
*/
public synchronized Optional<String> issue(String workloadArn, String roleArn, String accountId,
String sessionName, Instant now) {
Issued current = workloadArn == null ? null : byWorkloadArn.get(workloadArn);
if (current != null && (!current.session.getRoleArn().equals(roleArn)
|| !current.session.getOriginAccountId().equals(accountId))) {
revoke(current);
current = null;
}
if (taskArn == null || taskArn.isBlank() || roleArn == null || roleArn.isBlank()
|| accountId == null || accountId.isBlank()) {
if (workloadArn == null || workloadArn.isBlank() || roleArn == null || roleArn.isBlank()
|| accountId == null || accountId.isBlank() || sessionName == null) {
return Optional.empty();
}
Optional<IamRole> role = resolveRole(roleArn, accountId);
@@ -92,11 +110,10 @@ public class EcsTaskRoleCredentials {
SessionCredential session = new SessionCredential(
"ASIA" + random(UPPER_ALPHANUMERIC, 16), randomBase64(30), randomBase64(48),
roleArn, now.plusSeconds(ttlSeconds), null, accountId);
session.setEcsTaskArn(taskArn);
String taskSessionName = taskArn.contains("/") ? taskArn.substring(taskArn.lastIndexOf('/') + 1) : taskArn;
session.setRoleSessionName(taskSessionName);
session.setEcsTaskArn(workloadArn);
session.setRoleSessionName(sessionName);
if (role.get().getRoleId() != null) {
session.setAssumedRoleId(role.get().getRoleId() + ":" + taskSessionName);
session.setAssumedRoleId(role.get().getRoleId() + ":" + sessionName);
}
iamService.registerEcsTaskRoleSession(session);
@@ -111,7 +128,7 @@ public class EcsTaskRoleCredentials {
}
Issued issued = new Issued(session, path, role.get().getRoleId(), previous);
byPath.put(path, issued);
byTaskArn.put(taskArn, issued);
byWorkloadArn.put(workloadArn, issued);
return Optional.of(path);
}
@@ -122,19 +139,23 @@ public class EcsTaskRoleCredentials {
return Optional.empty();
}
return issue(issued.session.getEcsTaskArn(), issued.session.getRoleArn(),
issued.session.getOriginAccountId(), now).map(renewedPath -> byPath.get(renewedPath).session);
issued.session.getOriginAccountId(), issued.session.getRoleSessionName(), now)
.map(renewedPath -> byPath.get(renewedPath).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);
/**
* Revokes a workload's credentials, every generation of them: on a task's stop, exit, or a
* launch that failed part way through, and on a build's end, however it ends.
*/
public synchronized void revoke(String workloadArn) {
Issued issued = workloadArn == null ? null : byWorkloadArn.get(workloadArn);
if (issued != null) {
revoke(issued);
}
}
private void revoke(Issued issued) {
byTaskArn.remove(issued.session.getEcsTaskArn(), issued);
byWorkloadArn.remove(issued.session.getEcsTaskArn(), issued);
byPath.remove(issued.path, issued);
iamService.unregisterSession(issued.session.getOriginAccountId(), issued.session.getAccessKeyId());
for (SessionCredential previous : issued.previous) {
@@ -28,6 +28,9 @@ import java.util.concurrent.CompletableFuture;
* Floci's own process can bind an address it does not otherwise own on a task's Docker network.
* {@link EcsCredentialsProxy} is what actually holds 169.254.170.2, one small proxy container per
* ECS network, forwarding here over {@code host.docker.internal}.
*
* <p>It serves a CodeBuild build its project's service role the same way, and a build's need starts
* it whether or not ECS task-role credentials are enabled.
*/
@ApplicationScoped
public class EcsTaskRoleCredentialsServer {
@@ -41,6 +44,8 @@ public class EcsTaskRoleCredentialsServer {
private final EcsTaskRoleCredentials credentials;
private volatile HttpServer httpServer;
/** The bind in progress or done, so that a start during another's bind waits on that bind. */
private CompletableFuture<Void> listening;
@Inject
public EcsTaskRoleCredentialsServer(Vertx vertx, EmulatorConfig config, EcsTaskRoleCredentials credentials) {
@@ -50,8 +55,8 @@ public class EcsTaskRoleCredentialsServer {
}
public synchronized CompletableFuture<Void> start() {
if (httpServer != null) {
return CompletableFuture.completedFuture(null);
if (listening != null) {
return listening;
}
CompletableFuture<Void> future = new CompletableFuture<>();
int port = config.services().ecs().taskRoleCredentials().port();
@@ -59,25 +64,44 @@ public class EcsTaskRoleCredentialsServer {
Router router = Router.router(vertx);
router.get("/v2/credentials/:id").blockingHandler(this::handleCredentials);
httpServer = vertx.createHttpServer();
httpServer.requestHandler(router).listen(port, result -> {
HttpServer server = vertx.createHttpServer();
server.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());
// A failed bind leaves nothing behind, so the next start tries the bind again.
synchronized (this) {
if (listening == future) {
listening = null;
httpServer = null;
}
}
server.close();
future.completeExceptionally(result.cause());
}
});
httpServer = server;
listening = future;
return future;
}
/**
* Whether the server was started: by Floci's start with ECS task-role credentials on, or by the
* first CodeBuild build that needed it.
*/
public synchronized boolean isRunning() {
return httpServer != null;
}
public synchronized void stop() {
if (httpServer != null) {
httpServer.close();
httpServer = null;
}
listening = null;
}
private void handleCredentials(RoutingContext ctx) {
@@ -5564,7 +5564,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return removed;
}
/** Registers an ECS task-role session, outside request scope. */
/**
* Registers a session served at the container credentials endpoint, an ECS task's role or a
* CodeBuild build's service role, outside request scope.
*/
public void registerEcsTaskRoleSession(SessionCredential session) {
if (session.getOriginAccountId() == null || session.getOriginAccountId().isBlank()
|| session.getEcsTaskArn() == null || session.getEcsTaskArn().isBlank()) {
@@ -5578,7 +5581,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
/** No ECS task survives a Floci restart; discard credentials from the previous process. */
/**
* No ECS task or CodeBuild build survives a Floci restart; discard credentials from the
* previous process.
*/
public int sweepOrphanedEcsTaskRoleSessions() {
List<SessionCredential> stored = sessions instanceof AccountAwareStorageBackend<SessionCredential> aware
? aware.scanAllAccounts() : sessions.scan(key -> true);
@@ -36,7 +36,11 @@ public class SessionCredential {
private boolean lambdaExecutionRole;
private String ec2InstanceId;
private String ec2RoleId;
/** Exact ECS task ARN this session was minted for, when this is a task-role session. */
/**
* Exact ARN of the workload this session was minted for and is served to at the container
* credentials endpoint: an ECS task's, for a task-role session, or a CodeBuild build's, for a
* build's service-role session.
*/
private String ecsTaskArn;
/** Exact object action and ARN for an internally generated S3 presigned URL. */
private String presignedAction;