Light, fluffy, and always free - The AWS Local Emulator alternative
fix(secretsmanager): require lambda:InvokeFunction for RotateSecret under IAM enforcement (#4697)
Priamo Germosena075e2529059
diff --git a/docs/services/secrets-manager.md b/docs/services/secrets-manager.mdindex b661fc9445..3c603744c1 100644--- a/docs/services/secrets-manager.md+++ b/docs/services/secrets-manager.md@@ -137,6 +137,13 @@ aws secretsmanager validate-resource-policy \- **Rotation schedules fire.** A background sweep (see the config table) rotates any secret whose`NextRotationDate` has passed. `AutomaticallyAfterDays`, `rate()` and `cron()` are all honoured.+- **`RotateSecret` also needs `lambda:InvokeFunction` under IAM enforcement.** As on AWS, the caller+ must be allowed to invoke the rotation function as well as to call `RotateSecret`. A caller that+ is not gets `AccessDeniedException` with HTTP 400, as Secrets Manager reports it, and the secret is+ left as it was. Rotations started by the background sweep have no caller and are not checked.+- **A rotation function that does not exist** is reported as AWS reports it: `AccessDeniedException`+ (HTTP 400), "Secrets Manager cannot invoke the specified Lambda function". The secret's rotation+ settings are left as they were, including any rotation function configured before.- **Replication is synchronous.** Real AWS reports `InProgress` first; floci copies the secretimmediately, so a replica is `InSync` by the time the call returns. Replicas are read-only andtrack later writes to the primary.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.javaindex 0653a7c81a..6f54535c64 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java@@ -67,6 +67,7 @@ import jakarta.ws.rs.*;import jakarta.ws.rs.core.Context;import jakarta.ws.rs.core.HttpHeaders;import jakarta.ws.rs.core.Response;+import jakarta.ws.rs.core.UriInfo;import org.jboss.logging.Logger;/**@@ -271,6 +272,7 @@ public class AwsJson11Controller {public Response handle(@HeaderParam("X-Amz-Target") String target,@Context HttpHeaders httpHeaders,+ @Context UriInfo uriInfo,String body) {if (target == null) {@@ -313,7 +315,9 @@ public class AwsJson11Controller {case "wafv2" -> wafV2Handler.handle(action, request, region);case "memorydb" -> memoryDbHandler.handle(action, request, region);case "logs" -> cloudWatchLogsHandler.handle(action, request, region);- case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region);+ case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region,+ IamEnforcementFilter.requestAuthorization(+ httpHeaders.getHeaderString("Authorization"), uriInfo.getQueryParameters()));case "kinesis" -> kinesisJsonHandler.handle(action, request, region);case "kinesisanalytics" -> kinesisAnalyticsV2JsonHandler.handle(action, request, region);case "apigatewayv2" -> apigwV2JsonHandler.handle(action, request, region);diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex 2cb25f7ab9..b3f3ea7f82 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java@@ -24,6 +24,7 @@ import jakarta.ws.rs.container.ContainerRequestFilter;import jakarta.ws.rs.container.ResourceInfo;import jakarta.ws.rs.core.Context;import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.MultivaluedMap;import jakarta.ws.rs.core.Response;import jakarta.ws.rs.ext.Provider;import org.jboss.logging.Logger;@@ -255,7 +256,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {String auth = ctx.getHeaderString("Authorization");if (auth == null) {- auth = presignedCredentialAsAuthorization(ctx);+ auth = requestAuthorization(null, ctx.getUriInfo().getQueryParameters());}if (auth == null) {refuseUnsignedManagementCall(ctx);@@ -908,9 +909,20 @@ public class IamEnforcementFilter implements ContainerRequestFilter {* same way for the same reason. Synthesizing a {@code Credential=...} string from the query* parameter lets every downstream step here - access key extraction, credential scope,* action resolution, resource ARNs - run unchanged for both signing styles.+ *+ * <p>Public so that a handler authorizing a secondary resource through+ * {@link #authorizeAdditionalResource} hands it the same caller this filter evaluated, whichever+ * way the request was signed.+ *+ * @return the {@code Authorization} header, else a {@code Credential=...} string built from+ * {@code X-Amz-Credential}, else {@code null}*/- private static String presignedCredentialAsAuthorization(ContainerRequestContext ctx) {- String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");+ public static String requestAuthorization(String authorizationHeader,+ MultivaluedMap<String, String> queryParameters) {+ if (authorizationHeader != null) {+ return authorizationHeader;+ }+ String credential = queryParameters == null ? null : queryParameters.getFirst("X-Amz-Credential");return credential == null || credential.isBlank() ? null : "Credential=" + credential;}diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.javaindex 4ef88ac6d9..04264b2b78 100644--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java@@ -1,14 +1,15 @@package io.github.hectorvent.floci.services.secretsmanager;-import io.github.hectorvent.floci.core.common.AwsErrorResponse;-import io.github.hectorvent.floci.core.common.AwsException;-import io.github.hectorvent.floci.services.secretsmanager.model.Secret;-import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;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.services.secretsmanager.model.Secret;+import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import jakarta.ws.rs.core.Response;@@ -33,14 +34,31 @@ public class SecretsManagerJsonHandler {private final SecretsManagerService service;private final ObjectMapper objectMapper;+ private final IamEnforcementFilter iamEnforcementFilter;@Inject- public SecretsManagerJsonHandler(SecretsManagerService service, ObjectMapper objectMapper) {+ public SecretsManagerJsonHandler(SecretsManagerService service, ObjectMapper objectMapper,+ IamEnforcementFilter iamEnforcementFilter) {this.service = service;this.objectMapper = objectMapper;+ this.iamEnforcementFilter = iamEnforcementFilter;}+ /**+ * Handles a request that carries no caller credential of its own, such as an API Gateway+ * service integration. Checks that authorize the caller for a second resource have no caller to+ * authorize here, so they are skipped, as {@link IamEnforcementFilter} skips unsigned requests.+ */public Response handle(String action, JsonNode request, String region) {+ return handle(action, request, region, null);+ }++ /**+ * @param authorization the caller's credential as {@link IamEnforcementFilter#requestAuthorization}+ * reads it, used where an operation authorizes the caller for a second+ * resource+ */+ public Response handle(String action, JsonNode request, String region, String authorization) {return switch (action) {case "CreateSecret" -> handleCreateSecret(request, region);case "GetSecretValue" -> handleGetSecretValue(request, region);@@ -50,7 +68,7 @@ public class SecretsManagerJsonHandler {case "ListSecrets" -> handleListSecrets(request, region);case "DeleteSecret" -> handleDeleteSecret(request, region);case "RestoreSecret" -> handleRestoreSecret(request, region);- case "RotateSecret" -> handleRotateSecret(request, region);+ case "RotateSecret" -> handleRotateSecret(request, region, authorization);case "CancelRotateSecret" -> handleCancelRotateSecret(request, region);case "TagResource" -> handleTagResource(request, region);case "UntagResource" -> handleUntagResource(request, region);@@ -613,7 +631,7 @@ public class SecretsManagerJsonHandler {return Response.ok(response).build();}- private Response handleRotateSecret(JsonNode request, String region) {+ private Response handleRotateSecret(JsonNode request, String region, String authorization) {String secretId = request.path("SecretId").asText();String clientRequestToken = request.has("ClientRequestToken") ? request.path("ClientRequestToken").asText() : UUID.randomUUID().toString();@@ -638,7 +656,8 @@ public class SecretsManagerJsonHandler {rotationRules = new Secret.RotationRules(automaticallyAfterDays, duration, scheduleExpression);}- Secret secret = service.rotateSecret(secretId, clientRequestToken, lambdaArn, rotationRules, rotateImmediately, region);+ Secret secret = service.rotateSecret(secretId, clientRequestToken, lambdaArn, rotationRules, rotateImmediately,+ region, functionArn -> authorizeRotationInvoke(authorization, functionArn));ObjectNode response = objectMapper.createObjectNode();response.put("ARN", secret.getArn());@@ -651,6 +670,24 @@ public class SecretsManagerJsonHandler {return Response.ok(response).build();}+ /**+ * RotateSecret also needs {@code lambda:InvokeFunction} on the rotation function (Secrets Manager+ * API Reference, RotateSecret, "Required permissions"). The filter has already authorized+ * {@code secretsmanager:RotateSecret}; this authorizes the invoke for the same caller. The filter+ * reports a denial as S3's {@code AccessDenied}, so it is raised here the way Secrets Manager+ * reports one: {@code AccessDeniedException} with HTTP 400 (API Reference, "Common Errors").+ */+ private void authorizeRotationInvoke(String authorization, String functionArn) {+ try {+ iamEnforcementFilter.authorizeAdditionalResource(authorization, "lambda:InvokeFunction", functionArn);+ } catch (AwsException e) {+ if (!"AccessDenied".equals(e.getErrorCode())) {+ throw e;+ }+ throw new AwsException("AccessDeniedException", e.getMessage(), 400);+ }+ }+private Response handleCancelRotateSecret(JsonNode request, String region) {String secretId = request.path("SecretId").asText();// A service-managed secret is rotated by its owning service, so rotation can't be turneddiff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.javaindex e36d270845..388ab12090 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@@ -43,6 +43,7 @@ import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;import java.util.LinkedHashMap;import java.util.Set;+import java.util.function.Consumer;import java.util.regex.Pattern;@ApplicationScoped@@ -1088,8 +1089,23 @@ public class SecretsManagerService implements ResourceProvider {return secret;}+ /**+ * Rotation started by Floci itself, such as the scheduled sweep, with no caller to authorize.+ */public Secret rotateSecret(String secretId, String clientRequestToken, String rotationLambdaArn, Secret.RotationRules rotationRules,boolean rotateImmediately, String region) {+ return rotateSecret(secretId, clientRequestToken, rotationLambdaArn, rotationRules, rotateImmediately, region,+ functionArn -> { });+ }++ /**+ * @param authorizeInvoke called with the full ARN of the rotation function this call will+ * invoke, before the function is looked up or the secret changed, so the+ * caller can be refused {@code lambda:InvokeFunction} on exactly that+ * function+ */+ public Secret rotateSecret(String secretId, String clientRequestToken, String rotationLambdaArn, Secret.RotationRules rotationRules,+ boolean rotateImmediately, String region, Consumer<String> authorizeInvoke) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);throwIfReplica(secret);@@ -1118,14 +1134,24 @@ public class SecretsManagerService implements ResourceProvider {"You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and you didn't include such an ARN as a parameter in this call.", 400);}- // Validate Lambda exists synchronously+ // One full ARN for the permission check, the lookup and the invoke, so all three reach the same+ // function: a name or partial ARN would otherwise be invoked in whatever account the rotation+ // thread resolves, which is not necessarily the one that was checked.+ String functionArn = serviceManaged ? null : rotationFunctionArn(finalLambdaArn, secret, region);+ if (!serviceManaged) {+ authorizeInvoke.accept(functionArn);+ }++ // A function that cannot be invoked is reported the way AWS reports it, whatever the reason:+ // AccessDeniedException with HTTP 400, and the secret left as it was.if (!serviceManaged && lambdaService != null) {try {- lambdaService.getFunction(region, finalLambdaArn);+ lambdaService.getFunction(region, functionArn);} catch (AwsException e) {if (e.getHttpStatus() == 404) {- throw new AwsException("ResourceNotFoundException",- "Secrets Manager cannot find the specified Lambda function.", 404);+ throw new AwsException("AccessDeniedException",+ "Secrets Manager cannot invoke the specified Lambda function. Ensure that the function "+ + "policy grants access to the principal secretsmanager.amazonaws.com.", 400); // partition-literal: AWS's error text verbatim; names the service principal, which the Secrets Manager guide gives with no partition variant}throw e;}@@ -1172,7 +1198,7 @@ public class SecretsManagerService implements ResourceProvider {rotationExecutor.submit(() -> {try {- executeRotationLifecycle(arn, finalToken, finalLambdaArn, rotateImmediately, isExistingVersion, region);+ executeRotationLifecycle(arn, finalToken, functionArn, rotateImmediately, isExistingVersion, region);} catch (Exception e) {LOG.errorv(e, "Rotation lifecycle failed for secret {0}", arn);}@@ -1183,6 +1209,23 @@ public class SecretsManagerService implements ResourceProvider {}+ /**+ * The rotation function as the full ARN an IAM policy's {@code Resource} names. A function name+ * or partial ARN resolves in the secret's own account and the request's Region, as Lambda+ * resolves one.+ */+ static String rotationFunctionArn(String functionRef, Secret secret, String region) {+ if (functionRef.startsWith("arn:")) {+ return functionRef;+ }+ AwsArnUtils.Arn secretArn = AwsArnUtils.parse(secret.getArn());+ if (functionRef.contains(":function:")) {+ return "arn:" + secretArn.partition() + ":lambda:" + region + ":" + functionRef;+ }+ return new AwsArnUtils.Arn(secretArn.partition(), "lambda", region, secretArn.accountId(),+ "function:" + functionRef).toString();+ }+/*** The outcome of {@link #cancelRotateSecret}: the secret with rotation turned off, plus the id* of the version a cancelled rotation left behind, or {@code null} when no rotation was indiff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.javaindex 792ee5b16a..45f5cb1907 100644--- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java@@ -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 {@BeforeEachvoid 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) {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.javanew file mode 100644index 0000000000..cb0f7ff609--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java@@ -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";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationTest.javanew file mode 100644index 0000000000..89dcc31ff1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationTest.java@@ -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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationLockTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationLockTest.javaindex 30269f657a..00d3ae9ad2 100644--- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationLockTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationLockTest.java@@ -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,