diff --git a/docs/services/iam.md b/docs/services/iam.md index 9e9221cd78..d96f10e2d3 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -989,6 +989,7 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active, Floci also queries regi - An explicit **Deny** in a resource policy overrides any allows. - In cross-account scenarios or resource-controlled access, an explicit **Allow** in a resource policy grants access to the principal. - For detailed S3 bucket policy behavior and configuration, see [S3 Bucket Policy Enforcement](s3.md#bucket-policy-enforcement). +- Lambda function policies, the statements `AddPermission` adds, take part the same way. An invoke of another account's function by ARN runs it in that account, so its function policy has to allow the caller as well; see [Function policies under IAM enforcement](lambda.md#function-policies-under-iam-enforcement). ### Service control policies (SCPs) @@ -1201,9 +1202,8 @@ being bounded by SCPs (below): both forms of root enforcement now agree. A negat absent key cannot equal what the policy names, so the condition holds, and a `Deny` written that way applies when the key is missing. -**Not yet supported**: `NotPrincipal`, resource-based policies (S3 bucket policy, Lambda resource -policy), and `dynamodb:LeadingKeys` for `Scan`, `TransactWriteItems` / `TransactGetItems` and the -PartiQL operations. +**Not yet supported**: `dynamodb:LeadingKeys` for `Scan`, `TransactWriteItems` / `TransactGetItems` +and the PartiQL operations. ### Assumed roles diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 43c088e4d5..893c55fe7d 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -73,6 +73,29 @@ The event invoke configuration is stored and returned as AWS does, and `AWS::Lam provisions it from a stack. Asynchronous invocations apply its retry, event age, destination settings, and dead-letter queue configurations (`DeadLetterConfig`). +### Function policies under IAM enforcement + +With [IAM enforcement](iam.md#resource-based-policies) on, the statements `AddPermission` adds take +part in authorizing calls to the function: + +- An invoke of a function named by a full or partial ARN runs the function in the account in the + ARN. An invoke of another account's function needs its function policy to allow the caller as + well as the caller's own identity policy. +- `GetFunction`, `GetFunctionConfiguration` and `ListDurableExecutionsByFunction`, given a full ARN + with a version or alias, read the function in the account in the ARN, and need its function + policy to allow the caller in the same way. +- Other operations act on the caller's own function of the name the ARN gives, whatever account + the ARN names, and are authorized against that function. Floci does not serve them on another + account's function, which AWS allows through a function policy. +- Within one account, a statement naming the caller grants on its own. +- An invoke is authorized against the version or alias it names, in the function name or in + `Qualifier`. A grant added with `Qualifier` covers that version or alias only, and a grant on the + function does not cover a qualified invoke. Other operations are authorized against the + unqualified function. +- A statement conditioned on `InvokedViaFunctionUrl` does not admit a direct `Invoke`. +- `aws:PrincipalOrgID` is not part of the request context, so a grant added with `PrincipalOrgID` + admits no caller. + ### Reserved Concurrency Unqualified `GetFunction` reads include `Concurrency.ReservedConcurrentExecutions` when a reservation diff --git a/docs/services/secrets-manager.md b/docs/services/secrets-manager.md index 42bc96724d..9382fd6d82 100644 --- a/docs/services/secrets-manager.md +++ b/docs/services/secrets-manager.md @@ -140,10 +140,14 @@ aws secretsmanager validate-resource-policy \ - **`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. + left as it was. A function in another account is checked as any cross-account call is: its + function policy must allow the caller too. 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. + (HTTP 400), "Secrets Manager cannot invoke the specified Lambda function". The function is looked + up where the rotation runs it, in the account its ARN names and as the version or alias the ARN + names, so a missing alias is reported the same way. The secret's rotation settings are left as + they were, including any rotation function configured before. - **A rotation function reference Lambda refuses**, one it cannot parse or a full ARN in another Region, gets `InvalidParameterException` (HTTP 400), the error `RotateSecret` declares for an invalid parameter, with Lambda's reason in the message. The secret is left as it was. AWS does not diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 1322b80a17..7e7e579af3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.ServicePrincipals; @@ -78,7 +79,7 @@ public class ResourceArnBuilder { String path = ctx.getUriInfo().getPath(); return switch (credentialScope) { case "s3" -> List.of(buildS3Arn(path, region)); - case "lambda" -> List.of(buildLambdaArn(path, region, accountId)); + case "lambda" -> List.of(buildLambdaArn(path, ctx, region, accountId)); case "sqs" -> List.of(buildSqsArn(ctx, region, accountId)); case "sns" -> List.of(buildSnsArn(ctx, region, accountId)); case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId); @@ -541,7 +542,19 @@ public class ResourceArnBuilder { } // ── Lambda ────────────────────────────────────────────────────────────────── - private String buildLambdaArn(String path, String region, String accountId) { + + /** + * The function a Lambda request acts on, as an IAM policy names it. An invoke runs the function + * in the account and Region its full or partial ARN names, so it is evaluated against that + * function, and against the version or alias it names in the function name or in + * {@code Qualifier}, since Lambda authorizes a qualified call against the qualified ARN (Lambda + * Developer Guide, "Referencing functions in the Resource section of policies"). The reads + * {@link #readsInTheAccountItNames} names act in the account a qualified ARN names too. Every + * other route acts on the caller's own function of that name, whatever account an ARN names. + * Those are evaluated unqualified, because not every one of them acts on the qualifier it is + * given. + */ + private String buildLambdaArn(String path, ContainerRequestContext ctx, String region, String accountId) { String executionArn = durableExecutionArn(path); if (executionArn == null) { executionArn = durableCallbackExecutionArn(path); @@ -552,10 +565,49 @@ public class ResourceArnBuilder { // path: /2015-03-31/functions/name or similar String name = extractSegmentAfter(path, "functions"); if (name == null) return "*"; - // strip qualifier if present - int colon = name.indexOf(':'); - if (colon > 0) name = name.substring(0, colon); - return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString(); + boolean invoke = path.endsWith("/functions/" + name + "/invocations"); + try { + if (!invoke) { + LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(name); + boolean namedAccount = readsInTheAccountItNames(path, name, ref, ctx); + return AwsArnUtils.Arn.of("lambda", + namedAccount ? ref.region() : region, + namedAccount ? ref.account() : accountId, + "function:" + ref.name()).toString(); + } + LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolveWithQualifier( + name, ctx.getUriInfo().getQueryParameters().getFirst("Qualifier")); + String resource = ref.qualifier() != null + ? "function:" + ref.name() + ":" + ref.qualifier() + : "function:" + ref.name(); + return AwsArnUtils.Arn.of("lambda", + ref.region() != null ? ref.region() : region, + ref.account() != null ? ref.account() : accountId, + resource).toString(); + } catch (AwsException e) { + // A reference Lambda refuses, which its handler answers with a 400 before acting on anything. + return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString(); + } + } + + /** + * {@code GetFunction}, {@code GetFunctionConfiguration} and {@code ListDurableExecutionsByFunction} + * read a function named by a qualified full ARN in the account the ARN names, where the version or + * alias is resolved ({@code LambdaService.getFunction(region, name, qualifier)}). Unqualified, or + * by partial ARN, they read the caller's own function of that name, as every other route acts. + */ + private static boolean readsInTheAccountItNames(String path, String name, + LambdaArnUtils.ResolvedFunctionRef ref, + ContainerRequestContext ctx) { + if (!"GET".equals(ctx.getMethod()) || !name.startsWith("arn:")) { + return false; + } + String route = path.substring(path.indexOf("/functions/" + name) + "/functions/".length() + name.length()); + if (!route.isEmpty() && !route.equals("/configuration") && !route.equals("/durable-executions")) { + return false; + } + String qualifier = ctx.getUriInfo().getQueryParameters().getFirst("Qualifier"); + return ref.qualifier() != null || (qualifier != null && !qualifier.isBlank()); } /** Durable execution actions are authorized against the execution ARN, which carries the version. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaResourcePolicyProvider.java new file mode 100644 index 0000000000..911a489464 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaResourcePolicyProvider.java @@ -0,0 +1,81 @@ +package io.github.hectorvent.floci.services.lambda; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Supplies Lambda function policies to the IAM policy evaluation pipeline, together with the account + * that owns the function. + * + *

The owner is the account in the function ARN, and it is returned even when the function has no + * policy or does not exist: a call to another account's function is then judged as cross-account, + * which needs the function policy to allow the caller as well as the caller's own policy (Lambda + * Developer Guide, function URLs: "If the principal making the request is in a different account, + * then the principal must have both an identity-based policy ... and permissions granted to them in + * a resource-based policy"). + * + *

All of a function's statements are returned, its own and those of its versions and aliases. Each + * statement's {@code Resource} names the function, version or alias it was added to, so matching it + * against the ARN the call names is what scopes it: a grant on an alias covers calls to that alias + * only, and one on the function does not cover a qualified call (Lambda Developer Guide, "Referencing + * functions in the Resource section of policies"). + * + *

Keyed on the ARN rather than the request's credential scope, because a function is also the + * second resource of calls signed for another service: {@code RotateSecret} checks + * {@code lambda:InvokeFunction} on its rotation function under the {@code secretsmanager} scope. + */ +@ApplicationScoped +public class LambdaResourcePolicyProvider implements ResourcePolicyProvider { + + private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}"); + /** A function, version or alias, or a durable execution under one: the name is group 1. */ + private static final Pattern FUNCTION_RESOURCE = Pattern.compile("function:([^:/]+)(?:[:/].*)?"); + + private final LambdaService lambdaService; + private final ObjectMapper objectMapper; + + @Inject + public LambdaResourcePolicyProvider(LambdaService lambdaService, ObjectMapper objectMapper) { + this.lambdaService = lambdaService; + this.objectMapper = objectMapper; + } + + @Override + public List getResourcePolicies(String credentialScope, String resourceArn) { + if (!AwsArnUtils.isArnFor(resourceArn, "lambda")) { + return List.of(); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn); + Matcher function = FUNCTION_RESOURCE.matcher(arn.resource()); + if (!function.matches() || !ACCOUNT_ID.matcher(arn.accountId()).matches()) { + return List.of(); + } + List> statements = + lambdaService.policyStatements(arn.accountId(), arn.region(), function.group(1)); + return List.of(new ResourcePolicy(policyDocument(statements), arn.accountId())); + } + + private String policyDocument(List> statements) { + if (statements.isEmpty()) { + return null; + } + Map policy = new LinkedHashMap<>(); + policy.put("Version", "2012-10-17"); + policy.put("Statement", statements); + try { + return objectMapper.writeValueAsString(policy); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not serialize the function policy", e); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 9f7f45123e..7394fb327f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -1232,9 +1232,10 @@ public class LambdaService implements ResourceProvider { String name = ref.name(); String qualifier = ref.qualifier(); LambdaFunction fn; - if (functionName.startsWith("arn:")) { - AwsArnUtils.Arn arn = AwsArnUtils.parse(functionName); - fn = targetResolver.resolveInvokeTargetForAccount(arn.accountId(), region, name, qualifier); + // A full or partial ARN names its account, which is where the function runs and what IAM + // enforcement authorized the call against. + if (ref.account() != null) { + fn = targetResolver.resolveInvokeTargetForAccount(ref.account(), region, name, qualifier); } else { fn = targetResolver.resolveInvokeTarget(region, name, qualifier); } @@ -3731,6 +3732,40 @@ public class LambdaService implements ResourceProvider { } } + /** + * Every statement in the resource-based policies of a function in {@code accountId}: the + * function's own and those of each of its versions and aliases, which each statement's + * {@code Resource} tells apart. Read under the lock the policy mutations hold, so a statement + * being added or removed is seen whole or not at all. Empty when the function does not exist or + * has no policy. + */ + public List> policyStatements(String accountId, String region, String functionName) { + Optional observed = functionStore.getForAccount(accountId, region, functionName); + if (observed.isEmpty()) { + return List.of(); + } + synchronized (lockForPolicyMutation(observed.get().getFunctionArn())) { + return functionStore.getForAccount(accountId, region, functionName) + .map(fn -> fn.getPolicies().stream() + .>map(LinkedHashMap::new) + .toList()) + .orElse(List.of()); + } + } + + /** + * Reads the function, version or alias a full ARN names, in the ARN's own account and Region, + * where an invoke of that ARN runs it. {@link #getFunction(String, String)} reads a name in the + * caller's account, which for another account's ARN is a different function or none. + */ + public LambdaFunction getFunctionByArn(String functionArn) { + LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn); + if (ref.region() == null || ref.account() == null) { + throw new AwsException("InvalidParameterValueException", "Not a function ARN: " + functionArn, 400); + } + return targetResolver.resolveReadTargetForAccount(ref.account(), ref.region(), ref.name(), ref.qualifier()); + } + /** * Puts a previously captured policy statement back. Used to compensate when a replacement fails * after the original was removed: it takes the stored statement shape rather than an diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java index e868a149f1..fd561528ce 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 @@ -1149,10 +1149,11 @@ public class SecretsManagerService implements ResourceProvider { // A function that cannot be found is reported the way AWS reports it, AccessDeniedException with // HTTP 400; any other reference Lambda refuses is an invalid RotationLambdaARN. Either way the - // secret is left as it was. + // secret is left as it was. The function is looked up where the rotation will invoke it: in the + // ARN's account, and as the version or alias the ARN names. if (!serviceManaged && lambdaService != null) { try { - lambdaService.getFunction(region, functionArn); + lambdaService.getFunctionByArn(functionArn); } catch (AwsException e) { if (e.getHttpStatus() == 404) { throw new AwsException("AccessDeniedException", diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index 8ad8f0be99..4ea4568da0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -903,6 +903,94 @@ class ResourceArnBuilderTest { assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", arn); } + @Test + void lambdaFunctionArnKeepsTheAccountItNames() { + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function/invocations"); + assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/111122223333:function:my-function/invocations"); + assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + } + + @Test + void lambdaInvokeKeepsTheQualifierItRuns() { + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:live/invocations"); + assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function:live", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/my-function/invocations"); + queryParams.putSingle("Qualifier", "1"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:1", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + } + + @Test + void lambdaRoutesOtherThanInvokeAreCheckedAgainstTheCallersUnqualifiedFunction() { + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1/code"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/111122223333:function:my-function/policy"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/my-function"); + queryParams.putSingle("Qualifier", "1"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + } + + @Test + void lambdaQualifiedReadsByArnAreCheckedInTheAccountTheyRead() { + when(ctx.getMethod()).thenReturn("GET"); + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1"); + assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function/configuration"); + queryParams.putSingle("Qualifier", "live"); + assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + } + + @Test + void lambdaReadsThatDoNotFollowTheArnAreCheckedOnTheCallersFunction() { + when(ctx.getMethod()).thenReturn("GET"); + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/111122223333:function:my-function:1"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1/policy"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + + when(ctx.getMethod()).thenReturn("DELETE"); + when(uriInfo.getPath()).thenReturn( + "/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + } + + @Test + void lambdaReferenceLambdaRefusesIsNamedAsGiven() { + when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/not:a:function:ref/invocations"); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:not:a:function:ref", + builder.build("lambda", ctx, "us-east-1", "000000000000")); + } + @Test void lambdaDurableExecutionRoutesNameTheExecution() { when(uriInfo.getPath()).thenReturn("/2025-12-01/durable-executions/arn:aws:lambda:us-east-1:000000000000:" diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCrossAccountInvokeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCrossAccountInvokeIntegrationTest.java new file mode 100644 index 0000000000..1d6fd12f99 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCrossAccountInvokeIntegrationTest.java @@ -0,0 +1,441 @@ +package io.github.hectorvent.floci.services.lambda; + +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.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatcher; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Under IAM enforcement, a call to a function in another account needs the function policy to allow + * the caller as well as the caller's own policy (Lambda Developer Guide, function URLs: "If the + * principal making the request is in a different account, then the principal must have both an + * identity-based policy ... and permissions granted to them in a resource-based policy"). Lambda + * authorizes a call against the function, version or alias ARN the call names, so a function addressed + * by ARN is evaluated as that ARN, in its own account and with its qualifier. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class LambdaCrossAccountInvokeIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String OWNER = "444455556666"; + private static final String CALLER = "777788889999"; + private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String INVOKE_ANYTHING = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"*"}]}"""; + private static final String ROTATE_AND_INVOKE = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"secretsmanager:*","Resource":"*"}, + {"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"*"}]}"""; + + @InjectMock + LambdaExecutorService executor; + + /** How to delete each thing the test created, pushed as it is created and run newest first. */ + private final Deque cleanup = new ArrayDeque<>(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void stubExecutor() { + when(executor.invoke(any(), any(), any(), anyInt(), any(), any())) + .thenReturn(new InvokeResult(200, null, "{}".getBytes(StandardCharsets.UTF_8), null, "req")); + } + + @AfterEach + void deleteWhatTheTestCreated() { + while (!cleanup.isEmpty()) { + cleanup.pop().run(); + } + } + + @Test + void anotherAccountsFunctionIsRefusedWhenItsPolicyGrantsNothing() { + String functionArn = createFunction(OWNER, "victim-" + suffix()); + String caller = createUser(CALLER, "invoker-" + suffix(), INVOKE_ANYTHING); + + invoke(caller, functionArn) + .statusCode(403) + .body("__type", equalTo("AccessDeniedException")); + + verify(executor, never()).invoke(argThat(isFunction(functionArn)), any(), any(), anyInt(), any(), any()); + } + + @Test + void aGrantToTheCallersAccountLetsItInvoke() { + String functionArn = createFunction(OWNER, "shared-" + suffix()); + addPermission(OWNER, functionArn, null, Map.of("Principal", CALLER)); + String caller = createUser(CALLER, "invoker-" + suffix(), INVOKE_ANYTHING); + + invoke(caller, functionArn).statusCode(200); + + verify(executor).invoke(argThat(isFunction(functionArn)), any(), any(), anyInt(), any(), any()); + } + + @Test + void aGrantDoesNotStandInForTheCallersOwnPolicy() { + String functionArn = createFunction(OWNER, "shared-" + suffix()); + addPermission(OWNER, functionArn, null, Map.of("Principal", CALLER)); + String caller = createUser(CALLER, "no-lambda-" + suffix(), """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}]}"""); + + invoke(caller, functionArn).statusCode(403); + } + + @Test + void aPartialArnReachesTheAccountItNames() { + String name = "partial-" + suffix(); + String functionArn = createFunction(OWNER, name); + String caller = createUser(CALLER, "invoker-" + suffix(), INVOKE_ANYTHING); + + invoke(caller, OWNER + ":function:" + name).statusCode(403); + + addPermission(OWNER, functionArn, null, Map.of("Principal", CALLER)); + invoke(caller, OWNER + ":function:" + name).statusCode(200); + + verify(executor).invoke(argThat(isFunction(functionArn)), any(), any(), anyInt(), any(), any()); + } + + @Test + void aGrantNamingARoleCoversThatRolesSessionsOnly() { + String functionArn = createFunction(OWNER, "role-scoped-" + suffix()); + String grantedRole = "deploy.bot-" + suffix(); + String otherRole = "other-" + suffix(); + createRole(CALLER, grantedRole, INVOKE_ANYTHING); + createRole(CALLER, otherRole, INVOKE_ANYTHING); + addPermission(OWNER, functionArn, null, + Map.of("Principal", "arn:aws:iam::" + CALLER + ":role/" + grantedRole)); + + invoke(assumeRole(CALLER, grantedRole), functionArn).statusCode(200); + invoke(assumeRole(CALLER, otherRole), functionArn).statusCode(403); + } + + @Test + void anAliasGrantCoversThatAliasOnly() { + String name = "aliased-" + suffix(); + String functionArn = createFunction(OWNER, name); + publishVersionAndAlias(OWNER, name, "live"); + addPermission(OWNER, functionArn, "live", Map.of("Principal", CALLER)); + String caller = createUser(CALLER, "invoker-" + suffix(), INVOKE_ANYTHING); + + invoke(caller, functionArn + ":live").statusCode(200); + invoke(caller, functionArn, "live").statusCode(200); + invoke(caller, functionArn).statusCode(403); + invoke(caller, functionArn + ":1").statusCode(403); + } + + @Test + void aPublicFunctionUrlGrantDoesNotAdmitADirectInvoke() { + String functionArn = createFunction(OWNER, "url-only-" + suffix()); + addPermission(OWNER, functionArn, null, Map.of("Principal", "*", "InvokedViaFunctionUrl", true)); + String caller = createUser(CALLER, "invoker-" + suffix(), INVOKE_ANYTHING); + + invoke(caller, functionArn).statusCode(403); + } + + @Test + void aDenyOnTheFunctionArnAppliesToAnInvokeByArn() { + String name = "guarded-" + suffix(); + String functionArn = createFunction(OWNER, name); + String user = createUser(OWNER, "denied-" + suffix(), """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"*"}, + {"Effect":"Deny","Action":"lambda:InvokeFunction","Resource":"%s"}]}""".formatted(functionArn)); + + invoke(user, name).statusCode(403); + invoke(user, functionArn).statusCode(403); + invoke(user, OWNER + ":function:" + name).statusCode(403); + + verify(executor, never()).invoke(argThat(isFunction(functionArn)), any(), any(), anyInt(), any(), any()); + } + + @Test + void aSameAccountFunctionPolicyGrantsOnItsOwn() { + String functionArn = createFunction(OWNER, "own-grant-" + suffix()); + String userName = "granted-" + suffix(); + String user = createUser(OWNER, userName, """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}]}"""); + addPermission(OWNER, functionArn, null, Map.of("Principal", "arn:aws:iam::" + OWNER + ":user/" + userName)); + + invoke(user, functionArn).statusCode(200); + } + + /** + * Operations other than invoke act on the caller's own function of the name an ARN gives, whatever + * account it names, so they are authorized against that function: a grant from the account the + * ARN names does not get past a Deny on the function the call actually changes. + */ + @Test + void aManagementCallNamingAnotherAccountsArnIsCheckedAgainstTheFunctionItChanges() { + String name = "managed-" + suffix(); + String foreignArn = createFunction(OWNER, name); + String ownArn = createFunction(CALLER, name); + addPermission(OWNER, foreignArn, null, Map.of("Principal", CALLER, "Action", "lambda:DeleteFunction")); + String user = createUser(CALLER, "deleter-" + suffix(), """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"lambda:*","Resource":"*"}, + {"Effect":"Deny","Action":"lambda:DeleteFunction","Resource":"%s"}]}""".formatted(ownArn)); + + lambda(user).delete("/2015-03-31/functions/{name}", foreignArn).then().statusCode(403); + + lambda(CALLER).get("/2015-03-31/functions/{name}", name).then().statusCode(200); + lambda(OWNER).get("/2015-03-31/functions/{name}", name).then().statusCode(200); + } + + /** + * {@code GetFunction} reads a function named by a qualified ARN in the account the ARN names, so + * that account's function policy has to allow the caller, as for an invoke. + */ + @Test + void aQualifiedReadOfAnotherAccountsFunctionNeedsItsGrant() { + String foreignArn = createFunction(OWNER, "read-" + suffix()); + String user = createUser(CALLER, "reader-" + suffix(), """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"lambda:GetFunction","Resource":"*"}]}"""); + + lambda(user).get("/2015-03-31/functions/{name}", foreignArn + ":$LATEST").then().statusCode(403); + lambda(user).queryParam("Qualifier", "$LATEST").get("/2015-03-31/functions/{name}", foreignArn) + .then().statusCode(403); + + addPermission(OWNER, foreignArn, null, Map.of("Principal", CALLER, "Action", "lambda:GetFunction")); + lambda(user).get("/2015-03-31/functions/{name}", foreignArn + ":$LATEST") + .then().statusCode(200).body("Configuration.FunctionArn", startsWith(foreignArn)); + } + + @Test + void rotateSecretIsRefusedForAnotherAccountsFunctionThatGrantsNothing() { + String name = "rotator-" + suffix(); + String foreignArn = createFunction(OWNER, name); + createFunction(CALLER, name); + String caller = createUser(CALLER, "rotator-user-" + suffix(), ROTATE_AND_INVOKE); + String secretName = createSecret(caller, "foreign-" + suffix()); + + secretsManager(caller, "RotateSecret", + "{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + foreignArn + "\"}") + .statusCode(400) + .body("__type", equalTo("AccessDeniedException")); + + verify(executor, never()).invoke(argThat(isFunction(foreignArn)), any(), any(), anyInt(), any(), any()); + } + + @Test + void rotateSecretRunsAnotherAccountsFunctionThatGrantsTheCaller() { + String foreignArn = createFunction(OWNER, "rotator-" + suffix()); + addPermission(OWNER, foreignArn, null, Map.of("Principal", CALLER)); + String caller = createUser(CALLER, "rotator-user-" + suffix(), ROTATE_AND_INVOKE); + String secretName = createSecret(caller, "granted-" + suffix()); + + secretsManager(caller, "RotateSecret", + "{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + foreignArn + "\"}") + .statusCode(200); + + verify(executor, timeout(5000).atLeastOnce()) + .invoke(argThat(isFunction(foreignArn)), any(), any(), anyInt(), any(), any()); + awaitRotationFinished(caller, secretName); + } + + @Test + void rotateSecretRefusesAnAliasTheFunctionDoesNotHave() { + String functionArn = createFunction(OWNER, "rotator-" + suffix()); + String user = createUser(OWNER, "rotator-user-" + suffix(), ROTATE_AND_INVOKE); + String secretName = createSecret(user, "no-alias-" + suffix()); + + secretsManager(user, "RotateSecret", + "{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + ":nosuchalias\"}") + .statusCode(400) + .body("__type", equalTo("AccessDeniedException")); + + verify(executor, never()).invoke(any(), any(), any(), anyInt(), any(), any()); + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } + + private static ArgumentMatcher isFunction(String functionArn) { + return fn -> fn != null && functionArn.equals(fn.getFunctionArn()); + } + + private String createFunction(String account, String name) { + lambda(account) + .body(""" + {"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler", + "Role":"arn:aws:iam::%s:role/lambda-role"}""".formatted(name, account)) + .when() + .post("/2015-03-31/functions") + .then() + .statusCode(201); + cleanup.push(() -> lambda(account).delete("/2015-03-31/functions/{name}", name).then().statusCode(204)); + return "arn:aws:lambda:" + REGION + ":" + account + ":function:" + name; + } + + private static void publishVersionAndAlias(String account, String name, String alias) { + lambda(account).body("{}").post("/2015-03-31/functions/{name}/versions", name).then().statusCode(201); + lambda(account) + .body("{\"Name\":\"" + alias + "\",\"FunctionVersion\":\"1\"}") + .post("/2015-03-31/functions/{name}/aliases", name) + .then() + .statusCode(201); + } + + /** Adds a statement granting {@code lambda:InvokeFunction} unless {@code grant} names another action. */ + private static void addPermission(String account, String functionArn, String qualifier, Map grant) { + Map request = new LinkedHashMap<>(); + request.put("StatementId", "s-" + suffix()); + request.put("Action", "lambda:InvokeFunction"); + request.putAll(grant); + RequestSpecification spec = lambda(account).body(request); + if (qualifier != null) { + spec.queryParam("Qualifier", qualifier); + } + spec.post("/2015-03-31/functions/{name}/policy", functionArn).then().statusCode(201); + } + + private static ValidatableResponse invoke(String accessKeyId, String functionName) { + return invoke(accessKeyId, functionName, null); + } + + private static ValidatableResponse invoke(String accessKeyId, String functionName, String qualifier) { + RequestSpecification spec = given() + .header("Authorization", authorization(accessKeyId, "lambda")) + .contentType("application/json") + .body("{}"); + if (qualifier != null) { + spec.queryParam("Qualifier", qualifier); + } + return spec.when().post("/2015-03-31/functions/{name}/invocations", functionName).then(); + } + + private static RequestSpecification lambda(String accessKeyId) { + return given() + .header("Authorization", authorization(accessKeyId, "lambda")) + .contentType("application/json"); + } + + private String createSecret(String accessKeyId, String secretName) { + secretsManager(accessKeyId, "CreateSecret", + "{\"Name\":\"" + secretName + "\",\"SecretString\":\"v1\"}").statusCode(200); + cleanup.push(() -> secretsManager(accessKeyId, "DeleteSecret", + "{\"SecretId\":\"" + secretName + "\",\"ForceDeleteWithoutRecovery\":true}").statusCode(200)); + return secretName; + } + + 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(); + } + + /** + * Lets the rotation finish before cleanup deletes the secret, which it would otherwise go on + * trying to update. + */ + private static void awaitRotationFinished(String accessKeyId, String secretName) { + await().atMost(Duration.ofSeconds(5)).until(() -> secretsManager(accessKeyId, "DescribeSecret", + "{\"SecretId\":\"" + secretName + "\"}").statusCode(200).extract().path("LastRotatedDate") != null); + } + + private String createUser(String account, String userName, String policyDocument) { + iam(account, "CreateUser", Map.of("UserName", userName)).statusCode(200); + cleanup.push(() -> iam(account, "DeleteUser", Map.of("UserName", userName)).statusCode(200)); + iam(account, "PutUserPolicy", Map.of( + "UserName", userName, + "PolicyName", "inline", + "PolicyDocument", policyDocument)).statusCode(200); + cleanup.push(() -> iam(account, "DeleteUserPolicy", + Map.of("UserName", userName, "PolicyName", "inline")).statusCode(200)); + String accessKeyId = iam(account, "CreateAccessKey", Map.of("UserName", userName)) + .statusCode(200) + .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"); + cleanup.push(() -> iam(account, "DeleteAccessKey", + Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(200)); + return accessKeyId; + } + + private void createRole(String account, String roleName, String policyDocument) { + iam(account, "CreateRole", Map.of( + "RoleName", roleName, + "AssumeRolePolicyDocument", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}""" + .formatted(account))).statusCode(200); + cleanup.push(() -> iam(account, "DeleteRole", Map.of("RoleName", roleName)).statusCode(200)); + iam(account, "PutRolePolicy", Map.of( + "RoleName", roleName, + "PolicyName", "inline", + "PolicyDocument", policyDocument)).statusCode(200); + cleanup.push(() -> iam(account, "DeleteRolePolicy", + Map.of("RoleName", roleName, "PolicyName", "inline")).statusCode(200)); + } + + private static String assumeRole(String account, String roleName) { + return given() + .header("Authorization", authorization(account, "sts")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRole") + .formParam("Version", "2011-06-15") + .formParam("RoleArn", "arn:aws:iam::" + account + ":role/" + roleName) + .formParam("RoleSessionName", "s1b") + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"); + } + + private static ValidatableResponse iam(String account, String action, Map params) { + RequestSpecification spec = given() + .header("Authorization", authorization(account, "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 + "/20261011/" + REGION + "/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaResourcePolicyProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaResourcePolicyProviderTest.java new file mode 100644 index 0000000000..dc34d67c2a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaResourcePolicyProviderTest.java @@ -0,0 +1,78 @@ +package io.github.hectorvent.floci.services.lambda; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class LambdaResourcePolicyProviderTest { + + private static final String OWNER = "111122223333"; + private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:" + OWNER + ":function:my-function"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private LambdaService lambdaService; + private LambdaResourcePolicyProvider provider; + + @BeforeEach + void setUp() { + lambdaService = mock(LambdaService.class); + when(lambdaService.policyStatements(OWNER, "us-east-1", "my-function")).thenReturn(List.of()); + provider = new LambdaResourcePolicyProvider(lambdaService, objectMapper); + } + + @Test + void theOwnerComesFromTheArnEvenWithoutAPolicy() { + List policies = provider.getResourcePolicies("lambda", FUNCTION_ARN); + + assertEquals(1, policies.size()); + assertNull(policies.getFirst().policyDocument()); + assertEquals(OWNER, policies.getFirst().ownerAccountId()); + } + + @Test + void everyStatementOnTheFunctionComesBackForAQualifiedArn() throws Exception { + Map functionGrant = Map.of("Sid", "fn", "Effect", "Allow", + "Principal", Map.of("AWS", "arn:aws:iam::444455556666:root"), + "Action", "lambda:InvokeFunction", "Resource", FUNCTION_ARN); + Map aliasGrant = Map.of("Sid", "alias", "Effect", "Allow", + "Principal", Map.of("AWS", "arn:aws:iam::444455556666:root"), + "Action", "lambda:InvokeFunction", "Resource", FUNCTION_ARN + ":live"); + when(lambdaService.policyStatements(OWNER, "us-east-1", "my-function")) + .thenReturn(List.of(functionGrant, aliasGrant)); + + List policies = provider.getResourcePolicies("lambda", FUNCTION_ARN + ":live"); + + JsonNode statements = objectMapper.readTree(policies.getFirst().policyDocument()).get("Statement"); + assertEquals(2, statements.size()); + assertEquals(FUNCTION_ARN, statements.get(0).get("Resource").asText()); + assertEquals(FUNCTION_ARN + ":live", statements.get(1).get("Resource").asText()); + assertEquals(OWNER, policies.getFirst().ownerAccountId()); + } + + @Test + void aFunctionCheckedUnderAnotherServicesScopeIsStillSupplied() { + List policies = provider.getResourcePolicies("secretsmanager", FUNCTION_ARN); + + assertEquals(OWNER, policies.getFirst().ownerAccountId()); + } + + @Test + void resourcesThatAreNotFunctionsAreLeftToOtherProviders() { + assertTrue(provider.getResourcePolicies("lambda", "*").isEmpty()); + assertTrue(provider.getResourcePolicies("lambda", "arn:aws:lambda:us-east-1:" + OWNER + ":layer:my-layer:1").isEmpty()); + assertTrue(provider.getResourcePolicies("lambda", + "arn:aws:lambda:us-east-1:" + OWNER + ":event-source-mapping:fa123456-14a1-4fd2-9fec-83de64ad683d").isEmpty()); + assertTrue(provider.getResourcePolicies("s3", "arn:aws:s3:::bucket/key").isEmpty()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java index 25ec4899b2..394c36e076 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationIntegrationTest.java @@ -60,7 +60,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest { @BeforeEach void stubLambda() { - Mockito.when(lambdaService.getFunction(anyString(), anyString())).thenReturn(new LambdaFunction()); + Mockito.when(lambdaService.getFunctionByArn(anyString())).thenReturn(new LambdaFunction()); InvokeResult ok = new InvokeResult(); ok.setStatusCode(200); Mockito.when(lambdaService.invoke(any(), any(), any(), any())).thenReturn(ok); 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.java index e736290b98..358da8df44 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationInvokeAuthorizationTest.java @@ -50,7 +50,7 @@ class SecretsManagerRotationInvokeAuthorizationTest { void setUp() { store = new InMemoryStorage<>(); lambda = mock(LambdaService.class); - when(lambda.getFunction(anyString(), anyString())).thenReturn(new LambdaFunction()); + when(lambda.getFunctionByArn(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); @@ -116,7 +116,7 @@ class SecretsManagerRotationInvokeAuthorizationTest { @Test void lambdaRefusingTheReferenceAtTheLookupIsAnInvalidParameter() { - when(lambda.getFunction(anyString(), anyString())) + when(lambda.getFunctionByArn(anyString())) .thenThrow(new AwsException("ValidationException", "refused by Lambda", 400)); AwsException e = assertThrows(AwsException.class, () -> @@ -149,7 +149,7 @@ class SecretsManagerRotationInvokeAuthorizationTest { @Test void refusalComesBeforeTheExistenceCheck() { - when(lambda.getFunction(anyString(), anyString())) + when(lambda.getFunctionByArn(anyString())) .thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404)); Consumer refuse = functionArn -> { throw new AwsException("AccessDeniedException", "refused by the caller check", 400); @@ -163,7 +163,7 @@ class SecretsManagerRotationInvokeAuthorizationTest { @Test void missingFunctionIsReportedAsSecretsManagerReportsIt() { - when(lambda.getFunction(anyString(), anyString())) + when(lambda.getFunctionByArn(anyString())) .thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404)); AwsException e = assertThrows(AwsException.class, () -> @@ -181,7 +181,7 @@ class SecretsManagerRotationInvokeAuthorizationTest { Secret secret = service.describeSecret("my-secret", REGION); secret.setRotationLambdaArn(FUNCTION_ARN); store.put(REGION + "::my-secret", secret); - when(lambda.getFunction(anyString(), anyString())) + when(lambda.getFunctionByArn(anyString())) .thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404)); assertThrows(AwsException.class, () -> service.rotateSecret("my-secret", TOKEN, diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java index b70a0dc09d..022068e45b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java @@ -89,7 +89,7 @@ class SecretsManagerWriteLockTest { @Test void deletingASecretWaitsForTheFinalSaveOfARotation() throws Exception { LambdaService lambda = mock(LambdaService.class); - when(lambda.getFunction(anyString(), anyString())).thenReturn(new LambdaFunction()); + when(lambda.getFunctionByArn(anyString())).thenReturn(new LambdaFunction()); InvokeResult ok = new InvokeResult(); ok.setStatusCode(200); when(lambda.invoke(anyString(), anyString(), any(byte[].class), any())).thenReturn(ok);