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

@@ -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());
}
}