diff --git a/docs/services/ecs.md b/docs/services/ecs.md index 0ca3eb5f7d..c222118a11 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -899,6 +899,11 @@ them: Floci writes `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` into every container in the task, pointing at one `/v2/credentials/{id}` path per task, and the AWS SDKs pick it up with no code change. +The published path stays the same when credentials renew, including when a task first reads it +after the previous credentials expire. Reads near expiry return a fresh session. Credentials +already cached by another client remain valid until their original expiry; stopping the task +revokes every generation. A deleted or recreated task role invalidates the endpoint. + **A user-defined Docker network is required.** Set `FLOCI_SERVICES_ECS_DOCKER_NETWORK` to a network you created; the default bridge will not work. The SDKs hardcode `169.254.170.2` for this endpoint, so Floci runs a small proxy container that holds that address on the task's network and forwards to diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java index f5b4f47437..e42cc40fec 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java @@ -10,8 +10,11 @@ import jakarta.inject.Inject; import java.security.SecureRandom; import java.time.Instant; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -55,20 +58,36 @@ public class EcsTaskRoleCredentials { * created the task by the time containers are started. */ public synchronized Optional issue(String taskArn, String roleArn, String accountId, Instant now) { + Issued current = taskArn == null ? null : byTaskArn.get(taskArn); + 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()) { return Optional.empty(); } - Issued current = byTaskArn.get(taskArn); - if (current != null && current.session.getRoleArn().equals(roleArn) - && current.session.getExpiration().isAfter(now.plusSeconds(ROTATE_WITHIN_SECONDS))) { - return Optional.of(current.path); - } - Optional role = resolveRole(roleArn, accountId); - if (role.isEmpty()) { + if (role.isEmpty() || (current != null && !Objects.equals(current.roleId, role.get().getRoleId()))) { + if (current != null) { + revoke(current); + } return Optional.empty(); } + if (current != null) { + current.previous.removeIf(session -> { + if (!session.getExpiration().isAfter(now)) { + iamService.unregisterSession(accountId, session.getAccessKeyId()); + return true; + } + return false; + }); + long rotationWindow = Math.min(ROTATE_WITHIN_SECONDS, ttlSeconds / 10); + if (current.session.getExpiration().isAfter(now.plusSeconds(rotationWindow))) { + return Optional.of(current.path); + } + } SessionCredential session = new SessionCredential( "ASIA" + random(UPPER_ALPHANUMERIC, 16), randomBase64(30), randomBase64(48), @@ -81,14 +100,18 @@ public class EcsTaskRoleCredentials { } iamService.registerEcsTaskRoleSession(session); - String path = "/v2/credentials/" + UUID.randomUUID(); - Issued issued = new Issued(session, path); + String path = current == null ? "/v2/credentials/" + UUID.randomUUID() : current.path; + List previous = current == null ? new ArrayList<>() : current.previous; + if (current != null) { + if (current.session.getExpiration().isAfter(now)) { + previous.add(current.session); + } else { + iamService.unregisterSession(accountId, current.session.getAccessKeyId()); + } + } + Issued issued = new Issued(session, path, role.get().getRoleId(), previous); byPath.put(path, issued); byTaskArn.put(taskArn, issued); - if (current != null) { - byPath.remove(current.path, current); - iamService.unregisterSession(accountId, current.session.getAccessKeyId()); - } return Optional.of(path); } @@ -98,11 +121,8 @@ public class EcsTaskRoleCredentials { if (issued == null) { return Optional.empty(); } - if (!issued.session.getExpiration().isAfter(now)) { - revoke(issued); - return Optional.empty(); - } - return Optional.of(issued.session); + return issue(issued.session.getEcsTaskArn(), issued.session.getRoleArn(), + issued.session.getOriginAccountId(), now).map(renewedPath -> byPath.get(renewedPath).session); } /** Revokes the task's credentials on task stop, exit, or a launch that failed part way through. */ @@ -117,6 +137,9 @@ public class EcsTaskRoleCredentials { byTaskArn.remove(issued.session.getEcsTaskArn(), issued); byPath.remove(issued.path, issued); iamService.unregisterSession(issued.session.getOriginAccountId(), issued.session.getAccessKeyId()); + for (SessionCredential previous : issued.previous) { + iamService.unregisterSession(previous.getOriginAccountId(), previous.getAccessKeyId()); + } } private Optional resolveRole(String roleArn, String accountId) { @@ -126,7 +149,8 @@ public class EcsTaskRoleCredentials { } catch (IllegalArgumentException e) { return Optional.empty(); } - if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) { + if (!"iam".equals(parsed.service()) || !parsed.accountId().equals(accountId) + || !parsed.resource().startsWith("role/")) { return Optional.empty(); } String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1); @@ -150,5 +174,5 @@ public class EcsTaskRoleCredentials { return Base64.getEncoder().encodeToString(bytes); } - private record Issued(SessionCredential session, String path) {} + private record Issued(SessionCredential session, String path, String roleId, List previous) {} } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServer.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServer.java index 4ae30217b7..88212f995c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServer.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServer.java @@ -57,7 +57,7 @@ public class EcsTaskRoleCredentialsServer { int port = config.services().ecs().taskRoleCredentials().port(); Router router = Router.router(vertx); - router.get("/v2/credentials/:id").handler(this::handleCredentials); + router.get("/v2/credentials/:id").blockingHandler(this::handleCredentials); httpServer = vertx.createHttpServer(); httpServer.requestHandler(router).listen(port, result -> { diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServerIntegrationTest.java index 84161f96c4..3062dbdce8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServerIntegrationTest.java @@ -4,10 +4,12 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.testutil.FreePorts; import io.quarkus.test.junit.QuarkusTest; +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.URI; import java.net.http.HttpClient; @@ -17,13 +19,18 @@ import java.time.Duration; import java.time.Instant; import java.util.UUID; 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.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** @@ -38,8 +45,9 @@ class EcsTaskRoleCredentialsServerIntegrationTest { @Inject IamService iam; - @Test - void credentialsEndpointServesAnIssuedSessionAndStopsAfterRevoke() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void credentialsEndpointServesAndRenewsThePublishedPathThenStopsAfterRevoke(boolean expired) throws Exception { String account = "356813579012"; String suffix = UUID.randomUUID().toString().substring(0, 8); String role = "ecs-task-role-" + suffix; @@ -60,25 +68,32 @@ class EcsTaskRoleCredentialsServerIntegrationTest { when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L); Vertx vertx = Vertx.vertx(); - EcsTaskRoleCredentials credentials = new EcsTaskRoleCredentials(iam, config); + EcsTaskRoleCredentials credentials = spy(new EcsTaskRoleCredentials(iam, config)); + AtomicBoolean workerLookup = new AtomicBoolean(); + doAnswer(invocation -> { + workerLookup.set(Context.isOnWorkerThread()); + return invocation.callRealMethod(); + }).when(credentials).resolveByPath(anyString(), any(Instant.class)); EcsTaskRoleCredentialsServer server = new EcsTaskRoleCredentialsServer(vertx, config, credentials); String endpoint = "http://127.0.0.1:" + port; try (HttpClient client = HttpClient.newHttpClient()) { server.start().get(10, TimeUnit.SECONDS); - String path = credentials.issue(taskArn, roleArn, account, Instant.now()).orElseThrow(); + Instant issuedAt = Instant.now().minusSeconds(expired ? 21601 : 0); + String path = credentials.issue(taskArn, roleArn, account, issuedAt).orElseThrow(); assertTrue(path.matches("^/v2/credentials/[0-9a-f-]{36}$"), path); assertEquals(404, get(client, endpoint + "/v2/credentials/" + UUID.randomUUID()).statusCode()); HttpResponse response = get(client, endpoint + path); assertEquals(200, response.statusCode()); + assertTrue(workerLookup.get(), "Credential storage must run on a worker thread"); JsonObject body = new JsonObject(response.body()); assertEquals(roleArn, body.getString("RoleArn")); assertTrue(Instant.parse(body.getString("Expiration")).isAfter(Instant.now())); String key = body.getString("AccessKeyId"); String token = body.getString("Token"); assertTrue(key.startsWith("ASIA")); - assertEquals(body.getString("SecretAccessKey"), iam.findSecretKey(key, token).orElseThrow()); + assertTrue(iam.findSecretKey(key, token).filter(body.getString("SecretAccessKey")::equals).isPresent()); assertEquals(account, iam.resolveAccountId(key).orElseThrow()); credentials.revoke(taskArn); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/EcsTaskRoleCredentialsTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/EcsTaskRoleCredentialsTest.java index d2f47885d8..a5b4ad019a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/EcsTaskRoleCredentialsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/EcsTaskRoleCredentialsTest.java @@ -8,10 +8,12 @@ import io.github.hectorvent.floci.services.iam.model.SessionCredential; 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 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.assertTrue; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; @@ -31,13 +33,17 @@ class EcsTaskRoleCredentialsTest { private IamService iamService; private EcsTaskRoleCredentials credentials; private String roleArn; + private final Clock clock = mock(Clock.class); + private InMemoryStorage sessions; @BeforeEach void setUp() { + when(clock.instant()).thenReturn(Instant.parse("2030-01-01T00:00:00Z")); + sessions = new InMemoryStorage<>(); iamService = new IamService( new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false); + sessions, new RegionResolver("us-east-1", "000000000000"), false, clock); roleArn = iamService.createRole("ecsTaskRole", "/", "{}", null, 3600, null).getArn(); EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); @@ -47,7 +53,7 @@ class EcsTaskRoleCredentialsTest { @Test void issueMintsAResolvableSessionScopedToTheTask() { - Instant now = Instant.now(); + Instant now = clock.instant(); String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); assertTrue(path.matches("^/v2/credentials/[0-9a-f-]{36}$"), path); @@ -64,12 +70,12 @@ class EcsTaskRoleCredentialsTest { @Test void issueForUnknownRoleMintsNothing() { assertTrue(credentials.issue(TASK_ARN, "arn:aws:iam::000000000000:role/does-not-exist", - "000000000000", Instant.now()).isEmpty()); + "000000000000", clock.instant()).isEmpty()); } @Test void reissuingWellBeforeExpiryReturnsTheSamePath() { - Instant now = Instant.now(); + Instant now = clock.instant(); String first = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); String second = credentials.issue(TASK_ARN, roleArn, "000000000000", now.plusSeconds(10)).orElseThrow(); @@ -77,25 +83,26 @@ class EcsTaskRoleCredentialsTest { } @Test - void reissuingInsideTheRotationWindowMintsAFreshGenerationAndRetiresTheOld() { - Instant now = Instant.now(); + void reissuingInsideTheRotationWindowKeepsThePathAndUnexpiredCachedSession() { + Instant now = clock.instant(); String first = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); SessionCredential firstSession = credentials.resolveByPath(first, now).orElseThrow(); // Inside the 300-second rotation window, so a fresh generation is minted. Instant nearExpiry = firstSession.getExpiration().minusSeconds(60); + at(nearExpiry); String second = credentials.issue(TASK_ARN, roleArn, "000000000000", nearExpiry).orElseThrow(); - assertNotEquals(first, second); - assertTrue(credentials.resolveByPath(first, nearExpiry).isEmpty(), "retired generation must stop resolving"); - assertTrue(credentials.resolveByPath(second, nearExpiry).isPresent()); - assertTrue(iamService.findSecretKey(firstSession.getAccessKeyId(), firstSession.getSessionToken()).isEmpty(), - "the retired generation's access key must stop authenticating"); + assertEquals(first, second); + SessionCredential refreshed = credentials.resolveByPath(first, nearExpiry).orElseThrow(); + assertFalse(firstSession.getAccessKeyId().equals(refreshed.getAccessKeyId())); + assertTrue(iamService.findSecretKey(firstSession.getAccessKeyId(), firstSession.getSessionToken()).isPresent()); + assertEquals(now.plusSeconds(21600), firstSession.getExpiration()); } @Test void separateTasksGetIndependentSessions() { - Instant now = Instant.now(); + Instant now = clock.instant(); String taskAPath = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); String taskBPath = credentials.issue(OTHER_TASK_ARN, roleArn, "000000000000", now).orElseThrow(); @@ -110,7 +117,7 @@ class EcsTaskRoleCredentialsTest { @Test void revokeStopsTheAccessKeyFromAuthenticating() { - Instant now = Instant.now(); + Instant now = clock.instant(); String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); SessionCredential session = credentials.resolveByPath(path, now).orElseThrow(); @@ -126,19 +133,161 @@ class EcsTaskRoleCredentialsTest { } @Test - void resolveByPathExpiresAndRevokesOnceThePastExpirationIsSeen() { - Instant now = Instant.now(); + void expiredCredentialsAreRenewedAtThePublishedPath() { + Instant now = clock.instant(); String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential original = credentials.resolveByPath(path, now).orElseThrow(); + Instant later = at(now.plusSeconds(21601)); - Optional pastExpiry = credentials.resolveByPath(path, now.plusSeconds(21601)); + Optional pastExpiry = credentials.resolveByPath(path, later); - assertTrue(pastExpiry.isEmpty()); - assertTrue(credentials.resolveByPath(path, now).isEmpty(), "an expired path must not come back"); + assertTrue(pastExpiry.isPresent()); + assertEquals(later.plusSeconds(21600), pastExpiry.orElseThrow().getExpiration()); + assertTrue(iamService.findSecretKey(original.getAccessKeyId(), original.getSessionToken()).isEmpty()); + assertTrue(sessions.get(original.getAccessKeyId()).isEmpty()); } @Test void resolveByPathForUnknownPathIsEmpty() { - assertTrue(credentials.resolveByPath("/v2/credentials/does-not-exist", Instant.now()).isEmpty()); - assertTrue(credentials.resolveByPath(null, Instant.now()).isEmpty()); + assertTrue(credentials.resolveByPath("/v2/credentials/does-not-exist", clock.instant()).isEmpty()); + assertTrue(credentials.resolveByPath(null, clock.instant()).isEmpty()); + } + + @Test + void endpointReadsRenewBeforeExpiryAndStopRevokesAllLiveGenerations() { + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential first = credentials.resolveByPath(path, now).orElseThrow(); + Instant nearExpiry = at(first.getExpiration().minusSeconds(60)); + SessionCredential second = credentials.resolveByPath(path, nearExpiry).orElseThrow(); + assertFalse(first.getAccessKeyId().equals(second.getAccessKeyId())); + assertTrue(iamService.findSecretKey(first.getAccessKeyId(), first.getSessionToken()).isPresent()); + assertTrue(iamService.findSecretKey(second.getAccessKeyId(), second.getSessionToken()).isPresent()); + credentials.revoke(TASK_ARN); + assertTrue(credentials.resolveByPath(path, nearExpiry).isEmpty()); + assertTrue(iamService.findSecretKey(first.getAccessKeyId(), first.getSessionToken()).isEmpty()); + assertTrue(iamService.findSecretKey(second.getAccessKeyId(), second.getSessionToken()).isEmpty()); + } + + @Test + void successiveRenewalsDiscardExpiredGenerationsWithoutExtendingTheirLifetime() { + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential current = credentials.resolveByPath(path, now).orElseThrow(); + for (int i = 0; i < 3; i++) { + SessionCredential previous = current; + current = credentials.resolveByPath(path, at(previous.getExpiration().minusSeconds(60))).orElseThrow(); + assertFalse(previous.getAccessKeyId().equals(current.getAccessKeyId())); + assertEquals(2, sessions.scan(key -> true).size()); + credentials.resolveByPath(path, at(previous.getExpiration().plusSeconds(1))).orElseThrow(); + assertTrue(iamService.findSecretKey(previous.getAccessKeyId(), previous.getSessionToken()).isEmpty()); + assertTrue(iamService.findSecretKey(current.getAccessKeyId(), current.getSessionToken()).isPresent()); + assertEquals(1, sessions.scan(key -> true).size()); + } + credentials.revoke(TASK_ARN); + assertTrue(sessions.scan(key -> true).isEmpty()); + } + + @Test + void shortTtlDoesNotRotateEveryRead() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(60L); + credentials = new EcsTaskRoleCredentials(iamService, config); + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential first = credentials.resolveByPath(path, now).orElseThrow(); + assertEquals(path, credentials.issue(TASK_ARN, roleArn, "000000000000", at(now.plusSeconds(10))).orElseThrow()); + assertTrue(first.getAccessKeyId().equals( + credentials.resolveByPath(path, clock.instant()).orElseThrow().getAccessKeyId())); + SessionCredential second = credentials.resolveByPath(path, at(now.plusSeconds(59))).orElseThrow(); + assertFalse(first.getAccessKeyId().equals(second.getAccessKeyId())); + assertTrue(iamService.findSecretKey(first.getAccessKeyId(), first.getSessionToken()).isPresent()); + assertTrue(second.getAccessKeyId().equals( + credentials.resolveByPath(path, at(now.plusSeconds(61))).orElseThrow().getAccessKeyId())); + assertTrue(iamService.findSecretKey(first.getAccessKeyId(), first.getSessionToken()).isEmpty()); + } + + @Test + void oneSecondTtlReusesTheSessionUntilItExpires() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(1L); + credentials = new EcsTaskRoleCredentials(iamService, config); + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential first = sessions.scan(key -> true).getFirst(); + for (int i = 0; i < 10; i++) { + SessionCredential current = credentials.resolveByPath(path, at(now.plusMillis(i * 90))).orElseThrow(); + assertTrue(first.getAccessKeyId().equals(current.getAccessKeyId())); + assertEquals(1, sessions.scan(key -> true).size()); + } + SessionCredential renewed = credentials.resolveByPath(path, at(now.plusSeconds(1))).orElseThrow(); + assertFalse(first.getAccessKeyId().equals(renewed.getAccessKeyId())); + assertTrue(iamService.findSecretKey(first.getAccessKeyId(), first.getSessionToken()).isEmpty()); + assertEquals(1, sessions.scan(key -> true).size()); + } + + @Test + void deletingTheRoleRevokesThePathAndEveryCachedGeneration() { + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential first = credentials.resolveByPath(path, now).orElseThrow(); + credentials.issue(TASK_ARN, roleArn, "000000000000", at(first.getExpiration().minusSeconds(60))).orElseThrow(); + iamService.deleteRole("ecsTaskRole"); + assertTrue(credentials.resolveByPath(path, clock.instant()).isEmpty()); + assertTrue(sessions.scan(key -> true).isEmpty()); + } + + @Test + void recreatingTheRoleCannotRenewAnOldTasksCredentials() { + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + iamService.deleteRole("ecsTaskRole"); + iamService.createRole("ecsTaskRole", "/", "{}", null, 3600, null); + assertTrue(credentials.resolveByPath(path, now).isEmpty()); + assertTrue(sessions.scan(key -> true).isEmpty()); + } + + @Test + void wrongAccountRoleDoesNotMintASession() { + assertTrue(credentials.issue(TASK_ARN, roleArn, "111111111111", clock.instant()).isEmpty()); + assertTrue(sessions.scan(key -> true).isEmpty()); + } + + @Test + void changingToAnUnknownRoleRevokesTheOldAssignment() { + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + assertTrue(credentials.issue(TASK_ARN, "arn:aws:iam::000000000000:role/missing", "000000000000", now).isEmpty()); + assertTrue(credentials.resolveByPath(path, now).isEmpty()); + assertTrue(sessions.scan(key -> true).isEmpty()); + } + + @Test + void changingTheAccountRevokesTheOldAssignment() { + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + assertTrue(credentials.issue(TASK_ARN, roleArn, "111111111111", now).isEmpty()); + assertTrue(credentials.resolveByPath(path, now).isEmpty()); + assertTrue(sessions.scan(key -> true).isEmpty()); + } + + @Test + void changingToAnotherRoleReplacesThePathAndRevokesCachedGenerations() { + Instant now = clock.instant(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential first = credentials.resolveByPath(path, now).orElseThrow(); + Instant nearExpiry = at(first.getExpiration().minusSeconds(60)); + credentials.resolveByPath(path, nearExpiry).orElseThrow(); + String nextRole = iamService.createRole("nextRole", "/", "{}", null, 3600, null).getArn(); + String nextPath = credentials.issue(TASK_ARN, nextRole, "000000000000", nearExpiry).orElseThrow(); + assertNotEquals(path, nextPath); + assertTrue(credentials.resolveByPath(path, nearExpiry).isEmpty()); + assertEquals(nextRole, credentials.resolveByPath(nextPath, nearExpiry).orElseThrow().getRoleArn()); + assertEquals(1, sessions.scan(key -> true).size()); + } + + private Instant at(Instant now) { + when(clock.instant()).thenReturn(now); + return now; } }