diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java index 679fe23703..e868a149f1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java @@ -673,38 +673,41 @@ public class SecretsManagerService implements ResourceProvider { "The RecoveryWindowInDays value must be between 7 and 30 days, inclusive.", 400); } - Secret secret = resolveSecret(secretId, region); - throwIfReplica(secret); - // AWS: "You can't delete a primary secret that is replicated to other Regions. You must - // first delete the replicas." Deleting it here would strand every replica with no primary - // to sync from and no way to remove them. - if (secret.getReplicationStatus() != null && !secret.getReplicationStatus().isEmpty()) { - throw new AwsException("InvalidRequestException", - "You can't delete a secret that is replicated to other Regions. " - + "Remove the replicas with RemoveRegionsFromReplication first.", 400); - } - String storageKey = regionKey(region, secret.getName()); + Secret resolved = resolveSecret(secretId, region); + synchronized (lockFor(resolved.getArn())) { + Secret secret = resolveSecret(resolved.getArn(), region); + throwIfReplica(secret); + // AWS: "You can't delete a primary secret that is replicated to other Regions. You must + // first delete the replicas." Deleting it here would strand every replica with no primary + // to sync from and no way to remove them. + if (secret.getReplicationStatus() != null && !secret.getReplicationStatus().isEmpty()) { + throw new AwsException("InvalidRequestException", + "You can't delete a secret that is replicated to other Regions. " + + "Remove the replicas with RemoveRegionsFromReplication first.", 400); + } + String storageKey = regionKey(region, secret.getName()); - if (forceDelete) { - store.delete(storageKey); - LOG.infov("Force-deleted secret: {0}", secret.getName()); - secret.setDeletedDate(Instant.now()); + if (forceDelete) { + store.delete(storageKey); + LOG.infov("Force-deleted secret: {0}", secret.getName()); + secret.setDeletedDate(Instant.now()); + return secret; + } + + // Guard placed AFTER the force-delete branch on purpose: force-deleting a secret that is + // already inside its recovery window is a legitimate "skip the window, remove it now" + // escape hatch, so only the scheduling path is refused. Re-scheduling an already-scheduled + // secret silently moved its DeletionDate, which would quietly extend a window a caller + // believed was already counting down. + throwIfPendingDeletion(secret); + + int windowDays = (recoveryWindowInDays != null) ? recoveryWindowInDays : defaultRecoveryWindowDays; + Instant deletedDate = Instant.now().plusSeconds((long) windowDays * 86400); + secret.setDeletedDate(deletedDate); + store.put(storageKey, secret); + LOG.infov("Scheduled deletion of secret: {0} at {1}", secret.getName(), deletedDate); return secret; } - - // Guard placed AFTER the force-delete branch on purpose: force-deleting a secret that is - // already inside its recovery window is a legitimate "skip the window, remove it now" - // escape hatch, so only the scheduling path is refused. Re-scheduling an already-scheduled - // secret silently moved its DeletionDate, which would quietly extend a window a caller - // believed was already counting down. - throwIfPendingDeletion(secret); - - int windowDays = (recoveryWindowInDays != null) ? recoveryWindowInDays : defaultRecoveryWindowDays; - Instant deletedDate = Instant.now().plusSeconds((long) windowDays * 86400); - secret.setDeletedDate(deletedDate); - store.put(storageKey, secret); - LOG.infov("Scheduled deletion of secret: {0} at {1}", secret.getName(), deletedDate); - return secret; } // ─── Multi-region replication ────────────────────────────────────────────── @@ -1339,10 +1342,12 @@ public class SecretsManagerService implements ResourceProvider { } invokeRotationLambda(secretArn, clientRequestToken, lambdaArn, "testSecret", region); invokeRotationLambda(secretArn, clientRequestToken, lambdaArn, "finishSecret", region); - - Secret refreshed = resolveSecret(secretArn, region); - refreshed.setLastRotatedDate(Instant.now()); - persist(refreshed, region); + + synchronized (lockFor(secretArn)) { + Secret refreshed = resolveSecret(secretArn, region); + refreshed.setLastRotatedDate(Instant.now()); + persist(refreshed, region); + } } catch (Exception e) { LOG.errorv(e, "Error during rotation steps for secret {0}", secretArn); throw e; diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationFunctionRegionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationFunctionRegionIntegrationTest.java index e2c48f829f..dc0eb7dfbb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationFunctionRegionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationFunctionRegionIntegrationTest.java @@ -3,9 +3,13 @@ package io.github.hectorvent.floci.services.secretsmanager; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.List; + import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; @@ -20,17 +24,29 @@ class SecretsManagerRotationFunctionRegionIntegrationTest { private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1"; + private final List secretsToDelete = new ArrayList<>(); + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); } + @AfterEach + void deleteCreatedSecrets() { + for (String secretId : secretsToDelete) { + secretsManager("DeleteSecret", "{\"SecretId\": \"" + secretId + "\", \"ForceDeleteWithoutRecovery\": true}") + .then() + .statusCode(200); + } + } + @Test void rotationFunctionInAnotherRegionIsAnInvalidParameter() { String secretName = "rotation-other-region-secret"; secretsManager("CreateSecret", "{\"Name\": \"" + secretName + "\", \"SecretString\": \"initial-value\"}") .then() .statusCode(200); + secretsToDelete.add(secretName); secretsManager("RotateSecret", "{\"SecretId\": \"" + secretName + "\", " + "\"RotationLambdaARN\": \"arn:aws:lambda:us-west-2:000000000000:function:rotator\"}") diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationIntegrationTest.java index a55d7a3ba2..36e87e76d9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationIntegrationTest.java @@ -6,12 +6,18 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.InjectMock; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -28,11 +34,27 @@ public class SecretsManagerRotationIntegrationTest { @InjectMock LambdaService lambdaService; + private final List secretsToDelete = new ArrayList<>(); + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); } + @AfterEach + void deleteCreatedSecrets() { + for (String secretId : secretsToDelete) { + given() + .header("X-Amz-Target", "secretsmanager.DeleteSecret") + .contentType(SM_CONTENT_TYPE) + .body("{\"SecretId\": \"" + secretId + "\", \"ForceDeleteWithoutRecovery\": true}") + .when() + .post("/") + .then() + .statusCode(200); + } + } + @Test void testRotateSecretTriggersLambda() { // Mock lambda response to avoid errors @@ -56,6 +78,7 @@ public class SecretsManagerRotationIntegrationTest { .then() .statusCode(200) .extract().asString(); + secretsToDelete.add(secretName); // extract ARN if needed, but we can just refer by Name @@ -98,6 +121,18 @@ public class SecretsManagerRotationIntegrationTest { assertTrue(hasSet, "Should invoke setSecret"); assertTrue(hasTest, "Should invoke testSecret"); assertTrue(hasFinish, "Should invoke finishSecret"); + + // Let the rotation finish before cleanup deletes the secret, which it would otherwise go on + // trying to update. + await().atMost(Duration.ofSeconds(5)).until(() -> given() + .header("X-Amz-Target", "secretsmanager.DescribeSecret") + .contentType(SM_CONTENT_TYPE) + .body("{\"SecretId\": \"" + secretName + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("LastRotatedDate") != null); } @Test @@ -111,6 +146,7 @@ public class SecretsManagerRotationIntegrationTest { .post("/") .then() .statusCode(200); + secretsToDelete.add(secretName); given() .header("X-Amz-Target", "secretsmanager.RotateSecret") diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java index cb0f7ff609..25ec4899b2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java @@ -10,18 +10,23 @@ import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.util.ArrayDeque; +import java.util.Deque; import java.util.Map; import java.util.UUID; import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -45,6 +50,9 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { @InjectMock LambdaService lambdaService; + /** How to delete each thing the test created, pushed as it is created and run newest first. */ + private final Deque cleanup = new ArrayDeque<>(); + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -58,6 +66,18 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { Mockito.when(lambdaService.invoke(any(), any(), any(), any())).thenReturn(ok); } + /** + * Deletes what the test created, newest first: a secret before the user that made it, and a + * user's access key and inline policy before the user, as DeleteUser requires. A test whose + * setup stopped partway deletes only what it got to create. + */ + @AfterEach + void deleteWhatTheTestCreated() { + while (!cleanup.isEmpty()) { + cleanup.pop().run(); + } + } + @Test void rotateSecretIsDeniedWhenCallerCannotInvokeTheRotationFunction() { String suffix = UUID.randomUUID().toString().substring(0, 8); @@ -68,6 +88,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { String secretName = "rotate-denied-" + suffix; secretsManager(accessKeyId, "CreateSecret", "{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200); + deleteSecretAfterwards(secretName); secretsManager(accessKeyId, "RotateSecret", "{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + "\"}") @@ -87,6 +108,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { String secretName = "rotate-presigned-" + suffix; secretsManager(accessKeyId, "CreateSecret", "{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200); + deleteSecretAfterwards(secretName); String amzDate = AMZ_DATE_FMT.format(Instant.now()); given() @@ -122,6 +144,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { String secretName = "rotate-by-name-" + suffix; secretsManager(accessKeyId, "CreateSecret", "{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200); + deleteSecretAfterwards(secretName); secretsManager(accessKeyId, "RotateSecret", "{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionName + "\"}") @@ -129,6 +152,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { Mockito.verify(lambdaService, Mockito.timeout(5000).atLeastOnce()) .invoke(any(), eq(functionArn), any(), any()); + awaitRotationFinished(secretName); } @Test @@ -143,6 +167,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { String secretName = "rotate-allowed-" + suffix; secretsManager(accessKeyId, "CreateSecret", "{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200); + deleteSecretAfterwards(secretName); secretsManager(accessKeyId, "RotateSecret", "{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + "\"}") @@ -150,6 +175,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { Mockito.verify(lambdaService, Mockito.timeout(5000).atLeastOnce()) .invoke(any(), eq(functionArn), any(), any()); + awaitRotationFinished(secretName); } private static ValidatableResponse secretsManager(String accessKeyId, String operation, String body) { @@ -163,15 +189,35 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { .then(); } - private static String createUserWithPolicy(String userName, String policyDocument) { + /** + * Lets the rotation finish before cleanup deletes the secret, which it would otherwise go on + * trying to update. + */ + private static void awaitRotationFinished(String secretName) { + await().atMost(Duration.ofSeconds(5)).until(() -> secretsManager(ACCOUNT_ID, "DescribeSecret", + "{\"SecretId\":\"" + secretName + "\"}").statusCode(200).extract().path("LastRotatedDate") != null); + } + + private void deleteSecretAfterwards(String secretName) { + cleanup.push(() -> secretsManager(ACCOUNT_ID, "DeleteSecret", + "{\"SecretId\":\"" + secretName + "\",\"ForceDeleteWithoutRecovery\":true}").statusCode(200)); + } + + private String createUserWithPolicy(String userName, String policyDocument) { adminIam("CreateUser", Map.of("UserName", userName)).statusCode(200); + cleanup.push(() -> adminIam("DeleteUser", Map.of("UserName", userName)).statusCode(200)); adminIam("PutUserPolicy", Map.of( "UserName", userName, "PolicyName", "inline", "PolicyDocument", policyDocument)).statusCode(200); - return adminIam("CreateAccessKey", Map.of("UserName", userName)) + cleanup.push(() -> adminIam("DeleteUserPolicy", + Map.of("UserName", userName, "PolicyName", "inline")).statusCode(200)); + String accessKeyId = adminIam("CreateAccessKey", Map.of("UserName", userName)) .statusCode(200) .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"); + cleanup.push(() -> adminIam("DeleteAccessKey", + Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(200)); + return accessKeyId; } private static ValidatableResponse adminIam(String action, Map params) { diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java index 8ef20da538..b70a0dc09d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java @@ -1,6 +1,12 @@ package io.github.hectorvent.floci.services.secretsmanager; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; import io.github.hectorvent.floci.services.secretsmanager.model.Secret; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,10 +15,16 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiPredicate; 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Every write to a secret goes through the same per-secret monitor, including the writes a primary @@ -56,6 +68,54 @@ class SecretsManagerWriteLockTest { assertEquals("alias/second", updated.getKmsKeyId()); } + @Test + void deletingASecretWaitsForAnInFlightUpdate() throws Exception { + storage.parkOn(REGION + "::" + SECRET_NAME); + Watched update = start("update", () -> + service.updateSecret(SECRET_NAME, "from-update", null, REGION)); + assertTrue(storage.awaitEntered(), "UpdateSecret never reached the store write"); + + Watched delete = start("delete", () -> service.deleteSecret(SECRET_NAME, null, true, REGION)); + assertTrue(delete.awaitBlocked(), "DeleteSecret did not wait for the in-flight UpdateSecret"); + + storage.release(); + update.awaitSuccess(); + delete.awaitSuccess(); + + // The delete ran after the update's write, so the secret stays deleted. + assertThrows(AwsException.class, () -> service.describeSecret(SECRET_NAME, REGION)); + } + + @Test + void deletingASecretWaitsForTheFinalSaveOfARotation() throws Exception { + LambdaService lambda = mock(LambdaService.class); + when(lambda.getFunction(anyString(), anyString())).thenReturn(new LambdaFunction()); + InvokeResult ok = new InvokeResult(); + ok.setStatusCode(200); + when(lambda.invoke(anyString(), anyString(), any(byte[].class), any())).thenReturn(ok); + SecretsManagerService rotating = new SecretsManagerService( + storage, 30, new RegionResolver(REGION, "000000000000"), lambda, new ObjectMapper()); + try { + // The rotation's last write is the one that records LastRotatedDate. + storage.parkOn((key, secret) -> secret.getLastRotatedDate() != null); + rotating.rotateSecret(SECRET_NAME, "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "arn:aws:lambda:us-east-1:000000000000:function:rotator", null, true, REGION, functionArn -> { }); + assertTrue(storage.awaitEntered(), "The rotation never reached its final save"); + + Watched delete = start("delete", () -> rotating.deleteSecret(SECRET_NAME, null, true, REGION)); + assertTrue(delete.awaitBlocked(), "DeleteSecret did not wait for the rotation's final save"); + + storage.release(); + delete.awaitSuccess(); + + // Deleted after the final save, not before it, so the save cannot bring the secret back. + assertThrows(AwsException.class, () -> rotating.describeSecret(SECRET_NAME, REGION)); + } finally { + // Rotation workers are not daemon threads; leave none behind. + rotating.shutdown(); + } + } + @Test void promotingAReplicaWaitsForAnInFlightSyncFromItsPrimary() throws Exception { service.replicateSecretToRegions(SECRET_NAME, @@ -89,15 +149,19 @@ class SecretsManagerWriteLockTest { return watched; } - /** Parks the first write to one chosen key so another thread can race the caller holding it. */ + /** Parks the first matching write so another thread can race the caller holding it. */ private static final class ParkingStorage extends InMemoryStorage { private final CountDownLatch entered = new CountDownLatch(1); private final CountDownLatch released = new CountDownLatch(1); - private volatile String parkKey; + private volatile BiPredicate parkWhen; void parkOn(String key) { - this.parkKey = key; + parkOn((written, secret) -> written.equals(key)); + } + + void parkOn(BiPredicate condition) { + this.parkWhen = condition; } boolean awaitEntered() throws InterruptedException { @@ -110,8 +174,9 @@ class SecretsManagerWriteLockTest { @Override public void put(String key, Secret value) { - if (key.equals(parkKey)) { - parkKey = null; + BiPredicate condition = parkWhen; + if (condition != null && condition.test(key, value)) { + parkWhen = null; entered.countDown(); try { released.await(5, TimeUnit.SECONDS);