fix(secretsmanager): require lambda:InvokeFunction for RotateSecret under IAM enforcement (#4697)

AWS requires the caller of RotateSecret to hold lambda:InvokeFunction on the rotation function as
well as secretsmanager:RotateSecret (Secrets Manager API Reference, RotateSecret, "Required
permissions"). Floci checked only RotateSecret and then invoked the function in-process, so under
IAM enforcement a caller refused lambda:InvokeFunction could still run any function it could name by
configuring it as a rotation function.

RotateSecret now authorizes the invoke for the same caller the filter evaluated, against the exact
function the rotation will run (the requested ARN, or the one already configured, with a bare name
or partial ARN resolved in the secret's account and Region), and the rotation then invokes that same
full ARN. Invoking the reference as given would let a name or partial ARN resolve in whatever account
the rotation thread sees, so the function checked and the function run could differ. The check runs
before the function is
looked up or the secret changed, so a refused call leaves nothing configured for the scheduled sweep
to invoke later. A refusal is reported as Secrets Manager reports one: AccessDeniedException with
HTTP 400 (API Reference, "Common Errors").

A rotation function that does not exist is now reported the way AWS reports it too:
AccessDeniedException, HTTP 400, "Secrets Manager cannot invoke the specified Lambda function. Ensure
that the function policy grants access to the principal secretsmanager.amazonaws.com.", with the
secret's rotation settings left as they were. It used to be ResourceNotFoundException with HTTP 404.

The caller credential reaches the handler through IamEnforcementFilter.requestAuthorization, the
filter's own header-or-presigned logic, so a presigned request is checked the same way. Requests
with no caller credential, such as API Gateway service integrations, and rotations started by the
scheduled sweep are unchanged. With IAM enforcement off the caller check does not run; the
missing-function response above applies either way.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-29 18:54:38 -05:00
1 parent 7ff6a7cfa7
commit a075e25290
9 files changed
+467 -19

No files matched your search

@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.IamEnforcementFilter;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
@@ -17,6 +18,7 @@ import java.util.function.Consumer;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
class SecretsManagerJsonHandlerTest {
@@ -29,7 +31,7 @@ class SecretsManagerJsonHandlerTest {
@BeforeEach
void setUp() {
service = new SecretsManagerService(new InMemoryStorage<>(), 30);
handler = new SecretsManagerJsonHandler(service, MAPPER);
handler = new SecretsManagerJsonHandler(service, MAPPER, mock(IamEnforcementFilter.class));
}
private String getRandomPassword(ObjectNode request) {
@@ -0,0 +1,191 @@
package io.github.hectorvent.floci.services.secretsmanager;
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.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
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.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
/**
* RotateSecret needs the caller to hold {@code lambda:InvokeFunction} on the rotation function
* as well as {@code secretsmanager:RotateSecret} (Secrets Manager API Reference, RotateSecret,
* "Required permissions").
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class SecretsManagerRotationInvokeAuthorizationIntegrationTest {
private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ACCOUNT_ID = "111122223333";
private static final String REGION = "us-east-1";
private static final DateTimeFormatter AMZ_DATE_FMT =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
@InjectMock
LambdaService lambdaService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void stubLambda() {
Mockito.when(lambdaService.getFunction(anyString(), anyString())).thenReturn(new LambdaFunction());
InvokeResult ok = new InvokeResult();
ok.setStatusCode(200);
Mockito.when(lambdaService.invoke(any(), any(), any(), any())).thenReturn(ok);
}
@Test
void rotateSecretIsDeniedWhenCallerCannotInvokeTheRotationFunction() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String functionArn = "arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:rotator-" + suffix;
String accessKeyId = createUserWithPolicy("sm-only-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"secretsmanager:*","Resource":"*"}]}""");
String secretName = "rotate-denied-" + suffix;
secretsManager(accessKeyId, "CreateSecret",
"{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200);
secretsManager(accessKeyId, "RotateSecret",
"{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + "\"}")
.statusCode(400)
.body("__type", equalTo("AccessDeniedException"));
Mockito.verify(lambdaService, Mockito.never()).invoke(any(), eq(functionArn), any(), any());
}
@Test
void presignedRotateSecretIsCheckedLikeASignedOne() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String functionArn = "arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:rotator-" + suffix;
String accessKeyId = createUserWithPolicy("sm-presigned-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"secretsmanager:*","Resource":"*"}]}""");
String secretName = "rotate-presigned-" + suffix;
secretsManager(accessKeyId, "CreateSecret",
"{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200);
String amzDate = AMZ_DATE_FMT.format(Instant.now());
given()
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
.queryParam("X-Amz-Credential",
accessKeyId + "/" + amzDate.substring(0, 8) + "/" + REGION + "/secretsmanager/aws4_request")
.queryParam("X-Amz-Date", amzDate)
.queryParam("X-Amz-Expires", "3600")
.queryParam("X-Amz-SignedHeaders", "host")
.queryParam("X-Amz-Signature", "abc")
.header("X-Amz-Target", "secretsmanager.RotateSecret")
.contentType(SM_CONTENT_TYPE)
.body("{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AccessDeniedException"));
Mockito.verify(lambdaService, Mockito.never()).invoke(any(), eq(functionArn), any(), any());
}
@Test
void functionNamedByNameIsCheckedAsItsArn() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String functionName = "rotator-" + suffix;
String functionArn = "arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:" + functionName;
String accessKeyId = createUserWithPolicy("sm-by-name-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"secretsmanager:*","Resource":"*"},
{"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"%s"}]}"""
.formatted(functionArn));
String secretName = "rotate-by-name-" + suffix;
secretsManager(accessKeyId, "CreateSecret",
"{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200);
secretsManager(accessKeyId, "RotateSecret",
"{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionName + "\"}")
.statusCode(200);
Mockito.verify(lambdaService, Mockito.timeout(5000).atLeastOnce())
.invoke(any(), eq(functionArn), any(), any());
}
@Test
void rotateSecretProceedsWhenCallerCanInvokeTheRotationFunction() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String functionArn = "arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:rotator-" + suffix;
String accessKeyId = createUserWithPolicy("sm-and-invoke-" + suffix, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"secretsmanager:*","Resource":"*"},
{"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"%s"}]}"""
.formatted(functionArn));
String secretName = "rotate-allowed-" + suffix;
secretsManager(accessKeyId, "CreateSecret",
"{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200);
secretsManager(accessKeyId, "RotateSecret",
"{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + "\"}")
.statusCode(200);
Mockito.verify(lambdaService, Mockito.timeout(5000).atLeastOnce())
.invoke(any(), eq(functionArn), any(), any());
}
private static ValidatableResponse secretsManager(String accessKeyId, String operation, String body) {
return given()
.header("Authorization", authorization(accessKeyId, "secretsmanager"))
.header("X-Amz-Target", "secretsmanager." + operation)
.contentType(SM_CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then();
}
private static String createUserWithPolicy(String userName, String policyDocument) {
adminIam("CreateUser", 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))
.statusCode(200)
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
}
private static ValidatableResponse adminIam(String action, Map<String, String> params) {
RequestSpecification spec = given()
.header("Authorization", authorization(ACCOUNT_ID, "iam"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-05-08");
params.forEach(spec::formParam);
return spec.when().post("/").then();
}
private static String authorization(String accessKeyId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260929/" + REGION + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -0,0 +1,150 @@
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;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The hook RotateSecret uses to refuse a caller {@code lambda:InvokeFunction} on the rotation
* function (Secrets Manager API Reference, RotateSecret, "Required permissions").
*/
class SecretsManagerRotationInvokeAuthorizationTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String TOKEN = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:rotator";
private InMemoryStorage<String, Secret> store;
private LambdaService lambda;
private SecretsManagerService service;
@BeforeEach
void setUp() {
store = new InMemoryStorage<>();
lambda = mock(LambdaService.class);
when(lambda.getFunction(anyString(), anyString())).thenReturn(new LambdaFunction());
when(lambda.invoke(anyString(), anyString(), any(byte[].class), any())).thenReturn(new InvokeResult());
service = new SecretsManagerService(store, 30, new RegionResolver(REGION, ACCOUNT), lambda, new ObjectMapper());
service.createSecret("my-secret", "v1", null, null, null, null, REGION);
}
@ParameterizedTest
@CsvSource({
"rotator, arn:aws:lambda:us-east-1:000000000000:function:rotator",
"rotator:live, arn:aws:lambda:us-east-1:000000000000:function:rotator:live",
"111122223333:function:rotator, arn:aws:lambda:us-east-1:111122223333:function:rotator",
"arn:aws:lambda:us-east-1:111122223333:function:rotator, arn:aws:lambda:us-east-1:111122223333:function:rotator"
})
void checkAndInvokeUseTheSameFullArn(String given, String expected) {
List<String> checked = new ArrayList<>();
service.rotateSecret("my-secret", TOKEN, given, null, false, REGION, checked::add);
assertEquals(List.of(expected), checked);
// Invoked by that ARN, not by the reference as given: Lambda resolves a name or partial ARN
// in the ambient account, which on the rotation thread is not the one that was checked.
verify(lambda, timeout(5000).atLeastOnce()).invoke(eq(REGION), eq(expected), any(byte[].class), any());
}
@Test
void refusedCallerLeavesTheSecretUntouchedAndNothingRuns() {
Consumer<String> refuse = functionArn -> {
throw new AwsException("AccessDeniedException", "refused by the caller check", 400);
};
AwsException e = assertThrows(AwsException.class, () ->
service.rotateSecret("my-secret", TOKEN, FUNCTION_ARN, new Secret.RotationRules(7, null, null),
true, REGION, refuse));
assertEquals("AccessDeniedException", e.getErrorCode());
Secret secret = service.describeSecret("my-secret", REGION);
// A refused call must not leave the function configured: the scheduled sweep would
// otherwise invoke it later with no caller left to check.
assertNull(secret.getRotationLambdaArn());
assertFalse(secret.isRotationEnabled());
assertNull(secret.getNextRotationDate());
verify(lambda, never()).invoke(anyString(), anyString(), any(byte[].class), any());
}
@Test
void refusalComesBeforeTheExistenceCheck() {
when(lambda.getFunction(anyString(), anyString()))
.thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404));
Consumer<String> refuse = functionArn -> {
throw new AwsException("AccessDeniedException", "refused by the caller check", 400);
};
AwsException e = assertThrows(AwsException.class, () ->
service.rotateSecret("my-secret", TOKEN, FUNCTION_ARN, null, true, REGION, refuse));
assertEquals("refused by the caller check", e.getMessage());
}
@Test
void missingFunctionIsReportedAsSecretsManagerReportsIt() {
when(lambda.getFunction(anyString(), anyString()))
.thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404));
AwsException e = assertThrows(AwsException.class, () ->
service.rotateSecret("my-secret", TOKEN, FUNCTION_ARN, null, true, REGION, functionArn -> { }));
assertEquals("AccessDeniedException", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
assertEquals("Secrets Manager cannot invoke the specified Lambda function. Ensure that the function "
+ "policy grants access to the principal secretsmanager.amazonaws.com.", e.getMessage());
assertNull(service.describeSecret("my-secret", REGION).getRotationLambdaArn());
}
@Test
void missingFunctionLeavesThePreviouslyConfiguredFunctionInPlace() {
Secret secret = service.describeSecret("my-secret", REGION);
secret.setRotationLambdaArn(FUNCTION_ARN);
store.put(REGION + "::my-secret", secret);
when(lambda.getFunction(anyString(), anyString()))
.thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404));
assertThrows(AwsException.class, () -> service.rotateSecret("my-secret", TOKEN,
"arn:aws:lambda:us-east-1:000000000000:function:missing", null, true, REGION, functionArn -> { }));
assertEquals(FUNCTION_ARN, service.describeSecret("my-secret", REGION).getRotationLambdaArn());
}
@Test
void rotationWithoutAnArnChecksTheConfiguredFunction() {
Secret secret = service.describeSecret("my-secret", REGION);
secret.setRotationLambdaArn(FUNCTION_ARN);
store.put(REGION + "::my-secret", secret);
List<String> checked = new ArrayList<>();
service.rotateSecret("my-secret", TOKEN, null, null, false, REGION, checked::add);
assertEquals(List.of(FUNCTION_ARN), checked);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.secretsmanager;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.IamEnforcementFilter;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.lambda.LambdaService;
@@ -157,7 +158,8 @@ class SecretsManagerRotationLockTest {
// A rotation adds its AWSPENDING version from the rotation executor while a request thread
// is building DescribeSecret's VersionIdsToStages from the same map. Park the reader one
// entry into that iteration, add the version, and let the reader continue.
SecretsManagerJsonHandler handler = new SecretsManagerJsonHandler(service, new ObjectMapper());
SecretsManagerJsonHandler handler = new SecretsManagerJsonHandler(service, new ObjectMapper(),
mock(IamEnforcementFilter.class));
ParkingIterationVersions versions = new ParkingIterationVersions(secret.getVersions());
secret.setVersions(versions);
assertTrue(secret.getVersions() instanceof ConcurrentMap,