diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index acbb20b626..f74086f7f1 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -2011,6 +2011,38 @@ public interface EmulatorConfig { */ @WithDefault("false") boolean allowUnsafeHostVolumes(); + + EcsTaskRoleCredentialsConfig taskRoleCredentials(); + } + + interface EcsTaskRoleCredentialsConfig { + /** + * Opt-in: vends real task-role credentials over the AWS container-credentials wire + * contract. Off by default: reaching it from a task container needs a Docker network the + * task and Floci both have real access to, which the follow-up wiring this feeds into + * establishes; this alone has no way to satisfy it. + */ + @WithDefault("false") + boolean enabled(); + + /** + * Credential lifetime. AWS documents six hours as the default for task-role credentials, + * rotated by the agent well before expiry; kept configurable for tests that want a short + * TTL without waiting on the real one. + */ + @WithDefault("21600") + long ttlSeconds(); + + /** + * Port on the Floci host serving the credentials endpoint itself. Not the address a task + * container talks to: real ECS SDKs hardcode 169.254.170.2, which nothing in Floci's own + * process can bind without also owning that address on the task's Docker network. A + * follow-up piece launches a small proxy container that holds that address and forwards + * to this port, the same way Lambda and ECS containers already reach Floci's other + * endpoints over {@code host.docker.internal}. + */ + @WithDefault("51679") + int port(); } interface ResourceGroupsTaggingServiceConfig { 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 new file mode 100644 index 0000000000..452a5f32a8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java @@ -0,0 +1,149 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.model.IamRole; +import io.github.hectorvent.floci.services.iam.model.SessionCredential; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.security.SecureRandom; +import java.time.Instant; +import java.util.Base64; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Mints, rotates, and revokes the IAM sessions vended through the ECS task-role credential + * endpoint. Modeled on {@code Ec2InstanceCredentials}: unlike a persisted STS session, a task + * credential is owned by one exact task and cannot outlive it or a Floci restart. + */ +@ApplicationScoped +public class EcsTaskRoleCredentials { + + private static final String UPPER_ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + /** + * A session is rotated once less than this much of its lifetime remains, so an in-flight SDK + * request never races a credential that expires mid-call. AWS rotates task credentials well + * ahead of their advertised expiry for the same reason. + */ + private static final long ROTATE_WITHIN_SECONDS = 300; + + private final IamService iamService; + private final long ttlSeconds; + + /** taskArn -> the task's current issued session and the relative URI it was published at. */ + private final Map byTaskArn = new ConcurrentHashMap<>(); + /** relative URI path -> the session it resolves to, for the credentials endpoint's lookup. */ + private final Map byPath = new ConcurrentHashMap<>(); + + @Inject + public EcsTaskRoleCredentials(IamService iamService, EmulatorConfig config) { + this.iamService = iamService; + this.ttlSeconds = config.services().ecs().taskRoleCredentials().ttlSeconds(); + } + + /** + * Issues a session for the task's role, or returns its current one if it has not entered its + * rotation window. Returns empty, minting nothing, for a role that does not exist under the + * task's account: real ECS would fail the task launch outright on an unassumable role, but + * this provider fails closed on the credential surface instead, since RunTask has already + * created the task by the time containers are started. + */ + public synchronized Optional issue(String taskArn, String roleArn, String accountId, Instant now) { + if (taskArn == null || taskArn.isBlank() || roleArn == null || roleArn.isBlank() + || accountId == null || accountId.isBlank()) { + return Optional.empty(); + } + Issued current = byTaskArn.get(taskArn); + if (current != null && current.session.getRoleArn().equals(roleArn) + && current.session.getExpiration().isAfter(now.plusSeconds(ROTATE_WITHIN_SECONDS))) { + return Optional.of(current.path); + } + + Optional role = resolveRole(roleArn, accountId); + if (role.isEmpty()) { + return Optional.empty(); + } + + SessionCredential session = new SessionCredential( + "ASIA" + random(UPPER_ALPHANUMERIC, 16), randomBase64(30), randomBase64(48), + roleArn, now.plusSeconds(ttlSeconds), null, accountId); + session.setEcsTaskArn(taskArn); + iamService.registerEcsTaskRoleSession(session); + + String path = "/v2/credentials/" + UUID.randomUUID(); + Issued issued = new Issued(session, path); + byPath.put(path, issued); + byTaskArn.put(taskArn, issued); + if (current != null) { + byPath.remove(current.path, current); + iamService.unregisterSession(accountId, current.session.getAccessKeyId()); + } + return Optional.of(path); + } + + /** Resolves the active session addressed by its relative URI path, for the endpoint handler. */ + public synchronized Optional resolveByPath(String path, Instant now) { + Issued issued = path == null ? null : byPath.get(path); + if (issued == null) { + return Optional.empty(); + } + if (!issued.session.getExpiration().isAfter(now)) { + revoke(issued); + return Optional.empty(); + } + return Optional.of(issued.session); + } + + /** Revokes the task's credentials on task stop, exit, or a launch that failed part way through. */ + public synchronized void revoke(String taskArn) { + Issued issued = taskArn == null ? null : byTaskArn.get(taskArn); + if (issued != null) { + revoke(issued); + } + } + + private void revoke(Issued issued) { + byTaskArn.remove(issued.session.getEcsTaskArn(), issued); + byPath.remove(issued.path, issued); + iamService.unregisterSession(issued.session.getOriginAccountId(), issued.session.getAccessKeyId()); + } + + private Optional resolveRole(String roleArn, String accountId) { + AwsArnUtils.Arn parsed; + try { + parsed = AwsArnUtils.parse(roleArn); + } catch (IllegalArgumentException e) { + return Optional.empty(); + } + if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) { + return Optional.empty(); + } + String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1); + if (roleName.isBlank()) { + return Optional.empty(); + } + return iamService.findRole(accountId, roleName).filter(role -> roleArn.equals(role.getArn())); + } + + private static String random(String characters, int length) { + StringBuilder value = new StringBuilder(length); + for (int i = 0; i < length; i++) { + value.append(characters.charAt(SECURE_RANDOM.nextInt(characters.length()))); + } + return value.toString(); + } + + private static String randomBase64(int byteLength) { + byte[] bytes = new byte[byteLength]; + SECURE_RANDOM.nextBytes(bytes); + return Base64.getEncoder().encodeToString(bytes); + } + + private record Issued(SessionCredential session, String path) {} +} 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 new file mode 100644 index 0000000000..ac4b0c799d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServer.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.iam.model.SessionCredential; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** + * Serves the AWS container-credentials wire contract that + * {@code AWS_CONTAINER_CREDENTIALS_RELATIVE_URI} points at: {@code GET /v2/credentials/} + * returning {@code RoleArn}/{@code AccessKeyId}/{@code SecretAccessKey}/{@code Token}/ + * {@code Expiration}. + * + *

