fix(secretsmanager): stage an AWSPENDING version for the test step of a rotation that is not immediate (#7642)

This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-05 16:45:19 -04:00
1 parent 13d6dd18d4
commit bcbd7c8d9d
3 files changed
+177 -19

No files matched your search

@@ -1692,7 +1692,17 @@ public class SecretsManagerService implements ResourceProvider {
private void executeRotationLifecycle(String secretArn, String clientRequestToken, String lambdaArn, boolean rotateImmediately, boolean isExistingVersion, String region) {
if (!rotateImmediately) {
invokeRotationLambda(secretArn, clientRequestToken, lambdaArn, "testSecret", region);
// AWS tests the configuration against an AWSPENDING version it creates and then removes.
// Without a Lambda there is no test step, so there is nothing to stage.
boolean staged = lambdaService != null && !isExistingVersion
&& stagePendingVersion(secretArn, clientRequestToken, region);
try {
invokeRotationLambda(secretArn, clientRequestToken, lambdaArn, "testSecret", region);
} finally {
if (staged) {
removeVersion(secretArn, clientRequestToken, region);
}
}
synchronized (lockFor(secretArn)) {
Secret refreshed = resolveSecret(secretArn, region);
@@ -1709,22 +1719,7 @@ public class SecretsManagerService implements ResourceProvider {
try {
if (!isExistingVersion) {
synchronized (lockFor(secretArn)) {
Secret secret = resolveSecret(secretArn, region);
if (secret.getVersions() != null && secret.getVersions().containsKey(clientRequestToken)) {
isExistingVersion = true;
} else {
SecretVersion pendingVersion = new SecretVersion();
pendingVersion.setVersionId(clientRequestToken);
pendingVersion.setVersionStages(List.of("AWSPENDING"));
pendingVersion.setCreatedDate(Instant.now());
if (secret.getVersions() == null) {
secret.setVersions(new HashMap<>());
}
secret.getVersions().put(clientRequestToken, pendingVersion);
persist(secret, region);
}
}
isExistingVersion = !stagePendingVersion(secretArn, clientRequestToken, region);
}
if (!isExistingVersion) {
invokeRotationLambda(secretArn, clientRequestToken, lambdaArn, "createSecret", region);
@@ -1744,6 +1739,38 @@ public class SecretsManagerService implements ResourceProvider {
}
}
/**
* Adds an empty AWSPENDING version under the rotation token, unless a version with that id
* already exists. Returns whether it added one.
*/
private boolean stagePendingVersion(String secretArn, String clientRequestToken, String region) {
synchronized (lockFor(secretArn)) {
Secret secret = resolveSecret(secretArn, region);
if (secret.getVersions() != null && secret.getVersions().containsKey(clientRequestToken)) {
return false;
}
SecretVersion pendingVersion = new SecretVersion();
pendingVersion.setVersionId(clientRequestToken);
pendingVersion.setVersionStages(List.of("AWSPENDING"));
pendingVersion.setCreatedDate(Instant.now());
if (secret.getVersions() == null) {
secret.setVersions(new HashMap<>());
}
secret.getVersions().put(clientRequestToken, pendingVersion);
persist(secret, region);
return true;
}
}
private void removeVersion(String secretArn, String versionId, String region) {
synchronized (lockFor(secretArn)) {
Secret secret = resolveSecret(secretArn, region);
if (secret.getVersions() != null && secret.getVersions().remove(versionId) != null) {
persist(secret, region);
}
}
}
private void invokeRotationLambda(String secretArn, String clientRequestToken, String lambdaArn, String step, String region) {
if (lambdaService == null) {
LOG.warnv("LambdaService is not available; skipping rotation lambda invocation for step {0}", step);
@@ -10,16 +10,23 @@ import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Covers the background sweep that makes a rotation schedule actually fire. Rotation itself runs
@@ -32,19 +39,34 @@ class SecretRotationSchedulerTest {
private static final String LAMBDA_ARN = "arn:aws:lambda:us-east-1:000000000000:function:rotate";
private static final String TOKEN = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
private final LambdaService lambda = mock(LambdaService.class);
private SecretsManagerService service;
private SecretRotationScheduler scheduler;
@BeforeEach
void setUp() {
service = new SecretsManagerService(new InMemoryStorage<>(), 30,
new RegionResolver(REGION, "000000000000"), mock(LambdaService.class), new ObjectMapper());
new RegionResolver(REGION, "000000000000"), lambda, new ObjectMapper());
scheduler = new SecretRotationScheduler(service);
}
private void enableRotation(String name, Secret.RotationRules rules) {
service.createSecret(name, "v1", null, null, null, null, REGION);
service.rotateSecret(name, TOKEN, LAMBDA_ARN, rules, false, REGION);
awaitTestStep(service, lambda, name);
}
/**
* Enabling rotation tests it in the background against an AWSPENDING version, and a rotation
* requested while that version exists is refused. Waits until the test step has ended.
*/
private static void awaitTestStep(SecretsManagerService service, LambdaService lambda, String name) {
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
verify(lambda).invoke(anyString(), anyString(),
argThat(payload -> new String(payload, StandardCharsets.UTF_8).contains(name)), any());
assertTrue(service.describeSecret(name, REGION).getVersions().values().stream()
.noneMatch(version -> version.getVersionStages().contains("AWSPENDING")));
});
}
// ─── Next-rotation-date computation ────────────────────────────────────────
@@ -198,13 +220,15 @@ class SecretRotationSchedulerTest {
String foreignAccount = "111122223333";
AccountAwareStorageBackend<Secret> store =
AccountAwareStorageBackend.inMemory("000000000000");
LambdaService foreignLambda = mock(LambdaService.class);
SecretsManagerService accountAware = new SecretsManagerService(store, 30,
new RegionResolver(REGION, "000000000000"), mock(LambdaService.class), new ObjectMapper());
new RegionResolver(REGION, "000000000000"), foreignLambda, new ObjectMapper());
SecretRotationScheduler sweep = new SecretRotationScheduler(accountAware);
accountAware.createSecret("foreign", "v1", null, null, null, null, REGION);
accountAware.rotateSecret("foreign", TOKEN, LAMBDA_ARN,
new Secret.RotationRules(14, null, null), false, REGION);
awaitTestStep(accountAware, foreignLambda, "foreign");
// Re-home the secret into the other account, ARN included, and clear the default copy.
Secret secret = accountAware.describeSecret("foreign", REGION);
@@ -0,0 +1,107 @@
package io.github.hectorvent.floci.services.secretsmanager;
import com.fasterxml.jackson.databind.ObjectMapper;
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.secretsmanager.model.Secret;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
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.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* RotateSecret with {@code RotateImmediately=false} only tests the rotation configuration: AWS runs
* the function's testSecret step against an AWSPENDING version it creates, then removes that version.
*/
class SecretsManagerRotateLaterTest {
private static final String REGION = "us-east-1";
private static final String NAME = "rotate-later";
private static final String TOKEN = "11111111-2222-3333-4444-555555555555";
private static final String LAMBDA_ARN = "arn:aws:lambda:us-east-1:000000000000:function:rotate";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final LambdaService lambda = mock(LambdaService.class);
private final SecretsManagerService service = new SecretsManagerService(new InMemoryStorage<String, Secret>(),
30, new RegionResolver(REGION, "000000000000"), lambda, MAPPER);
@AfterEach
void shutdown() {
service.shutdown();
}
@Test
void theTestStepFindsAnAwsPendingVersionForItsToken() throws Exception {
AtomicReference<List<String>> stagesSeen = new AtomicReference<>();
CountDownLatch tested = new CountDownLatch(1);
when(lambda.invoke(anyString(), anyString(), any(byte[].class), any())).thenAnswer(invocation -> {
String step = MAPPER.readTree((byte[]) invocation.getArgument(2)).path("Step").asText();
if ("testSecret".equals(step)) {
SecretVersion version = service.describeSecret(NAME, REGION).getVersions().get(TOKEN);
stagesSeen.set(version == null ? List.of() : new ArrayList<>(version.getVersionStages()));
tested.countDown();
}
return succeeded();
});
service.createSecret(NAME, "v1", null, null, null, null, REGION);
service.rotateSecret(NAME, TOKEN, LAMBDA_ARN, null, false, REGION);
assertTrue(tested.await(10, TimeUnit.SECONDS), "the testSecret step must run");
assertEquals(List.of("AWSPENDING"), stagesSeen.get());
}
@Test
void thePendingVersionIsRemovedOnceTheTestStepEnds() {
when(lambda.invoke(anyString(), anyString(), any(byte[].class), any())).thenReturn(succeeded());
Secret created = service.createSecret(NAME, "v1", null, null, null, null, REGION);
service.rotateSecret(NAME, TOKEN, LAMBDA_ARN, null, false, REGION);
awaitOnlyVersion(created.getCurrentVersionId());
}
@Test
void thePendingVersionIsRemovedWhenTheTestStepFails() {
InvokeResult failed = succeeded();
failed.setFunctionError("Unhandled");
when(lambda.invoke(anyString(), anyString(), any(byte[].class), any())).thenReturn(failed);
Secret created = service.createSecret(NAME, "v1", null, null, null, null, REGION);
service.rotateSecret(NAME, TOKEN, LAMBDA_ARN, null, false, REGION);
awaitOnlyVersion(created.getCurrentVersionId());
}
/** Waits until the rotation has run its test step and the secret holds only the given version. */
private void awaitOnlyVersion(String versionId) {
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
verify(lambda).invoke(anyString(), anyString(), any(byte[].class), any());
assertEquals(List.of(versionId),
List.copyOf(service.describeSecret(NAME, REGION).getVersions().keySet()));
});
}
private static InvokeResult succeeded() {
InvokeResult result = new InvokeResult();
result.setStatusCode(200);
return result;
}
}