diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CredentialRetirementStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CredentialRetirementStorageTest.java new file mode 100644 index 0000000000..263f6bdcd7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CredentialRetirementStorageTest.java @@ -0,0 +1,227 @@ +package io.github.hectorvent.floci.services.ec2; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.model.SessionCredential; +import io.github.hectorvent.floci.testing.StorageFactories; +import io.vertx.core.json.JsonObject; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +class Ec2CredentialRetirementStorageTest { + private static final String ACCOUNT = "000000000000"; + private static final String OTHER_ACCOUNT = "111122223333"; + private static final Instant NOW = Instant.parse("2030-01-01T00:00:00Z"); + + @TempDir + Path directory; + + @ParameterizedTest + @CsvSource({"false,1", "false,2", "false,3", "false,4", "true,1", "true,2", "true,3", "true,4"}) + void snapshotFailureDoesNotInterruptRetirementOfAllGenerations(boolean clear, int failedDeletion) throws Exception { + EmulatorConfig config = StorageFactories.config(directory, ACCOUNT); + StorageFactory factory = StorageFactories.open(config, "persistent"); + Path obstruction = directory.resolve("iam-sessions.json.tmp"); + Path snapshot = directory.resolve("iam-sessions.json"); + List issued = new ArrayList<>(); + SessionCredential other; + try { + IamService iam = spy(new IamService(factory, config, + new RegionResolver("us-east-1", ACCOUNT), Clock.fixed(NOW, ZoneOffset.UTC))); + iam.createRole("worker", "/", "{}", null, 3600, null); + String profile = iam.createInstanceProfile("profile", "/").getArn(); + iam.addRoleToInstanceProfile("profile", "worker"); + Ec2InstanceCredentials credentials = new Ec2InstanceCredentials(iam); + Instance instance = instance("i-retiring"); + instance.setIamInstanceProfileArn(profile); + credentials.register(instance); + issued.add(credentials.get(instance, "worker", NOW).orElseThrow()); + issued.add(credentials.get(instance, "worker", NOW.plusSeconds(3300)).orElseThrow()); + issued.add(credentials.identity(instance, ACCOUNT, NOW).orElseThrow()); + issued.add(credentials.identity(instance, ACCOUNT, NOW.plusSeconds(3300)).orElseThrow()); + Ec2InstanceCredentials unrelated = clear ? new Ec2InstanceCredentials(iam) : credentials; + Instance otherInstance = instance("i-unrelated"); + unrelated.register(otherInstance); + other = unrelated.identity(otherInstance, OTHER_ACCOUNT, NOW).orElseThrow(); + AtomicInteger deletions = new AtomicInteger(); + AtomicReference beforeFailure = new AtomicReference<>(); + doAnswer(invocation -> { + if (deletions.incrementAndGet() == failedDeletion) { + beforeFailure.set(Files.readAllBytes(snapshot)); + Files.createDirectory(obstruction); + } + return invocation.callRealMethod(); + }).when(iam).unregisterSession(anyString(), anyString()); + + assertDoesNotThrow(() -> retire(credentials, instance, clear)); + assertArrayEquals(beforeFailure.get(), Files.readAllBytes(snapshot)); + assertTrue(iam.findSecretKey(issued.get(failedDeletion - 1).getAccessKeyId(), + issued.get(failedDeletion - 1).getSessionToken()).isEmpty()); + assertAll( + () -> assertTrue(credentials.get(instance, "worker", NOW).isEmpty()), + () -> assertTrue(credentials.identity(instance, ACCOUNT, NOW).isEmpty()), + () -> assertTrue(credentials.role(instance).isEmpty()), + () -> assertTrue(credentials.profile(instance).isEmpty()), + () -> { + Files.delete(obstruction); + factory.flushAll(); + List persisted = new ObjectMapper().readTree(Files.readAllBytes(snapshot)) + .findValuesAsText("accessKeyId"); + for (SessionCredential session : issued) { + assertFalse(persisted.contains(session.getAccessKeyId())); + assertTrue(iam.findSecretKey(session.getAccessKeyId(), session.getSessionToken()).isEmpty()); + } + assertSame(other, unrelated.identity(otherInstance, OTHER_ACCOUNT, NOW).orElseThrow()); + }); + } finally { + Files.deleteIfExists(obstruction); + factory.shutdownAll(); + } + StorageFactory reopened = StorageFactories.open(config, "persistent"); + try { + AccountAwareStorageBackend sessions = reopened.create( + "iam", "iam-sessions.json", new TypeReference<>() {}); + for (SessionCredential session : issued) { + assertTrue(sessions.getForAccount(ACCOUNT, session.getAccessKeyId()).isEmpty()); + } + assertTrue(sessions.getForAccount(OTHER_ACCOUNT, other.getAccessKeyId()).isPresent()); + } finally { + reopened.shutdownAll(); + } + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void imdsUnregisterCompletesDespiteSnapshotFailure(int failedDeletion) throws Exception { + EmulatorConfig config = StorageFactories.config(directory, ACCOUNT); + StorageFactory factory = StorageFactories.open(config, "persistent"); + Path obstruction = directory.resolve("iam-sessions.json.tmp"); + try { + IamService iam = spy(new IamService(factory, config, + new RegionResolver("us-east-1", ACCOUNT), Clock.systemUTC())); + iam.createRole("worker", "/", "{}", null, 3600, null); + String profile = iam.createInstanceProfile("profile", "/").getArn(); + iam.addRoleToInstanceProfile("profile", "worker"); + Instance instance = instance("i-imds-retirement"); + instance.setIamInstanceProfileArn(profile); + try (Ec2MetadataTestFixture fixture = new Ec2MetadataTestFixture()) { + fixture.start(iam, config, instance); + try { + HttpResponse tokenResponse = fixture.putToken("60"); + assertEquals(200, tokenResponse.statusCode()); + String token = tokenResponse.body(); + String profilePath = "/latest/meta-data/iam/security-credentials/worker"; + String identityPath = "/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance"; + HttpResponse profileResponse = fixture.get(profilePath, token); + HttpResponse identityResponse = fixture.get(identityPath, token); + assertEquals(200, profileResponse.statusCode()); + assertEquals(200, identityResponse.statusCode()); + List issued = List.of(new JsonObject(profileResponse.body()), + new JsonObject(identityResponse.body())); + AtomicInteger deletions = new AtomicInteger(); + doAnswer(invocation -> { + if (deletions.incrementAndGet() == failedDeletion) { + Files.createDirectory(obstruction); + } + return invocation.callRealMethod(); + }).when(iam).unregisterSession(anyString(), anyString()); + assertDoesNotThrow(() -> fixture.server().unregisterInstance(instance)); + assertTrue(fixture.server().registeredContainer(Ec2MetadataTestFixture.CALLER_IP).isEmpty()); + assertEquals(404, fixture.get(profilePath, token).statusCode()); + assertEquals(404, fixture.get(identityPath, token).statusCode()); + JsonObject remaining = issued.get(failedDeletion - 1); + assertTrue(iam.findSecretKey(remaining.getString("AccessKeyId"), remaining.getString("Token")).isEmpty()); + Files.delete(obstruction); + factory.flushAll(); + assertTrue(fixture.server().registeredContainer(Ec2MetadataTestFixture.CALLER_IP).isEmpty()); + assertEquals(404, fixture.get(profilePath, token).statusCode()); + for (JsonObject session : issued) { + assertTrue(iam.findSecretKey(session.getString("AccessKeyId"), session.getString("Token")).isEmpty()); + } + } finally { + Files.deleteIfExists(obstruction); + } + } + } finally { + Files.deleteIfExists(obstruction); + factory.shutdownAll(); + } + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void clearRevokesEveryInstanceDespiteSnapshotFailure(int failedDeletion) throws Exception { + EmulatorConfig config = StorageFactories.config(directory, ACCOUNT); + StorageFactory factory = StorageFactories.open(config, "persistent"); + Path obstruction = directory.resolve("iam-sessions.json.tmp"); + try { + IamService iam = spy(new IamService(factory, config, + new RegionResolver("us-east-1", ACCOUNT), Clock.fixed(NOW, ZoneOffset.UTC))); + Ec2InstanceCredentials credentials = new Ec2InstanceCredentials(iam); + Instance first = instance("i-first"); + Instance second = instance("i-second"); + credentials.register(first); + credentials.register(second); + SessionCredential firstSession = credentials.identity(first, ACCOUNT, NOW).orElseThrow(); + SessionCredential secondSession = credentials.identity(second, OTHER_ACCOUNT, NOW).orElseThrow(); + AtomicInteger deletions = new AtomicInteger(); + doAnswer(invocation -> { + if (deletions.incrementAndGet() == failedDeletion) { + Files.createDirectory(obstruction); + } + return invocation.callRealMethod(); + }).when(iam).unregisterSession(anyString(), anyString()); + assertDoesNotThrow(credentials::clear); + assertAll( + () -> assertTrue(credentials.identity(first, ACCOUNT, NOW).isEmpty()), + () -> assertTrue(credentials.identity(second, OTHER_ACCOUNT, NOW).isEmpty()), + () -> { + Files.delete(obstruction); + factory.flushAll(); + assertTrue(iam.findSecretKey(firstSession.getAccessKeyId(), firstSession.getSessionToken()).isEmpty()); + assertTrue(iam.findSecretKey(secondSession.getAccessKeyId(), secondSession.getSessionToken()).isEmpty()); + }); + } finally { + Files.deleteIfExists(obstruction); + factory.shutdownAll(); + } + } + + private static void retire(Ec2InstanceCredentials credentials, Instance instance, boolean clear) { + if (clear) { + credentials.clear(); + } else { + credentials.unregister(instance); + } + } + + private static Instance instance(String id) { + Instance instance = new Instance(); + instance.setInstanceId(id); + instance.setRegion("us-east-1"); + return instance; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamSessionRetirementStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamSessionRetirementStorageTest.java new file mode 100644 index 0000000000..f49cba73b6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamSessionRetirementStorageTest.java @@ -0,0 +1,167 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentials; +import io.github.hectorvent.floci.services.iam.model.SessionCredential; +import io.github.hectorvent.floci.testing.StorageFactories; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class IamSessionRetirementStorageTest { + + private static final String DEFAULT_ACCOUNT = "000000000000"; + private static final String OTHER_ACCOUNT = "111122223333"; + private static final String ACCESS_KEY = "ASIARETIREMENTFIXTURE"; + + @TempDir + Path directory; + + @ParameterizedTest + @ValueSource(strings = {"memory", "persistent", "hybrid", "wal"}) + void retirementPreservesOtherAccountAndSurvivesReload(String mode) { + EmulatorConfig config = StorageFactories.config(directory, DEFAULT_ACCOUNT); + StorageFactory factory = StorageFactories.open(config, mode); + try { + IamService iam = new IamService(factory, config, + new RegionResolver("us-east-1", DEFAULT_ACCOUNT), Clock.systemUTC()); + AccountAwareStorageBackend sessions = factory.create( + "iam", "iam-sessions.json", new TypeReference<>() {}); + iam.registerLambdaExecutionRoleSession(DEFAULT_ACCOUNT, ACCESS_KEY, "fixture-secret", + "arn:aws:iam::000000000000:role/default"); + iam.registerLambdaExecutionRoleSession(OTHER_ACCOUNT, ACCESS_KEY, "fixture-secret", + "arn:aws:iam::111122223333:role/other"); + + iam.unregisterSession(OTHER_ACCOUNT, null); + iam.unregisterSession(OTHER_ACCOUNT, " "); + assertTrue(sessions.getForAccount(OTHER_ACCOUNT, ACCESS_KEY).isPresent()); + iam.unregisterSession(OTHER_ACCOUNT, ACCESS_KEY); + iam.unregisterSession(OTHER_ACCOUNT, ACCESS_KEY); + + assertTrue(sessions.getForAccount(OTHER_ACCOUNT, ACCESS_KEY).isEmpty()); + assertTrue(sessions.getForAccount(DEFAULT_ACCOUNT, ACCESS_KEY).isPresent()); + } finally { + factory.shutdownAll(); + } + if (!"memory".equals(mode)) { + StorageFactory reopened = StorageFactories.open(config, mode); + try { + IamService iam = new IamService(reopened, config, + new RegionResolver("us-east-1", DEFAULT_ACCOUNT), Clock.systemUTC()); + AccountAwareStorageBackend sessions = reopened.create( + "iam", "iam-sessions.json", new TypeReference<>() {}); + assertTrue(sessions.getForAccount(OTHER_ACCOUNT, ACCESS_KEY).isEmpty()); + assertTrue(sessions.getForAccount(DEFAULT_ACCOUNT, ACCESS_KEY).isPresent()); + iam.unregisterSession(null, ACCESS_KEY); + assertTrue(sessions.getForAccount(DEFAULT_ACCOUNT, ACCESS_KEY).isEmpty()); + } finally { + reopened.shutdownAll(); + } + } + } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void snapshotFailureRevokesImmediatelyAndTheNextWritePersistsRemoval(boolean explicitAccount) throws Exception { + EmulatorConfig config = StorageFactories.config(directory, DEFAULT_ACCOUNT); + StorageFactory factory = StorageFactories.open(config, "persistent"); + Path obstruction = directory.resolve("iam-sessions.json.tmp"); + String account = explicitAccount ? OTHER_ACCOUNT : DEFAULT_ACCOUNT; + try { + IamService iam = new IamService(factory, config, + new RegionResolver("us-east-1", DEFAULT_ACCOUNT), Clock.systemUTC()); + AccountAwareStorageBackend sessions = factory.create( + "iam", "iam-sessions.json", new TypeReference<>() {}); + iam.registerLambdaExecutionRoleSession(account, ACCESS_KEY, "fixture-secret", + "arn:aws:iam::" + account + ":role/retirement"); + Path snapshot = directory.resolve("iam-sessions.json"); + byte[] before = Files.readAllBytes(snapshot); + Files.createDirectory(obstruction); + + assertDoesNotThrow( + () -> iam.unregisterSession(explicitAccount ? account : null, ACCESS_KEY)); + + assertArrayEquals(before, Files.readAllBytes(snapshot)); + assertTrue(sessions.getForAccount(account, ACCESS_KEY).isEmpty()); + assertTrue(iam.resolveCallerArns(ACCESS_KEY).isEmpty()); + Files.delete(obstruction); + iam.registerLambdaExecutionRoleSession(DEFAULT_ACCOUNT, "ASIANEXTWRITE", "fixture-secret", + "arn:aws:iam::000000000000:role/next-write"); + assertFalse(new ObjectMapper().readTree(Files.readAllBytes(snapshot)) + .findValuesAsText("accessKeyId").contains(ACCESS_KEY)); + assertTrue(sessions.getForAccount(account, ACCESS_KEY).isEmpty()); + } finally { + Files.deleteIfExists(obstruction); + factory.shutdownAll(); + } + StorageFactory reopened = StorageFactories.open(config, "persistent"); + try { + AccountAwareStorageBackend sessions = reopened.create( + "iam", "iam-sessions.json", new TypeReference<>() {}); + assertTrue(sessions.getForAccount(account, ACCESS_KEY).isEmpty()); + } finally { + reopened.shutdownAll(); + } + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void ecsRetirementRevokesEveryGenerationDespiteSnapshotFailure(int failedDeletion) throws Exception { + EmulatorConfig config = StorageFactories.config(directory, DEFAULT_ACCOUNT); + when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L); + StorageFactory factory = StorageFactories.open(config, "persistent"); + Path obstruction = directory.resolve("iam-sessions.json.tmp"); + Instant now = Instant.parse("2030-01-01T00:00:00Z"); + String taskArn = "arn:aws:ecs:us-east-1:000000000000:task/cluster/retirement"; + try { + IamService iam = spy(new IamService(factory, config, + new RegionResolver("us-east-1", DEFAULT_ACCOUNT), Clock.fixed(now, ZoneOffset.UTC))); + String roleArn = iam.createRole("retirement", "/", "{}", null, 3600, null).getArn(); + EcsTaskRoleCredentials credentials = new EcsTaskRoleCredentials(iam, config); + String path = credentials.issue(taskArn, roleArn, DEFAULT_ACCOUNT, now).orElseThrow(); + SessionCredential first = credentials.resolveByPath(path, now).orElseThrow(); + Instant rotatedAt = first.getExpiration().minusSeconds(60); + SessionCredential second = credentials.resolveByPath(path, rotatedAt).orElseThrow(); + AtomicInteger deletions = new AtomicInteger(); + doAnswer(invocation -> { + if (deletions.incrementAndGet() == failedDeletion) { + Files.createDirectory(obstruction); + } + return invocation.callRealMethod(); + }).when(iam).unregisterSession(anyString(), anyString()); + + assertDoesNotThrow(() -> credentials.revoke(taskArn)); + assertAll( + () -> assertTrue(credentials.resolveByPath(path, rotatedAt).isEmpty()), + () -> assertTrue(iam.findSecretKey(first.getAccessKeyId(), first.getSessionToken()).isEmpty()), + () -> assertTrue(iam.findSecretKey(second.getAccessKeyId(), second.getSessionToken()).isEmpty())); + Files.delete(obstruction); + factory.flushAll(); + } finally { + Files.deleteIfExists(obstruction); + factory.shutdownAll(); + } + } + +}