Bound to a normal Floci-host port, not to 169.254.170.2: the AWS SDK hardcodes that address + * (it is not configurable, unlike EC2's {@code AWS_EC2_METADATA_SERVICE_ENDPOINT}), and nothing in + * Floci's own process can bind an address it does not otherwise own on a task's Docker network. + * A follow-up piece is what actually holds 169.254.170.2, one small proxy container per ECS + * network, forwarding here over {@code host.docker.internal}. + */ +@ApplicationScoped +public class EcsTaskRoleCredentialsServer { + + private static final Logger LOG = Logger.getLogger(EcsTaskRoleCredentialsServer.class); + private static final DateTimeFormatter ISO = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") + .withZone(ZoneOffset.UTC); + + private final Vertx vertx; + private final EmulatorConfig config; + private final EcsTaskRoleCredentials credentials; + + private volatile HttpServer httpServer; + + @Inject + public EcsTaskRoleCredentialsServer(Vertx vertx, EmulatorConfig config, EcsTaskRoleCredentials credentials) { + this.vertx = vertx; + this.config = config; + this.credentials = credentials; + } + + public synchronized CompletableFuture start() { + if (httpServer != null) { + return CompletableFuture.completedFuture(null); + } + CompletableFuture future = new CompletableFuture<>(); + int port = config.services().ecs().taskRoleCredentials().port(); + + Router router = Router.router(vertx); + router.get("/v2/credentials/:id").handler(this::handleCredentials); + + httpServer = vertx.createHttpServer(); + httpServer.requestHandler(router).listen(port, result -> { + if (result.succeeded()) { + LOG.infof("ECS task-role credentials server listening on port %d", port); + future.complete(null); + } else { + LOG.warnf("ECS task-role credentials server failed to start on port %d: %s", + port, result.cause().getMessage()); + future.completeExceptionally(result.cause()); + } + }); + return future; + } + + public synchronized void stop() { + if (httpServer != null) { + httpServer.close(); + httpServer = null; + } + } + + private void handleCredentials(RoutingContext ctx) { + String path = "/v2/credentials/" + ctx.pathParam("id"); + Optional session = credentials.resolveByPath(path, Instant.now()); + if (session.isEmpty()) { + ctx.response().setStatusCode(404).end(); + return; + } + SessionCredential creds = session.get(); + ctx.response().putHeader("content-type", "application/json").end(new JsonObject() + .put("RoleArn", creds.getRoleArn()) + .put("AccessKeyId", creds.getAccessKeyId()) + .put("SecretAccessKey", creds.getSecretAccessKey()) + .put("Token", creds.getSessionToken()) + .put("Expiration", ISO.format(creds.getExpiration())).encode()); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3025786fa9..d56daeb328 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -106,6 +106,7 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.elb.ElbClassicService - --initialize-at-run-time=io.github.hectorvent.floci.services.datasync.DataSyncService - --initialize-at-run-time=io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials + - --initialize-at-run-time=io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentials - --initialize-at-run-time=io.github.hectorvent.floci.services.ssoportal.SsoPortalService - --initialize-at-run-time=io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator - --initialize-at-run-time=io.github.hectorvent.floci.services.ecs.exec.EcsExecSessionRegistry @@ -562,6 +563,10 @@ floci: publish-awsvpc-ports-to-host: false host-volume-roots: [] allow-unsafe-host-volumes: false + task-role-credentials: + enabled: false + ttl-seconds: 21600 + port: 51679 appconfig: enabled: true appconfigdata: 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 new file mode 100644 index 0000000000..fdba082ad0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentialsServerIntegrationTest.java @@ -0,0 +1,103 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.iam.IamService; +import io.quarkus.test.junit.QuarkusTest; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.net.ServerSocket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +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.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Exercises the real wire contract end to end: a role minted through the running app's IAM API, + * a real Vert.x server bound to a free port, and a plain {@link HttpClient} reading the response + * the way an AWS SDK's {@code ContainerMetadataFetcher} does. Modeled on + * {@code Ec2InstanceCredentialsIntegrationTest}. + */ +@QuarkusTest +class EcsTaskRoleCredentialsServerIntegrationTest { + + @Inject + IamService iam; + + @Test + void credentialsEndpointServesAnIssuedSessionAndStopsAfterRevoke() throws Exception { + String account = "356813579012"; + String suffix = UUID.randomUUID().toString().substring(0, 8); + String role = "ecs-task-role-" + suffix; + String taskArn = "arn:aws:ecs:us-east-1:" + account + ":task/cluster/" + suffix; + String auth = "AWS4-HMAC-SHA256 Credential=" + account + + "/20260916/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc"; + given().header("Authorization", auth).contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateRole").formParam("RoleName", role) + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ecs-tasks.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}") + .post("/").then().statusCode(200); + String roleArn = "arn:aws:iam::" + account + ":role/" + role; + + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + when(config.services().ecs().taskRoleCredentials().port()).thenReturn(port); + when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L); + + Vertx vertx = Vertx.vertx(); + EcsTaskRoleCredentials credentials = new EcsTaskRoleCredentials(iam, config); + 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(); + 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()); + 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()); + assertEquals(account, iam.resolveAccountId(key).orElseThrow()); + + credentials.revoke(taskArn); + assertNotEquals(200, get(client, endpoint + path).statusCode()); + assertTrue(iam.findSecretKey(key, token).isEmpty()); + } finally { + server.stop(); + vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS); + given().header("Authorization", auth).contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteRole").formParam("RoleName", role) + .post("/").then().statusCode(200); + } + } + + private static HttpResponse get(HttpClient client, String url) throws Exception { + return client.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(5)).GET().build(), + HttpResponse.BodyHandlers.ofString()); + } +} 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 new file mode 100644 index 0000000000..d2f47885d8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/EcsTaskRoleCredentialsTest.java @@ -0,0 +1,144 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentials; +import io.github.hectorvent.floci.services.iam.model.SessionCredential; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.Optional; + +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.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Uses a real {@link IamService} backed by in-memory storage, the same way + * {@code IamServiceTest} and {@code Ec2InstanceCredentialsTest} do: the behaviour under test is + * the interaction between the two, not either one in isolation. + */ +class EcsTaskRoleCredentialsTest { + + private static final String TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/cluster/abc123"; + private static final String OTHER_TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/cluster/def456"; + + private IamService iamService; + private EcsTaskRoleCredentials credentials; + private String roleArn; + + @BeforeEach + void setUp() { + iamService = new IamService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false); + roleArn = iamService.createRole("ecsTaskRole", "/", "{}", null, 3600, null).getArn(); + + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L); + credentials = new EcsTaskRoleCredentials(iamService, config); + } + + @Test + void issueMintsAResolvableSessionScopedToTheTask() { + Instant now = Instant.now(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + + assertTrue(path.matches("^/v2/credentials/[0-9a-f-]{36}$"), path); + SessionCredential session = credentials.resolveByPath(path, now).orElseThrow(); + assertEquals(roleArn, session.getRoleArn()); + assertEquals(TASK_ARN, session.getEcsTaskArn()); + assertEquals("000000000000", session.getOriginAccountId()); + assertTrue(session.getAccessKeyId().startsWith("ASIA")); + assertEquals(now.plusSeconds(21600), session.getExpiration()); + // Findable through the normal SigV4 path too, the same way ECS SDKs authenticate with it. + assertTrue(iamService.findSecretKey(session.getAccessKeyId(), session.getSessionToken()).isPresent()); + } + + @Test + void issueForUnknownRoleMintsNothing() { + assertTrue(credentials.issue(TASK_ARN, "arn:aws:iam::000000000000:role/does-not-exist", + "000000000000", Instant.now()).isEmpty()); + } + + @Test + void reissuingWellBeforeExpiryReturnsTheSamePath() { + Instant now = Instant.now(); + String first = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + String second = credentials.issue(TASK_ARN, roleArn, "000000000000", now.plusSeconds(10)).orElseThrow(); + + assertEquals(first, second); + } + + @Test + void reissuingInsideTheRotationWindowMintsAFreshGenerationAndRetiresTheOld() { + Instant now = Instant.now(); + 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); + 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"); + } + + @Test + void separateTasksGetIndependentSessions() { + Instant now = Instant.now(); + String taskAPath = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + String taskBPath = credentials.issue(OTHER_TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + + assertNotEquals(taskAPath, taskBPath); + assertEquals(TASK_ARN, credentials.resolveByPath(taskAPath, now).orElseThrow().getEcsTaskArn()); + assertEquals(OTHER_TASK_ARN, credentials.resolveByPath(taskBPath, now).orElseThrow().getEcsTaskArn()); + + credentials.revoke(TASK_ARN); + assertTrue(credentials.resolveByPath(taskAPath, now).isEmpty()); + assertTrue(credentials.resolveByPath(taskBPath, now).isPresent(), "revoking one task must not touch another"); + } + + @Test + void revokeStopsTheAccessKeyFromAuthenticating() { + Instant now = Instant.now(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + SessionCredential session = credentials.resolveByPath(path, now).orElseThrow(); + + credentials.revoke(TASK_ARN); + + assertTrue(credentials.resolveByPath(path, now).isEmpty()); + assertTrue(iamService.findSecretKey(session.getAccessKeyId(), session.getSessionToken()).isEmpty()); + } + + @Test + void revokingAnUnknownTaskIsANoOp() { + credentials.revoke("arn:aws:ecs:us-east-1:000000000000:task/cluster/never-issued"); + } + + @Test + void resolveByPathExpiresAndRevokesOnceThePastExpirationIsSeen() { + Instant now = Instant.now(); + String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow(); + + Optional pastExpiry = credentials.resolveByPath(path, now.plusSeconds(21601)); + + assertTrue(pastExpiry.isEmpty()); + assertTrue(credentials.resolveByPath(path, now).isEmpty(), "an expired path must not come back"); + } + + @Test + void resolveByPathForUnknownPathIsEmpty() { + assertTrue(credentials.resolveByPath("/v2/credentials/does-not-exist", Instant.now()).isEmpty()); + assertTrue(credentials.resolveByPath(null, Instant.now()).isEmpty()); + } +}