feat(secretsmanager): implement automatic secret rotation lifecycle (#1467)

* fix: return XML error for missing action and add volume action fallbacks

* fix(eventbridge): sync EventBridge tags to ResourceGroupsTaggingService

EventBridge stored tags on rules, buses, and archives in its own stores but never propagated them to the central ResourceGroupsTaggingService. This caused GetResources with --resource-type-filters events:rule to return an empty list.

Inject ResourceGroupsTaggingService into EventBridgeService (following the existing GlueService pattern) and sync tags during putRule, tagResource, untagResource, and deleteRule operations.

Closes #1343

* feat(secretsmanager): implement automatic secret rotation lifecycle

* fix(secretsmanager): correct RotationLambdaARN validation in tests and rotation rules parsing

* fix(secretsmanager): avoid implicit unboxing NPE when parsing rotation rules

* fix: remove debug print, drop camelCase rotation parameters fallback, and revert unrelated eventbridge changes

* fix: align PutSecretValue error code and resolve NPE in JSON handler tests

* fix(test): create Lambda function before rotateSecret to fix ResourceNotFoundException

rotateSecretStub failed because SecretsManagerService validates the
rotation Lambda exists synchronously. The test was passing an ARN for a
function that had never been created in the emulator.

Create a real Lambda function via LambdaClient before calling
rotateSecret, and clean it up afterwards. Uses
Runtime.fromValue(nodejs20.x) for SDK compatibility.

* fix: non-immediate rotation runs testSecret only

Per AWS RotateSecret docs, when RotateImmediately is false Secrets
Manager tests the rotation configuration by running only the testSecret
step. Remove the createSecret invocation from the non-immediate path.

* fix(test): align rotateSecretNotImmediate with non-immediate rotation path

The non-immediate rotation path only invokes testSecret (not createSecret),
so the test should expect 1 lambda invocation instead of 2.
This commit is contained in:
Konda Balaji Rao authored and GitHub committed 2026-06-22 23:18:16 -05:00
1 parent 2301db53c7
commit f725a38969
7 files changed
+723 -54

No files matched your search

@@ -247,4 +247,79 @@ class SecretsManagerJsonHandlerTest {
Response response = handler.handle("BatchGetSecretValue", batchReq, REGION);
assertThat(response.getStatus(), is(400));
}
@Test
void rotateSecretParsesRotationRules() {
ObjectNode createReq = MAPPER.createObjectNode();
createReq.put("Name", "rotate-test-secret");
handler.handle("CreateSecret", createReq, REGION);
ObjectNode rotateReq = MAPPER.createObjectNode();
rotateReq.put("SecretId", "rotate-test-secret");
rotateReq.put("RotationLambdaARN", "arn:aws:lambda:us-east-1:000000000000:function:rotate");
ObjectNode rules = MAPPER.createObjectNode();
rules.put("ScheduleExpression", "cron(0 16 ? * 2 *)");
rotateReq.set("RotationRules", rules);
Response response = handler.handle("RotateSecret", rotateReq, REGION);
assertThat(response.getStatus(), is(200));
ObjectNode describeReq = MAPPER.createObjectNode();
describeReq.put("SecretId", "rotate-test-secret");
Response describeResponse = handler.handle("DescribeSecret", describeReq, REGION);
ObjectNode body = (ObjectNode) describeResponse.getEntity();
assertThat(body.has("RotationRules"), is(true));
assertThat(body.get("RotationRules").get("ScheduleExpression").asText(), is("cron(0 16 ? * 2 *)"));
assertThat(body.get("RotationRules").has("AutomaticallyAfterDays"), is(false));
}
@Test
void rotateSecretFailsWithMutuallyExclusiveRotationRules() {
ObjectNode createReq = MAPPER.createObjectNode();
createReq.put("Name", "rotate-test-secret-2");
handler.handle("CreateSecret", createReq, REGION);
ObjectNode rotateReq = MAPPER.createObjectNode();
rotateReq.put("SecretId", "rotate-test-secret-2");
rotateReq.put("RotationLambdaARN", "arn:aws:lambda:us-east-1:000000000000:function:rotate");
ObjectNode rules = MAPPER.createObjectNode();
rules.put("AutomaticallyAfterDays", 30);
rules.put("ScheduleExpression", "cron(0 16 ? * 2 *)");
rotateReq.set("RotationRules", rules);
io.github.hectorvent.floci.core.common.AwsException ex = org.junit.jupiter.api.Assertions.assertThrows(
io.github.hectorvent.floci.core.common.AwsException.class,
() -> handler.handle("RotateSecret", rotateReq, REGION)
);
assertThat(ex.getErrorCode(), is("InvalidParameterException"));
}
@Test
void rotateSecretParsesAllPascalCaseRules() {
ObjectNode createReq = MAPPER.createObjectNode();
createReq.put("Name", "rotate-test-secret-all-pascal");
handler.handle("CreateSecret", createReq, REGION);
ObjectNode rotateReq = MAPPER.createObjectNode();
rotateReq.put("SecretId", "rotate-test-secret-all-pascal");
rotateReq.put("RotationLambdaARN", "arn:aws:lambda:us-east-1:000000000000:function:rotate");
rotateReq.put("RotateImmediately", false);
ObjectNode rules = MAPPER.createObjectNode();
rules.put("AutomaticallyAfterDays", 45);
rules.put("Duration", "2h");
rotateReq.set("RotationRules", rules);
Response response = handler.handle("RotateSecret", rotateReq, REGION);
assertThat(response.getStatus(), is(200));
ObjectNode describeReq = MAPPER.createObjectNode();
describeReq.put("SecretId", "rotate-test-secret-all-pascal");
Response describeResponse = handler.handle("DescribeSecret", describeReq, REGION);
ObjectNode body = (ObjectNode) describeResponse.getEntity();
assertThat(body.has("RotationRules"), is(true));
assertThat(body.get("RotationRules").get("AutomaticallyAfterDays").asInt(), is(45));
assertThat(body.get("RotationRules").get("Duration").asText(), is("2h"));
}
}
@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.services.secretsmanager;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
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.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
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.eq;
@QuarkusTest
public class SecretsManagerRotationIntegrationTest {
private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String REGION = "us-east-1";
@InjectMock
LambdaService lambdaService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void testRotateSecretTriggersLambda() {
// Mock lambda response to avoid errors
InvokeResult successResult = new InvokeResult();
successResult.setStatusCode(200);
Mockito.when(lambdaService.invoke(any(), any(), any(), any())).thenReturn(successResult);
// 1. Create a secret
String secretName = "rotation-test-secret";
String lambdaArn = "arn:aws:lambda:us-east-1:000000000000:function:my-rotation-lambda";
String createSecretResponse = given()
.header("X-Amz-Target", "secretsmanager.CreateSecret")
.contentType(SM_CONTENT_TYPE)
.body("{" +
"\"Name\": \"" + secretName + "\"," +
"\"SecretString\": \"initial-value\"" +
"}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
// extract ARN if needed, but we can just refer by Name
// 2. Rotate the secret
given()
.header("X-Amz-Target", "secretsmanager.RotateSecret")
.contentType(SM_CONTENT_TYPE)
.body("{" +
"\"SecretId\": \"" + secretName + "\"," +
"\"RotationLambdaARN\": \"" + lambdaArn + "\"" +
"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ARN", notNullValue())
.body("VersionId", notNullValue());
// 3. Verify that lambda was invoked 4 times for the rotation steps (timeout allows async execution to finish)
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
Mockito.verify(lambdaService, Mockito.timeout(5000).times(4))
.invoke(eq(REGION), eq(lambdaArn), payloadCaptor.capture(), eq(InvocationType.RequestResponse));
// 4. Verify payloads contain the required steps
boolean hasCreate = false;
boolean hasSet = false;
boolean hasTest = false;
boolean hasFinish = false;
for (byte[] payloadBytes : payloadCaptor.getAllValues()) {
String payloadStr = new String(payloadBytes, java.nio.charset.StandardCharsets.UTF_8);
if (payloadStr.contains("\"Step\":\"createSecret\"")) hasCreate = true;
if (payloadStr.contains("\"Step\":\"setSecret\"")) hasSet = true;
if (payloadStr.contains("\"Step\":\"testSecret\"")) hasTest = true;
if (payloadStr.contains("\"Step\":\"finishSecret\"")) hasFinish = true;
}
assertTrue(hasCreate, "Should invoke createSecret");
assertTrue(hasSet, "Should invoke setSecret");
assertTrue(hasTest, "Should invoke testSecret");
assertTrue(hasFinish, "Should invoke finishSecret");
}
}
@@ -63,7 +63,7 @@ class SecretsManagerServiceTest {
@Test
void putSecretValueRotatesVersion() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, null);
service.putSecretValue("my-secret", "v2", null, null, REGION, null);
SecretVersion current = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION);
assertEquals("v2", current.getSecretString());
@@ -77,14 +77,14 @@ class SecretsManagerServiceTest {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.deleteSecret("my-secret", null, true, REGION);
assertThrows(AwsException.class, () ->
service.putSecretValue("my-secret", "v2", null, REGION, null));
service.putSecretValue("my-secret", "v2", null, null, REGION, null));
}
@Test
void putSecretValuePendingStage() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, List.of("AWSCURRENT"));
service.putSecretValue("my-secret", "v3", null, REGION, List.of("AWSPENDING"));
service.putSecretValue("my-secret", "v2", null, null, REGION, List.of("AWSCURRENT"));
service.putSecretValue("my-secret", "v3", null, null, REGION, List.of("AWSPENDING"));
SecretVersion previous = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION);
assertEquals("v1", previous.getSecretString());
@@ -104,7 +104,7 @@ class SecretsManagerServiceTest {
assertEquals("v1", current.getSecretString());
// adding new secret version, previous will be v1, current will be v2
service.putSecretValue("my-secret", "v2", null, REGION, List.of("AWSCURRENT"));
service.putSecretValue("my-secret", "v2", null, null, REGION, List.of("AWSCURRENT"));
SecretVersion previous = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION);
assertEquals("v1", previous.getSecretString());
current = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION);
@@ -112,7 +112,7 @@ class SecretsManagerServiceTest {
// adding new secret version v3, current and pending will be v3,
// previous will be v2
service.putSecretValue("my-secret", "v3", null, REGION, List.of("AWSCURRENT", "AWSPENDING"));
service.putSecretValue("my-secret", "v3", null, null, REGION, List.of("AWSCURRENT", "AWSPENDING"));
previous = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION);
assertEquals("v2", previous.getSecretString());
current = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION);
@@ -127,13 +127,13 @@ class SecretsManagerServiceTest {
// no stages
Assertions.assertThrows(AwsException.class, () ->
service.putSecretValue("my-secret", "v2", null, REGION, List.of())
service.putSecretValue("my-secret", "v2", null, null, REGION, List.of())
);
// more than 20
List<String> stages =
IntStream.range(0, 21).mapToObj(i -> "stage" + i).toList();
Assertions.assertThrows(AwsException.class, () ->
service.putSecretValue("my-secret", "v2", null, REGION, stages)
service.putSecretValue("my-secret", "v2", null, null, REGION, stages)
);
}
@@ -142,12 +142,12 @@ class SecretsManagerServiceTest {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
// Stage name is 0-length
Assertions.assertThrows(AwsException.class, () ->
service.putSecretValue("my-secret", "v2", null, REGION, List.of(""))
service.putSecretValue("my-secret", "v2", null, null, REGION, List.of(""))
);
// Stage name is larger than 256 characters
String stageName = RandomStringUtils.randomAlphanumeric(257);
Assertions.assertThrows(AwsException.class, () ->
service.putSecretValue("my-secret", "v2", null, REGION, List.of(stageName))
service.putSecretValue("my-secret", "v2", null, null, REGION, List.of(stageName))
);
}
@@ -213,13 +213,65 @@ class SecretsManagerServiceTest {
}
@Test
void rotateSecret() {
service.createSecret("my-secret", "value", null, null, null, null, REGION);
Secret rotated = service.rotateSecret("my-secret",
void rotateSecret() throws Exception {
// We need a mocked LambdaService for testing the orchestrator.
// The service in the setUp method doesn't have it.
io.github.hectorvent.floci.services.lambda.LambdaService mockLambda = org.mockito.Mockito.mock(io.github.hectorvent.floci.services.lambda.LambdaService.class);
io.github.hectorvent.floci.services.lambda.model.InvokeResult successResult = new io.github.hectorvent.floci.services.lambda.model.InvokeResult();
// Assume success response
org.mockito.Mockito.when(mockLambda.invoke(org.mockito.Mockito.anyString(), org.mockito.Mockito.anyString(), org.mockito.Mockito.any(byte[].class), org.mockito.Mockito.any()))
.thenReturn(successResult);
SecretsManagerService svc = new SecretsManagerService(
new InMemoryStorage<String, Secret>(), 30,
new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "000000000000"),
mockLambda, new com.fasterxml.jackson.databind.ObjectMapper());
svc.createSecret("my-secret", "value", null, null, null, null, REGION);
Secret.RotationRules rules = new Secret.RotationRules(30, null, null);
Secret rotated = svc.rotateSecret("my-secret", "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"arn:aws:lambda:us-east-1:000000000000:function:rotate",
Map.of("AutomaticallyAfterDays", 30), true, REGION);
rules, true, REGION);
assertTrue(rotated.isRotationEnabled());
// Verify lambda invoked 4 times
org.mockito.Mockito.verify(mockLambda, org.mockito.Mockito.timeout(5000).times(4))
.invoke(org.mockito.Mockito.eq(REGION),
org.mockito.Mockito.eq("arn:aws:lambda:us-east-1:000000000000:function:rotate"),
org.mockito.Mockito.any(byte[].class),
org.mockito.Mockito.eq(io.github.hectorvent.floci.services.lambda.model.InvocationType.RequestResponse));
}
@Test
void rotateSecretNotImmediate() throws Exception {
io.github.hectorvent.floci.services.lambda.LambdaService mockLambda = org.mockito.Mockito.mock(io.github.hectorvent.floci.services.lambda.LambdaService.class);
io.github.hectorvent.floci.services.lambda.model.InvokeResult successResult = new io.github.hectorvent.floci.services.lambda.model.InvokeResult();
org.mockito.Mockito.when(mockLambda.invoke(org.mockito.Mockito.anyString(), org.mockito.Mockito.anyString(), org.mockito.Mockito.any(byte[].class), org.mockito.Mockito.any()))
.thenReturn(successResult);
SecretsManagerService svc = new SecretsManagerService(
new InMemoryStorage<String, Secret>(), 30,
new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "000000000000"),
mockLambda, new com.fasterxml.jackson.databind.ObjectMapper());
svc.createSecret("my-secret", "value", null, null, null, null, REGION);
Secret.RotationRules rules = new Secret.RotationRules(30, null, null);
svc.rotateSecret("my-secret", "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"arn:aws:lambda:us-east-1:000000000000:function:rotate",
rules, false, REGION);
// Verify lambda invoked 1 time (testSecret only for non-immediate rotation)
org.mockito.Mockito.verify(mockLambda, org.mockito.Mockito.timeout(5000).times(1))
.invoke(org.mockito.Mockito.eq(REGION),
org.mockito.Mockito.eq("arn:aws:lambda:us-east-1:000000000000:function:rotate"),
org.mockito.Mockito.any(byte[].class),
org.mockito.Mockito.eq(io.github.hectorvent.floci.services.lambda.model.InvocationType.RequestResponse));
}
@Test
@@ -254,7 +306,7 @@ class SecretsManagerServiceTest {
@Test
void listSecretVersionIds() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, null);
service.putSecretValue("my-secret", "v2", null, null, REGION, null);
Map<String, List<String>> versions = service.listSecretVersionIds("my-secret", REGION);
assertEquals(2, versions.size());
@@ -270,7 +322,7 @@ class SecretsManagerServiceTest {
SecretVersion v1 = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION);
String v1Id = v1.getVersionId();
service.putSecretValue("my-secret", "v2", null, REGION, null);
service.putSecretValue("my-secret", "v2", null, null, REGION, null);
SecretVersion fetched = service.getSecretValue("my-secret", v1Id, null, REGION);
assertEquals("v1", fetched.getSecretString());
@@ -431,7 +483,7 @@ class SecretsManagerServiceTest {
@Test
void updateSecretVersionStageRemoveFromMustMatchCurrentVersion() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, null);
service.putSecretValue("my-secret", "v2", null, null, REGION, null);
String v1Id = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION).getVersionId();
String v2Id = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId();
@@ -452,7 +504,7 @@ class SecretsManagerServiceTest {
@Test
void updateSecretVersionStageMovesCustomLabel() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, List.of("AWSCURRENT", "MYSTAGE"));
service.putSecretValue("my-secret", "v2", null, null, REGION, List.of("AWSCURRENT", "MYSTAGE"));
String v1Id = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION).getVersionId();
String v2Id = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId();
@@ -469,7 +521,7 @@ class SecretsManagerServiceTest {
@Test
void updateSecretVersionStageMoveAwsCurrentAddsAwsPrevious() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, null);
service.putSecretValue("my-secret", "v2", null, null, REGION, null);
String v1Id = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION).getVersionId();
String v2Id = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId();
@@ -500,8 +552,8 @@ class SecretsManagerServiceTest {
@Test
void updateSecretVersionStageMoveAwsCurrentCleansUpPreviousFromMultiStageVersion() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, null);
service.putSecretValue("my-secret", "v3", null, REGION, null);
service.putSecretValue("my-secret", "v2", null, null, REGION, null);
service.putSecretValue("my-secret", "v3", null, null, REGION, null);
String v1Id = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId();
String v3Id = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId();
@@ -524,8 +576,8 @@ class SecretsManagerServiceTest {
@Test
void updateSecretVersionStageMoveAwsCurrentRemovesPreviousOnlyVersion() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
service.putSecretValue("my-secret", "v2", null, REGION, null);
service.putSecretValue("my-secret", "v3", null, REGION, null);
service.putSecretValue("my-secret", "v2", null, null, REGION, null);
service.putSecretValue("my-secret", "v3", null, null, REGION, null);
String v3Id = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId();
String v2Id = service.getSecretValue("my-secret", null, "AWSPREVIOUS", REGION).getVersionId();
@@ -541,7 +593,7 @@ class SecretsManagerServiceTest {
}
@Test
void updateSecretVersionStageRemovesLabelOnly() {
void rotateSecretRemovesAwsCurrentOnlyRemovesLabel() {
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
String v1Id = service.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId();
@@ -555,4 +607,169 @@ class SecretsManagerServiceTest {
assertFalse(v1After.getVersionStages().contains("CUSTOMLABEL"));
assertTrue(v1After.getVersionStages().contains("AWSCURRENT"));
}
@Test
void rotateSecretFailsEarly() throws Exception {
io.github.hectorvent.floci.services.lambda.LambdaService mockLambda = org.mockito.Mockito.mock(io.github.hectorvent.floci.services.lambda.LambdaService.class);
io.github.hectorvent.floci.services.lambda.model.InvokeResult successResult = new io.github.hectorvent.floci.services.lambda.model.InvokeResult();
io.github.hectorvent.floci.services.lambda.model.InvokeResult errorResult = new io.github.hectorvent.floci.services.lambda.model.InvokeResult();
errorResult.setFunctionError("Unhandled");
// Fail on second invocation (setSecret)
org.mockito.Mockito.when(mockLambda.invoke(org.mockito.Mockito.anyString(), org.mockito.Mockito.anyString(), org.mockito.Mockito.any(byte[].class), org.mockito.Mockito.any()))
.thenReturn(successResult)
.thenReturn(errorResult);
SecretsManagerService svc = new SecretsManagerService(
new InMemoryStorage<String, Secret>(), 30,
new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "000000000000"),
mockLambda, new com.fasterxml.jackson.databind.ObjectMapper());
svc.createSecret("my-secret", "value", null, null, null, null, REGION);
Secret.RotationRules rules = new Secret.RotationRules(30, null, null);
svc.rotateSecret("my-secret", "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"arn:aws:lambda:us-east-1:000000000000:function:rotate",
rules, true, REGION);
// Verify lambda invoked 2 times only (createSecret, setSecret)
org.mockito.Mockito.verify(mockLambda, org.mockito.Mockito.timeout(5000).times(2))
.invoke(org.mockito.Mockito.eq(REGION),
org.mockito.Mockito.eq("arn:aws:lambda:us-east-1:000000000000:function:rotate"),
org.mockito.Mockito.any(byte[].class),
org.mockito.Mockito.eq(io.github.hectorvent.floci.services.lambda.model.InvocationType.RequestResponse));
}
@Test
void rotateSecret_actuallyChangesTheStoredSecretValue() throws Exception {
io.github.hectorvent.floci.services.lambda.LambdaService mockLambda = org.mockito.Mockito.mock(io.github.hectorvent.floci.services.lambda.LambdaService.class);
String lambdaArn = "arn:aws:lambda:us-east-1:000000000000:function:rotate";
SecretsManagerService svc = new SecretsManagerService(
new InMemoryStorage<String, Secret>(), 30,
new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "000000000000"),
mockLambda, new com.fasterxml.jackson.databind.ObjectMapper());
svc.createSecret("my-secret", "old-value", null, null, null, null, REGION);
org.mockito.Mockito.when(mockLambda.invoke(org.mockito.Mockito.anyString(), org.mockito.Mockito.anyString(), org.mockito.Mockito.any(byte[].class), org.mockito.Mockito.any()))
.thenAnswer(invocation -> {
byte[] payloadBytes = invocation.getArgument(2);
com.fasterxml.jackson.databind.JsonNode payload = new com.fasterxml.jackson.databind.ObjectMapper().readTree(payloadBytes);
String step = payload.get("Step").asText();
String token = payload.get("ClientRequestToken").asText();
switch (step) {
case "createSecret" ->
svc.putSecretValue("my-secret", "new-rotated-value", null, token, REGION, List.of("AWSPENDING"));
case "finishSecret" ->
svc.updateSecretVersionStage("my-secret", token,
svc.getSecretValue("my-secret", null, "AWSCURRENT", REGION).getVersionId(),
"AWSCURRENT", REGION);
default -> { /* setSecret, testSecret: no-op for this test */ }
}
io.github.hectorvent.floci.services.lambda.model.InvokeResult ok = new io.github.hectorvent.floci.services.lambda.model.InvokeResult();
ok.setStatusCode(200);
return ok;
});
svc.rotateSecret("my-secret", "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
lambdaArn, null, true, REGION);
long end = System.currentTimeMillis() + 2000;
boolean passed = false;
while (System.currentTimeMillis() < end) {
try {
SecretVersion current = svc.getSecretValue("my-secret", null, "AWSCURRENT", REGION);
assertEquals("new-rotated-value", current.getSecretString());
passed = true;
break;
} catch (Throwable t) {
Thread.sleep(100);
}
}
assertTrue(passed, "Failed to wait for rotation completion");
}
@Test
void rotateSecret_previousRotationInProgressThrows() throws Exception {
io.github.hectorvent.floci.services.lambda.LambdaService mockLambda = org.mockito.Mockito.mock(io.github.hectorvent.floci.services.lambda.LambdaService.class);
String lambdaArn = "arn:aws:lambda:us-east-1:000000000000:function:rotate";
SecretsManagerService svc = new SecretsManagerService(
new InMemoryStorage<String, Secret>(), 30,
new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "000000000000"),
mockLambda, new com.fasterxml.jackson.databind.ObjectMapper());
svc.createSecret("my-secret", "old-value", null, null, null, null, REGION);
// Put an AWSPENDING version to simulate an ongoing rotation
svc.putSecretValue("my-secret", "pending-value", null, "a1b2c3d4-e5f6-7890-abcd-ef1234567890", REGION, List.of("AWSPENDING"));
AwsException ex = assertThrows(AwsException.class, () ->
svc.rotateSecret("my-secret", "b1b2c3d4-e5f6-7890-abcd-ef1234567890",
lambdaArn, null, true, REGION)
);
assertEquals("InvalidRequestException", ex.getErrorCode());
}
@Test
void rotateSecret_concurrentCallsLockingWorks() throws Exception {
io.github.hectorvent.floci.services.lambda.LambdaService mockLambda = org.mockito.Mockito.mock(io.github.hectorvent.floci.services.lambda.LambdaService.class);
String lambdaArn = "arn:aws:lambda:us-east-1:000000000000:function:rotate";
SecretsManagerService svc = new SecretsManagerService(
new InMemoryStorage<String, Secret>(), 30,
new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "000000000000"),
mockLambda, new com.fasterxml.jackson.databind.ObjectMapper());
svc.createSecret("my-secret", "old-value", null, null, null, null, REGION);
java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1);
org.mockito.Mockito.when(mockLambda.invoke(org.mockito.Mockito.anyString(), org.mockito.Mockito.anyString(), org.mockito.Mockito.any(byte[].class), org.mockito.Mockito.any()))
.thenAnswer(invocation -> {
// Create secret and hold the lock on executor to simulate delay
byte[] payloadBytes = invocation.getArgument(2);
com.fasterxml.jackson.databind.JsonNode payload = new com.fasterxml.jackson.databind.ObjectMapper().readTree(payloadBytes);
String step = payload.get("Step").asText();
String token = payload.get("ClientRequestToken").asText();
if ("createSecret".equals(step)) {
svc.putSecretValue("my-secret", "new-rotated-value", null, token, REGION, List.of("AWSPENDING"));
latch.await();
}
io.github.hectorvent.floci.services.lambda.model.InvokeResult ok = new io.github.hectorvent.floci.services.lambda.model.InvokeResult();
ok.setStatusCode(200);
return ok;
});
// Trigger first rotation
svc.rotateSecret("my-secret", "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
lambdaArn, null, true, REGION);
// Wait until AWSPENDING is set by the background thread
long end = System.currentTimeMillis() + 2000;
boolean pendingFound = false;
while (System.currentTimeMillis() < end) {
try {
svc.getSecretValue("my-secret", null, "AWSPENDING", REGION);
pendingFound = true;
break;
} catch (Exception e) {
Thread.sleep(100);
}
}
assertTrue(pendingFound, "AWSPENDING version was not created in time");
// Trigger second rotation while the first one is running and holds AWSPENDING
AwsException ex = assertThrows(AwsException.class, () ->
svc.rotateSecret("my-secret", "b1b2c3d4-e5f6-7890-abcd-ef1234567890",
lambdaArn, null, true, REGION)
);
assertEquals("InvalidRequestException", ex.getErrorCode());
latch.countDown();
}
}