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

@@ -36,6 +36,7 @@ import software.amazon.awssdk.services.codebuild.model.SourceType;
import software.amazon.awssdk.services.codebuild.model.StartBuildResponse;
import software.amazon.awssdk.services.codebuild.model.Tag;
import software.amazon.awssdk.services.codebuild.model.UpdateProjectResponse;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
@@ -48,7 +49,10 @@ class CodeBuildTest {
private static final String CODEBUILD_TEST_IMAGE =
"busybox@sha256:fd8d9aa63ba2f0982b5304e1ee8d3b90a210bc1ffb5314d980eb6962f1a9715d";
private static final String SERVICE_ROLE = "codebuild-role";
static CodeBuildClient codebuild;
static IamClient iam;
static String reportGroupArn;
static String sourceCredentialsArn;
static String buildId;
@@ -56,11 +60,24 @@ class CodeBuildTest {
@BeforeAll
static void setup() {
codebuild = TestFixtures.codeBuildClient();
// CodeBuild refuses to run a build whose service role it cannot assume.
iam = TestFixtures.iamClient();
iam.createRole(r -> r
.roleName(SERVICE_ROLE)
.assumeRolePolicyDocument("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"codebuild.amazonaws.com"},
"Action":"sts:AssumeRole"}]}"""));
}
@AfterAll
static void teardown() {
codebuild.close();
try {
iam.deleteRole(r -> r.roleName(SERVICE_ROLE));
} finally {
iam.close();
codebuild.close();
}
}
@Test
+13
View File
@@ -76,6 +76,19 @@ Source injection and artifact extraction both use the Docker API's archive copy
CodeBuild runs a build of a project with a `vpcConfig` with a network interface in one of the project's subnets. Floci puts the build container on that VPC's Docker network, at an address leased from the first subnet, before the first phase runs, the way it places EC2 instances, VPC-configured Lambda functions and MWAA environments, so a build reaches a database or anything else in the VPC by its private IP. The container keeps the network it was created on as well. A subnet EC2 does not know, or `FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=false`, leaves it there alone. Security groups are not enforced, as for EC2. While a build runs, `DeleteSubnet` refuses its subnet and `DeleteVpc` its VPC (`DependencyViolation`), as the build's network interface does on AWS; a project's `vpcConfig` alone holds none. `BatchGetBuilds` returns the project's `vpcConfig` on each build.
## The Build's Credentials
A build runs as its project's `serviceRole`, as CodeBuild uses the service role for every operation it performs on the account's behalf. Floci mints a session of that role in the project's account, named `AWSCodeBuild-<build id after the project's name>`, so `aws sts get-caller-identity` inside the build answers `arn:aws:sts::<account>:assumed-role/<role name>/AWSCodeBuild-<id>`, and with `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true` the role's policies decide what the build may call. Floci puts no access keys of its own in the build's environment.
How the session reaches the build depends on the Docker network the build joins, `FLOCI_SERVICES_CODEBUILD_DOCKER_NETWORK`, else `FLOCI_SERVICES_DOCKER_NETWORK`, else Floci's own when Floci runs in a container:
- **On a user-defined network**, the session is served the way CodeBuild serves it: the build gets `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` and none of `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_CONTAINER_CREDENTIALS_FULL_URI` or `AWS_CONTAINER_AUTHORIZATION_TOKEN`, and the AWS SDKs and CLI read the role's credentials at `http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, with no code change. Floci serves that address with the same credentials server and per-network proxy container ECS task roles use (see [ECS](ecs.md#task-iam-role-credentials)), and gives the build's container its own address in `169.254.0.0/16` so it can reach it. Reads near expiry return a fresh session at the same path, and the path answers nothing once the build has ended.
- **On Docker's default bridge**, where no container can hold a link-local address, the same session is handed as `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_SESSION_TOKEN`, so the build still runs as the role; these keys are not renewed during the build, and they expire after `FLOCI_SERVICES_ECS_TASK_ROLE_CREDENTIALS_TTL_SECONDS` (6 hours by default), which a build on the bridge should not outlive.
A build whose project's role does not exist in its account fails in `PROVISIONING`, before its first command, with `CLIENT_ERROR` and the message CodeBuild gives, `CodeBuild is not authorized to perform: sts:AssumeRole on <role ARN>`. A build on a user-defined network whose endpoint cannot be served, as where the Docker runtime does not honour link-local addresses, is handed its session as the three keys instead, with a warning. A variable of any of these names that the project, the buildspec or `StartBuild` sets still reaches the build.
Unlike CodeBuild, Floci does not evaluate the role's trust policy: a role that does not trust `codebuild.amazonaws.com` is still assumed.
## Buildspec Support
Floci parses the `buildspec.yml` embedded in the project or provided via `buildspecOverride`. Supported fields:
+3
View File
@@ -1072,6 +1072,9 @@ for reasons that have nothing to do with the role's policy.
Each of these logs a warning naming the task and the role it asked for.
The same credentials server and per-network proxy also serve a CodeBuild build its project's
service role, whether or not this setting is on (see [CodeBuild](codebuild.md#the-builds-credentials)).
### Ephemeral task volumes
A volume declared with only a `name`, or with an empty `host` and no `sourcePath`, supplies
@@ -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;
@@ -62,6 +62,27 @@ class ContainerLifecycleManagerTeardownTest {
verify(logStream).close();
}
@Test
void confirmedRemovalAnswersWhetherTheContainerIsGoneAndKeepsTheLogStreamUntilItIs() throws Exception {
DockerClient docker = mock(DockerClient.class);
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
StopContainerCmd stop = mock(StopContainerCmd.class);
when(docker.stopContainerCmd("held")).thenReturn(stop);
when(stop.withTimeout(5)).thenReturn(stop);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
when(docker.removeContainerCmd("held")).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
doThrow(new IllegalStateException("daemon refused removal")).doNothing().when(remove).exec();
Closeable logStream = mock(Closeable.class);
assertFalse(manager.stopAndConfirmRemoved("held", logStream, 5, true));
verify(logStream, never()).close();
verify(remove).withRemoveVolumes(true);
assertTrue(manager.stopAndConfirmRemoved("held", logStream, 5, true));
verify(logStream).close();
}
@ParameterizedTest
@ValueSource(strings = {"strict", "strict-volumes", "best-effort", "stop-only"})
void laterOwnedStopsReachDockerWhileEarlierRemovalsAreBlocked(String mode) throws Exception {
@@ -0,0 +1,250 @@
package io.floci.aws.services.codebuild;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.services.codebuild.model.Build;
import io.floci.aws.services.codebuild.model.BuildPhase;
import io.floci.aws.services.codebuild.model.Project;
import io.floci.aws.services.codebuild.model.ProjectEnvironment;
import io.floci.aws.services.codebuild.model.ProjectSource;
import io.floci.aws.services.ec2.Ec2Service;
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.IamService;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.services.iam.model.SessionCredential;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.Closeable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A build runs as the role its project names as {@code serviceRole}, handed over the way CodeBuild
* hands it: on a user-defined network, the container credentials endpoint's relative URI and no
* keys; on the default bridge, where no container can hold a link-local address, the same session
* as keys. A build whose role cannot be found never runs a command.
*/
class CodeBuildRunnerServiceRoleTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE_NAME = "build-role";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT + ":role/service-role/" + ROLE_NAME;
private static final String NETWORK = "builds";
private static final Set<String> NO_KEYS = Set.of(
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN",
"AWS_CONTAINER_CREDENTIALS_FULL_URI", "AWS_CONTAINER_AUTHORIZATION_TOKEN",
"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE");
@Test
void aBuildOnAUserDefinedNetworkIsServedItsRoleAtTheRelativeUriAndHoldsNoKeys() throws Exception {
Fixture fixture = fixture(Optional.of(NETWORK), true, List.of());
fixture.run();
List<String> env = fixture.env();
assertEquals(List.of(), env.stream().filter(e -> NO_KEYS.contains(name(e))).toList(),
"the build's environment holds credentials of its own: " + env);
String relativeUri = value(env, "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
.orElseThrow(() -> new AssertionError("no AWS_CONTAINER_CREDENTIALS_RELATIVE_URI in " + env));
assertTrue(relativeUri.startsWith("/"), relativeUri);
assertTrue(!relativeUri.contains("://"), relativeUri);
verify(fixture.specBuilder()).withLinkLocalIp(startsWith("169.254."));
SessionCredential session = fixture.issuedSession();
assertEquals(ROLE_ARN, session.getRoleArn());
assertEquals("AWSCodeBuild-7", session.getRoleSessionName());
assertEquals(ACCOUNT, session.getOriginAccountId());
}
@Test
void aBuildOnTheDefaultBridgeHoldsItsRolesSessionAsKeys() throws Exception {
Fixture fixture = fixture(Optional.empty(), true, List.of());
fixture.run();
List<String> env = fixture.env();
SessionCredential session = fixture.issuedSession();
assertEquals(Optional.of(session.getAccessKeyId()), value(env, "AWS_ACCESS_KEY_ID"), env::toString);
assertEquals(Optional.of(session.getSecretAccessKey()), value(env, "AWS_SECRET_ACCESS_KEY"), env::toString);
assertEquals(Optional.of(session.getSessionToken()), value(env, "AWS_SESSION_TOKEN"), env::toString);
assertTrue(session.getAccessKeyId().startsWith("ASIA"), session.getAccessKeyId());
assertEquals(ROLE_ARN, session.getRoleArn());
assertEquals("AWSCodeBuild-7", session.getRoleSessionName());
assertTrue(value(env, "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI").isEmpty(), env::toString);
verify(fixture.specBuilder(), never()).withLinkLocalIp(anyString());
}
@Test
void credentialVariablesTheProjectSetsStillReachTheBuild() throws Exception {
Fixture fixture = fixture(Optional.of(NETWORK), true, List.of(
Map.of("name", "AWS_ACCESS_KEY_ID", "value", "project-key"),
Map.of("name", "AWS_SESSION_TOKEN", "value", "project-token")));
fixture.run();
List<String> env = fixture.env();
assertEquals(Optional.of("project-key"), value(env, "AWS_ACCESS_KEY_ID"), env::toString);
assertEquals(Optional.of("project-token"), value(env, "AWS_SESSION_TOKEN"), env::toString);
}
@Test
void aBuildWhoseRoleIsNotFoundFailsInProvisioning() throws Exception {
Fixture fixture = fixture(Optional.of(NETWORK), false, List.of());
fixture.run();
Build build = fixture.build();
assertEquals("FAILED", build.getBuildStatus(), () -> phases(build).toString());
BuildPhase failed = build.getPhases().stream()
.filter(phase -> "FAILED".equals(phase.getPhaseStatus()))
.findFirst().orElseThrow(() -> new AssertionError("no failed phase in " + phases(build)));
assertEquals("PROVISIONING", failed.getPhaseType());
assertEquals("CLIENT_ERROR", failed.getContexts().getFirst().get("statusCode"));
assertEquals("CodeBuild is not authorized to perform: sts:AssumeRole on " + ROLE_ARN,
failed.getContexts().getFirst().get("message"));
verify(fixture.iam(), never()).registerEcsTaskRoleSession(any());
verify(fixture.lifecycle(), never()).createAndStart(any());
}
private static List<String> phases(Build build) {
return build.getPhases().stream().map(p -> p.getPhaseType() + "=" + p.getPhaseStatus()).toList();
}
private static String name(String entry) {
int equals = entry.indexOf('=');
return equals < 0 ? entry : entry.substring(0, equals);
}
private static Optional<String> value(List<String> env, String name) {
Optional<String> found = Optional.empty();
for (String entry : env) {
if (name.equals(name(entry))) {
found = Optional.of(entry.substring(name.length() + 1));
}
}
return found;
}
private Fixture fixture(Optional<String> network, boolean roleExists, List<Map<String, String>> projectVariables) {
DockerClient docker = mock(DockerClient.class);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(network);
when(specBuilder.build()).thenReturn(new ContainerSpec("alpine:latest"));
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("container", Map.of()));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.attach(eq("container"), anyString(), anyString(), anyString(), anyString()))
.thenReturn(mock(Closeable.class));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().codebuild().dockerNetwork()).thenReturn(network);
when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
when(endpoint.port()).thenReturn(4566);
IamService iam = mock(IamService.class);
IamRole role = new IamRole();
role.setRoleId("AROABUILDROLE");
role.setRoleName(ROLE_NAME);
role.setArn(ROLE_ARN);
when(iam.findRole(ACCOUNT, ROLE_NAME)).thenReturn(roleExists ? Optional.of(role) : Optional.empty());
EcsTaskRoleCredentials credentials = new EcsTaskRoleCredentials(iam, config);
EcsTaskRoleCredentialsServer server = mock(EcsTaskRoleCredentialsServer.class);
when(server.start()).thenReturn(CompletableFuture.completedFuture(null));
EcsCredentialsProxy proxy = mock(EcsCredentialsProxy.class);
CodeBuildRunner runner = spy(new CodeBuildRunner(docker, containerBuilder, lifecycle, logStreamer,
null, null, null, config, mock(ContainerDetector.class), regionResolver, endpoint,
mock(Ec2Service.class),
new CodeBuildRoleCredentials(credentials, server, proxy, new EcsTaskLinkLocalAddresses())));
doReturn(CodeBuildRunner.PhaseResult.ofSuccess()).when(runner)
.runPhase(anyString(), anyString(), anyList(), anyList(), anyInt(), any(AtomicBoolean.class));
Build build = new Build();
build.setId("project:7");
build.setArn("arn:aws:codebuild:us-east-1:" + ACCOUNT + ":build/project:7");
build.setBuildNumber(7L);
build.setPhases(new ArrayList<>());
Project project = new Project();
project.setName("project");
project.setArn("arn:aws:codebuild:us-east-1:" + ACCOUNT + ":project/project");
project.setServiceRole(ROLE_ARN);
ProjectSource source = new ProjectSource();
source.setType("NO_SOURCE");
source.setBuildspec("version: 0.2\nphases:\n build:\n commands:\n - aws sts get-caller-identity\n");
project.setSource(source);
ProjectEnvironment environment = new ProjectEnvironment();
environment.setImage("alpine:latest");
environment.setEnvironmentVariables(projectVariables);
project.setEnvironment(environment);
return new Fixture(runner, build, project, specBuilder, lifecycle, iam);
}
private record Fixture(CodeBuildRunner runner, Build build, Project project, ContainerBuilder.Builder specBuilder,
ContainerLifecycleManager lifecycle, IamService iam) {
void run() {
runner.startBuild("us-east-1", build, project, null);
await("build finished").atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(20))
.until(() -> Boolean.TRUE.equals(build.getBuildComplete()));
}
@SuppressWarnings("unchecked")
List<String> env() {
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
verify(specBuilder, atLeastOnce()).withEnv(captor.capture());
return captor.getValue();
}
/** The one session the build's start registered with IAM. */
SessionCredential issuedSession() {
ArgumentCaptor<SessionCredential> captor = ArgumentCaptor.forClass(SessionCredential.class);
verify(iam).registerEcsTaskRoleSession(captor.capture());
return captor.getValue();
}
}
}
@@ -41,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
@@ -150,10 +151,12 @@ class CodeBuildRunnerSourceFailureTest {
when(specBuilder.build()).thenReturn(new ContainerSpec("alpine:latest"));
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(lifecycle.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("container", Map.of()));
CountDownLatch finished = new CountDownLatch(1);
doAnswer(invocation -> { finished.countDown(); return null; })
.when(lifecycle).stopAndRemove(eq("container"), nullable(Closeable.class));
.when(lifecycle).stopAndRemoveStrict(eq("container"), nullable(Closeable.class), eq(5), eq(false));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.attach(eq("container"), anyString(), anyString(), anyString(), anyString()))
@@ -171,8 +174,12 @@ class CodeBuildRunnerSourceFailureTest {
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
when(endpoint.port()).thenReturn(4566);
CodeBuildRoleCredentials roleCredentials = mock(CodeBuildRoleCredentials.class);
when(roleCredentials.provision(anyString(), anyString(), nullable(String.class), anyString(), any()))
.thenReturn(new CodeBuildRoleCredentials.BuildCredentials(Map.of(), null));
CodeBuildRunner runner = spy(new CodeBuildRunner(docker, containerBuilder, lifecycle, logStreamer,
s3, null, null, config, mock(ContainerDetector.class), regionResolver, endpoint, ec2));
s3, null, null, config, mock(ContainerDetector.class), regionResolver, endpoint, ec2,
roleCredentials));
doReturn(CodeBuildRunner.PhaseResult.ofSuccess()).when(runner)
.runPhase(anyString(), anyString(), anyList(), anyList(), anyInt(), any(AtomicBoolean.class));
@@ -37,7 +37,7 @@ class CodeBuildRunnerTest {
String lastLine = "error: build step failed\n";
DockerClient dockerClient = dockerClientStreaming(chunk, chunkCount, lastLine, 2L);
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null,
null);
null, null);
CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),
List.of("./build.sh"), 60, new AtomicBoolean(false));
@@ -51,7 +51,7 @@ class CodeBuildRunnerTest {
void failureMessageIgnoresLongTrailingWhitespace() {
DockerClient dockerClient = dockerClientStreaming(new byte[0], 0, "tests failed" + "\n".repeat(10_000), 1L);
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null,
null);
null, null);
CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),
List.of("./test.sh"), 60, new AtomicBoolean(false));
@@ -68,7 +68,7 @@ class CodeBuildRunnerTest {
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerReachableEndpoint endpoint = new ContainerReachableEndpoint(config, null, null, null, 4811);
CodeBuildRunner runner = new CodeBuildRunner(null, null, null, null, null, null, null,
config, containerDetector, null, endpoint, null);
config, containerDetector, null, endpoint, null, null);
assertEquals("http://host.docker.internal:4811", runner.resolveEndpointUrl());
}
@@ -0,0 +1,335 @@
package io.floci.aws.services.codebuild;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
import io.floci.aws.services.ecs.container.EcsCredentialsProxy;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.TestImages;
import io.floci.aws.testutil.FreePorts;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.path.json.JsonPath;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A build runs as its project's service role, end to end: on a user-defined Docker network, with
* IAM enforcement on, a build reads its role's session at {@code 169.254.170.2} through the
* container credentials proxy, the AWS CLI's default chain finds it there, STS answers the role's
* {@code AWSCodeBuild-<id>} session, and the role's policy alone decides what the build may list.
* Once the build has ended, the path it was handed answers nothing.
*
* <p>Runs in both shapes Floci runs in. With Floci on the host, the builds join a network this test
* creates, and the proxy forwards over {@code host.docker.internal}. With Floci itself in a
* container on a user-defined network, the builds join Floci's own network, as no CodeBuild network
* is configured, and the proxy forwards to Floci's address there. Floci in a container on the
* default bridge cannot hand a build the endpoint, so the test is skipped there.
*
* <p>The build installs the AWS CLI with pip, so it needs to reach PyPI. Skipped without a Docker
* daemon, like the other {@code *DockerIntegrationTest} classes.
*/
@QuarkusTest
@TestProfile(CodeBuildServiceRoleDockerIntegrationTest.Profile.class)
@Timeout(value = 10, unit = TimeUnit.MINUTES)
class CodeBuildServiceRoleDockerIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ACCOUNT = "000000000000";
private static final String ADMIN = "test";
private static final String AWS_CLI = "awscli==1.40.0";
private static final Set<String> NO_KEYS = Set.of(
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN",
"AWS_CONTAINER_CREDENTIALS_FULL_URI", "AWS_CONTAINER_AUTHORIZATION_TOKEN",
"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE");
@Inject
DockerClient dockerClient;
@Inject
ContainerDetector containerDetector;
@Inject
CurrentContainerNetworkResolver currentContainerNetworkResolver;
@Inject
EcsCredentialsProxy credentialsProxy;
@Inject
IamService iamService;
@Inject
S3Service s3Service;
@Inject
EmulatorConfig config;
private final String suffix = UUID.randomUUID().toString().substring(0, 8);
private final String roleName = "codebuild-service-role-" + suffix;
private final String projectName = "service-role-" + suffix;
private final String grantedBucket = "granted-" + suffix;
private final String otherBucket = "other-" + suffix;
private final String resultsBucket = "results-" + suffix;
private String createdNetworkId;
/** Whether the test ran, so that its cleanup has something to remove and a client set up to do it. */
private boolean ran;
@BeforeEach
void requireANetworkABuildCanReachTheEndpointOn() throws Exception {
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), "Docker daemon must be available");
RestAssuredJsonUtils.configureAwsContentTypes();
ran = true;
if (containerDetector.isRunningInContainer()) {
Optional<String> own = currentContainerNetworkResolver.resolveNetworkName();
Assumptions.assumeTrue(own.filter(Profile::userDefined).isPresent(),
"Floci runs in a container on " + own.orElse("no network")
+ ", where a build cannot hold a link-local address");
} else if (dockerClient.listNetworksCmd().withNameFilter(Profile.NETWORK).exec().stream()
.noneMatch(network -> Profile.NETWORK.equals(network.getName()))) {
createdNetworkId = dockerClient.createNetworkCmd().withName(Profile.NETWORK).exec().getId();
}
}
@AfterEach
void removeWhatTheTestMade() {
if (!ran) {
return;
}
codeBuild("DeleteProject")
.body(Map.of("name", projectName)).post("/");
for (String bucket : List.of(grantedBucket, otherBucket, resultsBucket)) {
if (s3Service.bucketExists(bucket)) {
s3Service.listObjects(bucket, null, null, 1000).forEach(o -> s3Service.deleteObject(bucket, o.getKey()));
s3Service.deleteBucket(bucket);
}
}
if (iamService.findRole(ACCOUNT, roleName).isPresent()) {
iamService.deleteRolePolicy(roleName, "ListOneBucket");
iamService.deleteRole(roleName);
}
if (createdNetworkId != null) {
// The proxy lives for the process; it has to go before the network it holds an address on.
credentialsProxy.stopManagedContainers();
awaitNoContainerOn(createdNetworkId);
dockerClient.removeNetworkCmd(createdNetworkId).exec();
}
}
/**
* The runner removes the build's container after it has reported the build complete, so a
* network removed at once still has that endpoint.
*/
private void awaitNoContainerOn(String networkId) {
await("no container on the build's network").atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(200)).until(() -> {
Map<String, ?> containers =
dockerClient.inspectNetworkCmd().withNetworkId(networkId).exec().getContainers();
return containers == null || containers.isEmpty();
});
}
@Test
void aBuildRunsAsItsProjectsServiceRoleServedAtTheContainerCredentialsEndpoint() throws Exception {
String roleArn = iamService.createRole(roleName, "/", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"codebuild.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""", null, 0, null).getArn();
iamService.putRolePolicy(roleName, "ListOneBucket", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::%s"}]}
""".formatted(grantedBucket));
for (String bucket : List.of(grantedBucket, otherBucket, resultsBucket)) {
given().header("Authorization", auth(ADMIN, "s3")).put("/" + bucket).then().statusCode(200);
}
createProject(roleArn);
String buildId = startBuild();
JsonPath build = awaitBuild(buildId);
assertEquals("SUCCEEDED", build.getString("buildStatus"), () -> "phases: " + build.getList("phases")
+ "; the credentials read: " + resultIfAny("credentials-headers.txt"));
String sessionSuffix = buildId.substring(buildId.indexOf(':') + 1);
assertEquals("arn:aws:sts::" + ACCOUNT + ":assumed-role/" + roleName + "/AWSCodeBuild-" + sessionSuffix,
result("caller.txt").strip());
List<String> names = Arrays.asList(result("env-names.txt").strip().split("\n"));
assertTrue(names.contains("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"), names::toString);
assertEquals(List.of(), names.stream().filter(NO_KEYS::contains).toList());
String relativeUri = result("relative-uri.txt").strip();
assertTrue(relativeUri.startsWith("/") && !relativeUri.contains("://"), relativeUri);
assertTrue(result("credentials-headers.txt").contains(" 200 "), () -> result("credentials-headers.txt"));
JsonNode credentials = new ObjectMapper().readTree(result("credentials.json"));
assertEquals(Set.of("AccessKeyId", "SecretAccessKey", "Token", "Expiration", "RoleArn"),
Set.copyOf(iterableToList(credentials.fieldNames())));
assertEquals(roleArn, credentials.get("RoleArn").asText());
assertEquals("granted listed", result("granted.txt").strip());
assertTrue(result("other.txt").contains("AccessDenied"), () -> result("other.txt"));
// The build's relative URI answers no credentials once the build has ended.
awaitAnswersNothing(relativeUri, Duration.ofSeconds(10));
}
private void createProject(String roleArn) {
Map<String, Object> project = new HashMap<>();
project.put("name", projectName);
project.put("source", Map.of("type", "NO_SOURCE", "buildspec", buildspec()));
project.put("artifacts", Map.of("type", "S3", "location", resultsBucket, "packaging", "NONE"));
project.put("environment", Map.of("type", "LINUX_CONTAINER", "image", TestImages.PYTHON_ALPINE,
"computeType", "BUILD_GENERAL1_SMALL"));
project.put("serviceRole", roleArn);
codeBuild("CreateProject").body(project).post("/").then().statusCode(200);
}
private String buildspec() {
return """
version: 0.2
phases:
install:
commands:
- pip install --quiet --disable-pip-version-check --root-user-action=ignore %s
build:
commands:
- env | sed 's/=.*//' | sort > env-names.txt
- echo "$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" > relative-uri.txt
- wget -S -O credentials.json "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" 2> credentials-headers.txt
- aws sts get-caller-identity --query Arn --output text > caller.txt
- aws configure set default.s3.addressing_style path
- aws s3api list-objects-v2 --bucket %s > /dev/null && echo "granted listed" > granted.txt
- if aws s3api list-objects-v2 --bucket %s > other.txt 2>&1; then echo "other listed" >> other.txt; fi
artifacts:
files:
- '*.txt'
- credentials.json
""".formatted(AWS_CLI, grantedBucket, otherBucket);
}
private String startBuild() {
return codeBuild("StartBuild").body(Map.of("projectName", projectName)).post("/")
.then().statusCode(200).extract().jsonPath().getString("build.id");
}
private JsonPath awaitBuild(String buildId) {
return await("build " + buildId + " complete").atMost(Duration.ofMinutes(8))
.pollInterval(Duration.ofMillis(500))
.until(() -> codeBuild("BatchGetBuilds").body(Map.of("ids", List.of(buildId))).post("/")
.then().statusCode(200).extract().jsonPath().setRootPath("builds[0]"),
build -> build.getBoolean("buildComplete"));
}
/** A CodeBuild call signed as the account's administrator, whom IAM enforcement lets do anything. */
private static RequestSpecification codeBuild(String action) {
return given().header("Authorization", auth(ADMIN, "codebuild"))
.header("X-Amz-Target", "CodeBuild_20161006." + action).contentType(CONTENT_TYPE);
}
private String result(String key) {
try {
return new String(s3Service.getObject(resultsBucket, key).getData(), StandardCharsets.UTF_8);
} catch (RuntimeException e) {
throw new AssertionError("the build left no " + key + " in " + resultsBucket, e);
}
}
private String resultIfAny(String key) {
try {
return result(key).strip();
} catch (AssertionError e) {
return "none left";
}
}
/**
* Polls the credentials server from Floci's side, as the build would through the proxy, at the
* port the running app has, not the one this class picked: the test profile's class is
* initialised again in the app's class loader, where its pick differs. The runner revokes the
* session after it has reported the build complete, hence the window.
*/
private void awaitAnswersNothing(String relativeUri, Duration window) {
HttpClient client = HttpClient.newHttpClient();
int port = config.services().ecs().taskRoleCredentials().port();
HttpRequest request = HttpRequest.newBuilder(
URI.create("http://127.0.0.1:" + port + relativeUri)).GET().build();
await("the build's relative URI answers 404").atMost(window).pollInterval(Duration.ofMillis(200))
.until(() -> client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode() == 404);
}
private static <T> List<T> iterableToList(Iterator<T> iterator) {
ArrayList<T> list = new ArrayList<>();
iterator.forEachRemaining(list::add);
return list;
}
public static final class Profile implements QuarkusTestProfile {
static final String NETWORK = "floci-codebuild-service-role-test";
/** Two distinct ports, picked together so neither pick can repeat the other. */
private static final int[] PORTS = freePorts(2);
static final int CREDENTIALS_PORT = PORTS[0];
static final int PORT = PORTS[1];
static boolean userDefined(String network) {
return !Set.of("bridge", "default", "host", "none").contains(network);
}
private static int[] freePorts(int count) {
try {
return FreePorts.anyInterfacePorts(count);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public Map<String, String> getConfigOverrides() {
Map<String, String> overrides = new HashMap<>(Map.of(
"floci.services.iam.enforcement-enabled", "true",
"floci.services.ecs.task-role-credentials.port", String.valueOf(CREDENTIALS_PORT),
"quarkus.http.test-port", String.valueOf(PORT),
"floci.port", String.valueOf(PORT),
"floci.base-url", "http://localhost:" + PORT));
// Floci in a container puts a build on its own network; on the host, on the test's.
if (!new ContainerDetector().isRunningInContainer()) {
overrides.put("floci.services.codebuild.docker-network", NETWORK);
}
return overrides;
}
}
}
@@ -33,7 +33,7 @@ class CodeBuildSourceCopyTest {
uploads.consumedBytes = 8;
uploads.failure = new RuntimeException(new IOException("Broken pipe"));
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0);
assertEquals(2, uploads.commands.size());
@@ -58,7 +58,7 @@ class CodeBuildSourceCopyTest {
uploads.failure = new RuntimeException(new IOException("Broken pipe"));
RuntimeException failure = assertThrows(RuntimeException.class, () ->
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0));
assertEquals(6, uploads.commands.size());
@@ -74,7 +74,7 @@ class CodeBuildSourceCopyTest {
uploads.failure = new IllegalStateException("No such container");
RuntimeException failure = assertThrows(RuntimeException.class, () ->
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0));
assertTrue(failure.getMessage().contains("No such container"));
@@ -85,7 +85,7 @@ class CodeBuildSourceCopyTest {
void skipsEmptyWorkspace(@TempDir Path workspace) {
DockerClient docker = mock(DockerClient.class);
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src");
verifyNoInteractions(docker);
@@ -93,6 +93,8 @@ class EcsContainerManagerSharedTaskNetworkTest {
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of(NETWORK));
lifecycleManager = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -32,6 +32,8 @@ 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.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
@@ -73,6 +75,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of(NETWORK));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -188,6 +192,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void revokesCredentialsEvenWhenAContainerCouldNotBeRemoved() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
@@ -233,6 +239,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void keepsAddressesReservedWhenAContainerCouldNotBeRemoved() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
@@ -257,6 +265,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void keepsAddressesReservedWhenCleanupCannotRemoveAContainer() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -284,6 +294,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void keepsAddressesReservedWhenAFailedLaunchCannotRemoveAContainer() {
ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(failing.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(failing.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
// The first container starts and the second does not, so the launch unwinds with one
@@ -361,6 +373,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void revokesCredentialsWhenTheLaunchFailsPartWayThrough() {
ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(failing.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(failing.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(failing.createAndStartEphemeral(any(), any())).thenThrow(new IllegalStateException("no daemon"));
@@ -47,6 +47,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
@@ -259,6 +260,8 @@ class EcsContainerManagerVolumesTest {
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
// Its confirmed removal goes through the strict removal each test stubs.
when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod();
when(lifecycleManager.removeVolume(anyString())).thenReturn(true);
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
@@ -8,9 +8,11 @@ import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
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;
@@ -18,12 +20,15 @@ import java.net.http.HttpResponse;
import java.time.Duration;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -108,6 +113,34 @@ class EcsTaskRoleCredentialsServerIntegrationTest {
}
}
@Test
void aBindThatFailsLeavesTheNextStartToBindAgain() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
int port = FreePorts.anyInterfacePort();
when(config.services().ecs().taskRoleCredentials().port()).thenReturn(port);
Vertx vertx = Vertx.vertx();
EcsTaskRoleCredentialsServer server =
new EcsTaskRoleCredentialsServer(vertx, config, mock(EcsTaskRoleCredentials.class));
try (HttpClient client = HttpClient.newHttpClient()) {
try (ServerSocket taken = new ServerSocket(port)) {
ExecutionException refused = assertThrows(ExecutionException.class,
() -> server.start().get(10, TimeUnit.SECONDS));
assertTrue(refused.getCause().getMessage().contains("in use"), refused.getCause().toString());
assertFalse(server.isRunning(), "a failed bind counts as no server");
assertTrue(taken.isBound());
}
server.start().get(10, TimeUnit.SECONDS);
assertTrue(server.isRunning());
assertEquals(404, get(client, "http://127.0.0.1:" + port + "/v2/credentials/" + UUID.randomUUID())
.statusCode());
} finally {
server.stop();
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
}
}
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,129 @@
package io.floci.aws.services.iam;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.codebuild.CodeBuildRoleCredentials;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A build's session against a real {@link IamService}, as {@code EcsTaskRoleCredentialsTest} reads
* a task's: the caller STS answers for it, and what its end leaves.
*/
class CodeBuildRoleCredentialsTest {
private static final String ACCOUNT = "000000000000";
private static final String BUILD_ARN = "arn:aws:codebuild:us-east-1:" + ACCOUNT + ":build/project:7";
private static final String RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
private IamService iamService;
private EcsTaskRoleCredentials sessions;
private EcsCredentialsProxy proxy;
private CodeBuildRoleCredentials credentials;
private String roleArn;
@BeforeEach
void setUp() {
Clock clock = mock(Clock.class);
when(clock.instant()).thenReturn(Instant.now());
iamService = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new RegionResolver("us-east-1", ACCOUNT), false, clock);
roleArn = iamService.createRole("build-role", "/service-role/", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"codebuild.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""", null, 3600, null).getArn();
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L);
sessions = new EcsTaskRoleCredentials(iamService, config);
EcsTaskRoleCredentialsServer server = mock(EcsTaskRoleCredentialsServer.class);
when(server.start()).thenReturn(CompletableFuture.completedFuture(null));
proxy = mock(EcsCredentialsProxy.class);
credentials = new CodeBuildRoleCredentials(sessions, server, proxy, new EcsTaskLinkLocalAddresses());
}
@Test
void theBuildsCallerIsItsRolesCodeBuildSession() {
CodeBuildRoleCredentials.BuildCredentials handed =
credentials.provision(BUILD_ARN, "project:7", roleArn, ACCOUNT, Optional.of("builds"));
String path = handed.env().get(RELATIVE_URI);
String accessKeyId = sessions.resolveByPath(path, Instant.now()).orElseThrow().getAccessKeyId();
assertEquals(Optional.of("arn:aws:sts::" + ACCOUNT + ":assumed-role/build-role/AWSCodeBuild-7"),
iamService.resolveCallerArn(accessKeyId));
assertTrue(handed.linkLocalAddress().startsWith("169.254."), handed.linkLocalAddress());
verify(proxy).ensureProxyOn("builds");
}
@Test
void theBuildsEndRevokesItsSession() {
CodeBuildRoleCredentials.BuildCredentials handed =
credentials.provision(BUILD_ARN, "project:7", roleArn, ACCOUNT, Optional.of("builds"));
String path = handed.env().get(RELATIVE_URI);
String accessKeyId = sessions.resolveByPath(path, Instant.now()).orElseThrow().getAccessKeyId();
credentials.revoke(BUILD_ARN);
assertTrue(sessions.resolveByPath(path, Instant.now()).isEmpty());
assertTrue(iamService.resolveCallerArn(accessKeyId).isEmpty());
}
@Test
void onTheDefaultBridgeTheSessionIsHandedAsKeysAndNoEndpointIsReadied() {
CodeBuildRoleCredentials.BuildCredentials handed =
credentials.provision(BUILD_ARN, "project:7", roleArn, ACCOUNT, Optional.of("bridge"));
assertEquals(Optional.of("arn:aws:sts::" + ACCOUNT + ":assumed-role/build-role/AWSCodeBuild-7"),
iamService.resolveCallerArn(handed.env().get("AWS_ACCESS_KEY_ID")));
assertEquals(null, handed.linkLocalAddress());
verify(proxy, never()).ensureProxyOn("bridge");
}
@Test
void aRoleNotFoundMintsNothing() {
String missing = "arn:aws:iam::" + ACCOUNT + ":role/missing";
CodeBuildRoleCredentials.RoleNotFoundException refused = assertThrows(
CodeBuildRoleCredentials.RoleNotFoundException.class,
() -> credentials.provision(BUILD_ARN, "project:7", missing, ACCOUNT, Optional.of("builds")));
assertEquals("CodeBuild is not authorized to perform: sts:AssumeRole on " + missing, refused.getMessage());
verify(proxy, never()).ensureProxyOn("builds");
}
@Test
void anEndpointThatCannotBeServedOnTheNetworkHandsTheSessionAsKeys() {
doThrow(new IllegalStateException("the runtime does not honour link-local addresses"))
.when(proxy).ensureProxyOn("builds");
CodeBuildRoleCredentials.BuildCredentials handed =
credentials.provision(BUILD_ARN, "project:7", roleArn, ACCOUNT, Optional.of("builds"));
assertEquals(Optional.of("arn:aws:sts::" + ACCOUNT + ":assumed-role/build-role/AWSCodeBuild-7"),
iamService.resolveCallerArn(handed.env().get("AWS_ACCESS_KEY_ID")));
assertNull(handed.env().get(RELATIVE_URI));
assertNull(handed.linkLocalAddress());
}
}