Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambdaweb): check the execution role as AWS does (#6347)
TATSUNO “Taz” Yasuhiro7e6439cf8654
diff --git a/compatibility-tests/sdk-test-awscli/test/lambda-web.bats b/compatibility-tests/sdk-test-awscli/test/lambda-web.batsindex 726ee0cfdb..6d2b96f0d4 100644--- a/compatibility-tests/sdk-test-awscli/test/lambda-web.bats+++ b/compatibility-tests/sdk-test-awscli/test/lambda-web.bats@@ -8,7 +8,11 @@ setup() {load 'test_helper/common-setup'FUNCTION_NAME=""BUCKET="cli-lambda-web-code-$$"- ROLE_ARN="arn:aws:iam::000000000000:role/lambda-web"+ ROLE_NAME="cli-lambda-web-$$"+ ROLE_ARN="arn:aws:iam::000000000000:role/$ROLE_NAME"+ aws_cmd iam create-role --role-name "$ROLE_NAME" --assume-role-policy-document \+ '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}' \+ >/dev/null 2>&1 || trueaws_cmd s3api create-bucket --bucket "$BUCKET" >/dev/null 2>&1 || true# A revision whose code is not a zip fails. python3 ships in the CLI image.python3 -c 'import sys, zipfile@@ -24,6 +28,7 @@ teardown() {aws_cmd iam delete-role --role-name "awscli-lambdaweb-$FUNCTION_NAME" >/dev/null 2>&1 || truefiaws_cmd s3 rb "s3://$BUCKET" --force >/dev/null 2>&1 || true+ aws_cmd iam delete-role --role-name "$ROLE_NAME" >/dev/null 2>&1 || true}build_config() {@@ -136,6 +141,24 @@ create_function() {assert_output --partial "Invalid function name or ARN '-bad'"}+@test "Lambda Web: an execution role Lambda cannot assume is refused" {+ FUNCTION_NAME=$(unique_name "cli-web")+ create_function "$FUNCTION_NAME" >/dev/null++ run aws_cmd lambda-web create-web-function-revision --function-name "$FUNCTION_NAME" \+ --build-config "$(build_config)" --service-config "{\"executionRoleArn\":\"$ROLE_ARN-missing\"}"+ assert_failure+ assert_output --partial "ValidationException"+ assert_output --partial "The execution role $ROLE_ARN-missing cannot be assumed by lambda.amazonaws.com."++ run aws_cmd lambda-web create-web-function-revision --function-name "$FUNCTION_NAME" \+ --build-config "$(build_config)" \+ --service-config "{\"executionRoleArn\":\"arn:aws:iam::111122223333:role/$ROLE_NAME\"}"+ assert_failure+ assert_output --partial "AccessDeniedException"+ assert_output --partial "Cross-account pass role is not allowed."+}+@test "Lambda Web: deploy the hello world app and invoke its endpoint" {FUNCTION_NAME=$(unique_name "cli-web")# deploy passes --endpoint-url only to its Lambda Web client, so the environment variable routes the rest.diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaWebTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaWebTest.javaindex a94a971671..25e18f8b4e 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaWebTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaWebTest.java@@ -8,7 +8,9 @@ import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;import software.amazon.awssdk.core.sync.RequestBody;+import software.amazon.awssdk.services.iam.IamClient;import software.amazon.awssdk.services.lambdaweb.LambdaWebClient;+import software.amazon.awssdk.services.lambdaweb.model.AccessDeniedException;import software.amazon.awssdk.services.lambdaweb.model.AuthType;import software.amazon.awssdk.services.lambdaweb.model.AutoDeploymentMode;import software.amazon.awssdk.services.lambdaweb.model.BuildConfig;@@ -42,8 +44,12 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;class LambdaWebTest {private static final String FUNCTION_NAME = "sdk-test-web-fn";- private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-web-role";+ private static final String LAMBDA_TRUST = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";private static LambdaWebClient lambdaWeb;+ private static IamClient iam;+ private static String roleName;+ private static String role;private static S3Client s3;private static String bucket;private static String functionArn;@@ -54,6 +60,9 @@ class LambdaWebTest {static void setup() {lambdaWeb = TestFixtures.lambdaWebClient();s3 = TestFixtures.s3Client();+ iam = TestFixtures.iamClient();+ roleName = TestFixtures.uniqueName("sdk-test-web-role");+ role = iam.createRole(r -> r.roleName(roleName).assumeRolePolicyDocument(LAMBDA_TRUST)).role().arn();bucket = TestFixtures.uniqueName("sdk-test-web-code");s3.createBucket(r -> r.bucket(bucket));s3.putObject(r -> r.bucket(bucket).key("app.zip"), RequestBody.fromBytes(LambdaUtils.minimalZip()));@@ -79,6 +88,12 @@ class LambdaWebTest {}s3.close();}+ if (iam != null) {+ if (role != null) {+ iam.deleteRole(r -> r.roleName(roleName));+ }+ iam.close();+ }}private static BuildConfig buildConfig() {@@ -95,7 +110,7 @@ class LambdaWebTest {.functionName(FUNCTION_NAME).revisionConfig(RevisionConfig.builder().buildConfig(buildConfig())- .serviceConfig(ServiceConfig.builder().executionRoleArn(ROLE).build())+ .serviceConfig(ServiceConfig.builder().executionRoleArn(role).build()).build()).endpointConfig(EndpointConfig.builder().endpointName("dev")@@ -147,7 +162,7 @@ class LambdaWebTest {.functionName(FUNCTION_NAME).description("second").buildConfig(buildConfig())- .serviceConfig(ServiceConfig.builder().executionRoleArn(ROLE).timeoutSeconds(60)+ .serviceConfig(ServiceConfig.builder().executionRoleArn(role).timeoutSeconds(60).environmentVariables(Map.of("APP_VERSION", "2")).build()));secondRevisionId = revision.revisionId();assertThat(revision.stateAsString()).isEqualTo("Pending");@@ -195,7 +210,7 @@ class LambdaWebTest {assertThatThrownBy(() -> lambdaWeb.createWebFunctionRevision(r -> r.functionName(FUNCTION_NAME).buildConfig(buildConfig())- .serviceConfig(ServiceConfig.builder().executionRoleArn(ROLE).timeoutSeconds(2).build())))+ .serviceConfig(ServiceConfig.builder().executionRoleArn(role).timeoutSeconds(2).build()))).isInstanceOf(ValidationException.class).hasMessageContaining("1 validation error detected: Value '2' at 'serviceConfig.timeoutSeconds' failed"+ " to satisfy constraint: Member must have value greater than or equal to 3");@@ -207,6 +222,21 @@ class LambdaWebTest {.endpointType(EndpointType.HOME_REGION).authType(AuthType.APPLICATION_MANAGED))).isInstanceOf(ValidationException.class).hasMessageContaining("The revisionWeights must be specified when the autoDeploymentMode is Disabled.");+ String missingRole = role.replace(roleName, roleName + "-missing");+ assertThatThrownBy(() -> lambdaWeb.createWebFunctionRevision(r -> r+ .functionName(FUNCTION_NAME)+ .buildConfig(buildConfig())+ .serviceConfig(ServiceConfig.builder().executionRoleArn(missingRole).build())))+ .isInstanceOf(ValidationException.class)+ .hasMessageContaining("The execution role " + missingRole + " cannot be assumed by lambda.amazonaws.com."+ + " Verify its trust policy. If the role was just created, retry in a few seconds.");+ assertThatThrownBy(() -> lambdaWeb.createWebFunctionRevision(r -> r+ .functionName(FUNCTION_NAME)+ .buildConfig(buildConfig())+ .serviceConfig(ServiceConfig.builder()+ .executionRoleArn("arn:aws:iam::111122223333:role/" + roleName).build())))+ .isInstanceOfSatisfying(AccessDeniedException.class, e -> assertThat(e.statusCode()).isEqualTo(403))+ .hasMessageContaining("Cross-account pass role is not allowed.");}@Testdiff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdindex a5a437c10b..12947de805 100644--- a/docs/services/lambda-web-functions.md+++ b/docs/services/lambda-web-functions.md@@ -38,7 +38,7 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A- **Failed revisions:** a revision whose code is not a zip, or whose files add up to more than 512 MiB, is stored `Failed`, as on AWS. It cannot be deployed: weights that name it, or `LatestRevision` while it is the newest revision, are `409 ConflictException`, and `LatestRevision` endpoints stay on their revision. The endpoint of a `CreateWebFunction` whose revision fails is `Failed` too. It answers every request with `409` and `Platform.EndpointNotActive` and refuses updates until it is deleted. In a stack, the revision's resource fails with the revision's `stateReason` and the rollback deletes it. An empty object is a `500 InternalServerException` with the body `{}`, and an object over 512 MiB is a `400 ValidationException`, as on AWS.- **Code comes from S3 only.** The object named in `buildConfig.codeConfig.s3Object` must exist in Floci's S3, as on AWS. AWS also requires bucket versioning and a bucket policy for the Lambda service principal. Floci does not check them yet.- **Each revision keeps its own copy of the code**, read at creation from the version the request names or the current one, under the Lambda `code-path`. As on AWS, a later write or delete in the bucket does not change what the revision runs. AWS moves a revision to `Failed` when it later finds its object version gone, which Floci does not do.-- **Execution role and network connector** ARNs are checked for shape only. The assume-role check AWS makes is not done yet.+- **Execution role:** a role in another account is `403 AccessDeniedException` "Cross-account pass role is not allowed.". A role that does not exist in IAM, or whose trust policy does not let `lambda.amazonaws.com` assume it, is `400 ValidationException` "The execution role <arn> cannot be assumed by lambda.amazonaws.com. Verify its trust policy. If the role was just created, retry in a few seconds.". As on AWS, this check sets no `aws:SourceAccount` or `aws:SourceArn`, so a trust policy that requires either refuses the role. The network connector ARN is checked for shape only.- **Resource policies** are checked the way AWS checks them before storing: the document grammar, a `lambda:` action, a `Resource` that names the function, a valid principal, and no public `Allow`. A wildcard principal needs a positive condition (`StringEquals`, `StringLike`, `ArnLike`, `Bool`) on a trusted key such as `aws:PrincipalAccount` or `aws:PrincipalArn`, with no wildcard in the account it names. An `IamAuth` endpoint evaluates it on requests, as below.- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.@@ -78,7 +78,7 @@ An `IamAuth` endpoint takes a request signed with SigV4 for the service `lambda`The revision's `timeoutSeconds` bounds the whole exchange, as on AWS: a response that has not started by then is the 504 page, and one that is still streaming is cut. The request body is taken in full before the answer, so a slow upload gets its 504 once the body is in.-The container gets the execution role's session credentials when the role exists in IAM, and the account's test credentials otherwise, so SDK calls from the app land in the function's account.+The container gets the execution role's session credentials, so SDK calls from the app land in the function's account. An environment assumes the role with the function ARN as `aws:SourceArn` and its account as `aws:SourceAccount`. When the role was deleted or no longer trusts Lambda, the request gets `502 Platform.CannotAssumeRole` and the revision stays `Active`, as on AWS.The platform answers these cases itself, with the AWS HTML pages and `lambda-web-error-type`:diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.javaindex fbe8aceb61..6cf0a6052f 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.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.IamConditionContextResolver;import io.github.hectorvent.floci.core.common.ServicePrincipals;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;@@ -12,6 +13,7 @@ import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.function.Predicate;import java.util.regex.Matcher;import java.util.regex.Pattern;@@ -237,10 +239,10 @@ public class AssumeRolePolicyEvaluator {}/**- * Checks a service trust policy in the context of an AppSync API. AWS supports narrowing- * service trust with aws:SourceAccount and aws:SourceArn, which form the request context here;- * a condition on any other key finds it absent and does not match, so it never turns a- * conditional Allow into an unconditional one.+ * Checks a service trust policy against the context of a call the service makes: its principal+ * keys, and aws:SourceArn and aws:SourceAccount when it names them. A condition on any other+ * key finds it absent and does not match, so it never turns a conditional Allow into an+ * unconditional one.*/public boolean allowsService(String trustPolicyDocument, String servicePrincipal,String sourceArn, String sourceAccount) {@@ -259,13 +261,8 @@ public class AssumeRolePolicyEvaluator {return false;}String version = root.path("Version").asText(null);- Map<String, List<String>> context = new HashMap<>();- if (sourceArn != null) {- context.put("aws:SourceArn", List.of(sourceArn));- }- if (sourceAccount != null) {- context.put("aws:SourceAccount", List.of(sourceAccount));- }+ Map<String, List<String>> context = IamConditionContextResolver.serviceCallContext(+ servicePrincipal, null, null, sourceArn, sourceAccount);boolean allow = false;if (statements.isArray()) {for (JsonNode statement : statements) {@@ -377,20 +374,32 @@ public class AssumeRolePolicyEvaluator {if (principalNode == null || servicePrincipal == null) {return false;}- JsonNode service = principalNode.isObject() ? principalNode.get("Service") : null;- if (service == null) {+ // "*" and {"AWS": "*"} name every principal, a service among them.+ if (principalNode.isTextual()) {+ return "*".equals(principalNode.asText());+ }+ if (!principalNode.isObject()) {return false;}// A policy may name the service in the universal form or the partition form AWS accepted// before it (elasticmapreduce.amazonaws.com.cn); both sides are folded to the universal// one so either matches, still exactly and case-sensitively.String wanted = ServicePrincipals.canonical(servicePrincipal);- if (service.isTextual()) {- return ServicePrincipals.canonical(service.asText()).equals(wanted);+ return anyEntry(principalNode.get("AWS"), "*"::equals)+ || anyEntry(principalNode.get("Service"), name -> ServicePrincipals.canonical(name).equals(wanted));+ }++ /** True if {@code node}, a string or an array of them, holds one that {@code matches} accepts. */+ private static boolean anyEntry(JsonNode node, Predicate<String> matches) {+ if (node == null) {+ return false;+ }+ if (node.isTextual()) {+ return matches.test(node.asText());}- if (service.isArray()) {- for (JsonNode entry : service) {- if (entry.isTextual() && ServicePrincipals.canonical(entry.asText()).equals(wanted)) {+ if (node.isArray()) {+ for (JsonNode entry : node) {+ if (entry.isTextual() && matches.test(entry.asText())) {return true;}}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebAccessDeniedException.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebAccessDeniedException.javanew file mode 100644index 0000000000..1c9ed3ea1b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebAccessDeniedException.java@@ -0,0 +1,16 @@+package io.github.hectorvent.floci.services.lambdaweb;++import java.util.Map;++/** An access denial. AWS writes its message under {@code Message}, not {@code message}. */+public final class LambdaWebAccessDeniedException extends LambdaWebErrorBodyException {++ LambdaWebAccessDeniedException(String message) {+ super("AccessDeniedException", message, 403);+ }++ @Override+ Map<String, String> body() {+ return Map.of("Message", getMessage());+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.javaindex a70f7b39e6..51aee4e1cb 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManager.java@@ -266,6 +266,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {private final ZipExtractor zipExtractor;private final LaunchedContainerAwsEnv awsEnv;private final LambdaExecutionRoleCredentials executionRoleCredentials;+ private final LambdaWebExecutionRole executionRole;private final LambdaWebLogs logs;private final LambdaWebMetrics metrics;private final byte[] runtime;@@ -283,7 +284,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {@StreamingDocker DockerClient streamingDocker, ImageResolver imageResolver,EcrRegistryManager ecrRegistryManager, LambdaWebCode code,ZipExtractor zipExtractor, LaunchedContainerAwsEnv awsEnv,- LambdaExecutionRoleCredentials executionRoleCredentials, LambdaWebLogs logs,+ LambdaExecutionRoleCredentials executionRoleCredentials,+ LambdaWebExecutionRole executionRole, LambdaWebLogs logs,LambdaWebMetrics metrics) {this.config = config;this.containerBuilder = containerBuilder;@@ -295,6 +297,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {this.zipExtractor = zipExtractor;this.awsEnv = awsEnv;this.executionRoleCredentials = executionRoleCredentials;+ this.executionRole = executionRole;this.logs = logs;this.metrics = metrics;this.runtime = runtimeScript();@@ -541,6 +544,9 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {}private void start(Environment environment, String region, WebFunction fn, WebFunctionRevision revision) {+ if (!executionRole.assumableFor(region, fn.functionArn, revision.serviceConfig.executionRoleArn)) {+ throw new StartFailure(LambdaWebErrorPages.CANNOT_ASSUME_ROLE);+ }String accountId = environment.accountId;String image = ecrRegistryManager.rewriteImageUri(imageResolver.resolve(revision.buildConfig.runtime));String shortId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);@@ -552,6 +558,10 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {cmd.add(RUNTIME_DIR + "/index.js");Optional<SessionCreds> roleCredentials = executionRoleCredentials.forRole(revision.serviceConfig.executionRoleArn, accountId, fn.functionName);+ // The role can be deleted after the trust check.+ if (roleCredentials.isEmpty()) {+ throw new StartFailure(LambdaWebErrorPages.CANNOT_ASSUME_ROLE);+ }ContainerSpec spec = containerBuilder.newContainer(image).withName(name).withEnv(environment(accountId, region, revision, userEnv, roleCredentials))diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorBodyException.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorBodyException.javanew file mode 100644index 0000000000..0529937251--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorBodyException.java@@ -0,0 +1,15 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.core.common.AwsException;++import java.util.Map;++/** An error AWS answers with a body other than {@code {"message": ...}}. */+public abstract class LambdaWebErrorBodyException extends AwsException {++ LambdaWebErrorBodyException(String errorCode, String message, int httpStatus) {+ super(errorCode, message, httpStatus);+ }++ abstract Map<String, String> body();+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebInternalServerExceptionMapper.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorBodyExceptionMapper.javasimilarity index 63%rename from src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebInternalServerExceptionMapper.javarename to src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorBodyExceptionMapper.javaindex 5102ce6fcc..ee7043797b 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebInternalServerExceptionMapper.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorBodyExceptionMapper.java@@ -5,17 +5,15 @@ import jakarta.ws.rs.core.Response;import jakarta.ws.rs.ext.ExceptionMapper;import jakarta.ws.rs.ext.Provider;-import java.util.Map;-@Provider-public final class LambdaWebInternalServerExceptionMapper implements ExceptionMapper<LambdaWebInternalServerException> {+public final class LambdaWebErrorBodyExceptionMapper implements ExceptionMapper<LambdaWebErrorBodyException> {@Override- public Response toResponse(LambdaWebInternalServerException exception) {+ public Response toResponse(LambdaWebErrorBodyException exception) {return Response.status(exception.getHttpStatus()).type(MediaType.APPLICATION_JSON).header("X-Amzn-Errortype", exception.getErrorCode())- .entity(Map.of())+ .entity(exception.body()).build();}}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorPages.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorPages.javaindex fcf806954b..e49d3cb3b5 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorPages.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebErrorPages.java@@ -32,6 +32,7 @@ final class LambdaWebErrorPages {static final Page IMPORT_CODE_ERROR = new Page(502, "Bad Gateway", "Runtime.ImportCodeError", APPLICATION_ERROR);static final Page RUNTIME_EXIT = new Page(502, "Bad Gateway", "Runtime.Exit", APPLICATION_ERROR);static final Page RUNTIME_EXIT_ERROR = new Page(502, "Bad Gateway", "Runtime.ExitError", APPLICATION_ERROR);+ static final Page CANNOT_ASSUME_ROLE = new Page(502, "Bad Gateway", "Platform.CannotAssumeRole", APPLICATION_ERROR);private static final String RATE_EXCEEDED = "Request rate exceeded. Please try again later.";static final Page ENDPOINT_MAX_ENV_THROTTLE = new Page(429, "Too Many Requests","Platform.EndpointMaxEnvThrottle", RATE_EXCEEDED);diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebExecutionRole.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebExecutionRole.javanew file mode 100644index 0000000000..f1e36969eb--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebExecutionRole.java@@ -0,0 +1,53 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.AwsRegions;+import io.github.hectorvent.floci.core.common.ServicePrincipals;+import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;+import io.github.hectorvent.floci.services.iam.IamService;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++/** Whether Lambda can assume the execution role of a revision. */+@ApplicationScoped+public class LambdaWebExecutionRole {++ private static final String LAMBDA = ServicePrincipals.of("lambda");++ private final IamService iamService;+ private final AssumeRolePolicyEvaluator trust;++ @Inject+ public LambdaWebExecutionRole(IamService iamService, AssumeRolePolicyEvaluator trust) {+ this.iamService = iamService;+ this.trust = trust;+ }++ /** AWS gives no aws:SourceAccount or aws:SourceArn here, so a trust policy that needs one refuses. */+ void requireAssumable(String region, String roleArn) {+ if (!assumable(region, roleArn, null, null)) {+ throw new AwsException("ValidationException", "The execution role " + roleArn+ + " cannot be assumed by " + LAMBDA + ". Verify its trust policy."+ + " If the role was just created, retry in a few seconds.", 400);+ }+ }++ /** An environment assumes the role with the function as aws:SourceArn and its account as aws:SourceAccount. */+ boolean assumableFor(String region, String functionArn, String roleArn) {+ return assumable(region, roleArn, functionArn, AwsArnUtils.parse(functionArn).accountId());+ }++ private boolean assumable(String region, String roleArn, String sourceArn, String sourceAccount) {+ AwsArnUtils.Arn arn = AwsArnUtils.parse(roleArn);+ if (!arn.partition().equals(AwsRegions.partitionFor(region))) {+ return false;+ }+ String name = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);+ return iamService.findRole(arn.accountId(), name)+ .filter(role -> IamService.roleArnMatches(roleArn, role))+ .filter(role -> trust.allowsService(role.getAssumeRolePolicyDocument(), LAMBDA, sourceArn,+ sourceAccount))+ .isPresent();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebInternalServerException.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebInternalServerException.javaindex ce249f5934..d28c39b6d9 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebInternalServerException.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebInternalServerException.java@@ -1,11 +1,16 @@package io.github.hectorvent.floci.services.lambdaweb;-import io.github.hectorvent.floci.core.common.AwsException;+import java.util.Map;/** An internal error. AWS answers it with the type in the header and the body {@code {}}. */-public final class LambdaWebInternalServerException extends AwsException {+public final class LambdaWebInternalServerException extends LambdaWebErrorBodyException {LambdaWebInternalServerException() {super("InternalServerException", null, 500);}++ @Override+ Map<String, String> body() {+ return Map.of();+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.javaindex c89ca6fd3d..e384a49601 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java@@ -140,6 +140,7 @@ public class LambdaWebService implements Resettable {private final LambdaWebCode code;private final ObjectMapper objectMapper;private final Instance<RequestContext> requestContext;+ private final LambdaWebExecutionRole executionRole;/** Keyed {@code region/functionName}. The backend adds the caller's account to every key. */private StorageBackend<String, WebFunction> functions;@@ -152,7 +153,7 @@ public class LambdaWebService implements Resettable {@Injectpublic LambdaWebService(RegionResolver regionResolver, StorageFactory storageFactory, EmulatorConfig config,S3Service s3Service, LambdaWebCode code, ObjectMapper objectMapper,- Instance<RequestContext> requestContext) {+ Instance<RequestContext> requestContext, LambdaWebExecutionRole executionRole) {this.regionResolver = regionResolver;this.storageFactory = storageFactory;this.config = config;@@ -160,6 +161,7 @@ public class LambdaWebService implements Resettable {this.code = code;this.objectMapper = objectMapper;this.requestContext = requestContext;+ this.executionRole = executionRole;}@PostConstruct@@ -301,7 +303,7 @@ public class LambdaWebService implements Resettable {"The revisionConfig and endpointConfig must be specified.", 400);}requireValidTags(tags);- validateRevisionRules(revisionConfig);+ validateRevisionRules(region, revisionConfig);String accountId = regionResolver.getAccountId();WebFunctionEndpoint endpoint = draftEndpoint(region, accountId, functionName, endpointConfig, false);return storeNewFunction(region, functionName, tags, fn -> {@@ -401,8 +403,8 @@ public class LambdaWebService implements Resettable {LambdaWebValidation validation = new LambdaWebValidation();validateRevisionShape(validation, request, "");validation.throwIfAny();- validateRevisionRules(request);String functionName = resolveFunctionName(region, functionNameOrArn, "CreateWebFunctionRevision");+ validateRevisionRules(region, request);synchronized (lockFor(region, functionName)) {WebFunction fn = function(region, functionName);WebFunctionRevision revision = buildRevision(fn, request);@@ -507,8 +509,12 @@ public class LambdaWebService implements Resettable {}/** The rules a revision request must meet before the function is looked up. */- private static void validateRevisionRules(JsonNode request) {+ private void validateRevisionRules(String region, JsonNode request) {JsonNode service = LambdaWebJson.structure(request, "serviceConfig");+ String role = LambdaWebJson.text(service, "executionRoleArn");+ if (!AwsArnUtils.parse(role).accountId().equals(regionResolver.getAccountId())) {+ throw new LambdaWebAccessDeniedException("Cross-account pass role is not allowed.");+ }Map<String, String> environment = LambdaWebJson.stringMap(service, "environmentVariables", false);if (environment != null) {List<String> reserved = environment.keySet().stream().filter(RESERVED_ENVIRONMENT_KEYS::contains).toList();@@ -522,6 +528,7 @@ public class LambdaWebService implements Resettable {throw new AwsException("ValidationException", "The logGroup " + logGroup+ " is invalid. Log group names starting with aws/ (case-insensitive) are reserved for AWS.", 400);}+ executionRole.requireAssumable(region, role);}private WebFunctionRevision buildRevision(WebFunction fn, JsonNode request) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaWebIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaWebIntegrationTest.javaindex db29ab752e..ffbe923ac2 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaWebIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaWebIntegrationTest.java@@ -1,6 +1,8 @@package io.github.hectorvent.floci.services.cloudformation;import io.github.hectorvent.floci.core.common.XmlParser;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebRoles;import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;import io.github.hectorvent.floci.services.s3.S3Service;import io.quarkus.test.junit.QuarkusTest;@@ -36,8 +38,12 @@ class CloudFormationLambdaWebIntegrationTest {@InjectS3Service s3Service;+ @Inject+ IamService iamService;+@Testvoid stackProvisionsFunctionRevisionAndEndpoint() {+ LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());String suffix = Long.toString(System.nanoTime(), 36);@@ -103,6 +109,7 @@ class CloudFormationLambdaWebIntegrationTest {@Testvoid aRevisionOnCodeThatIsNotAZipFailsItsResource() {+ LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/cfn-web");s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());s3Service.putObject(BUCKET, "notzip.zip", "this is not a zip\n".getBytes(StandardCharsets.UTF_8),diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginServingTest.javaindex e5c62c4066..33bd08aa8f 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginServingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginServingTest.java@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehaviorimport io.github.hectorvent.floci.services.cloudfront.model.Distribution;import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;import io.github.hectorvent.floci.services.cloudfront.model.Origin;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebRoles;import io.github.hectorvent.floci.services.lambdaweb.LambdaWebZips;import io.github.hectorvent.floci.services.s3.S3Service;import io.github.hectorvent.floci.testing.PartitionCleanup;@@ -38,13 +40,16 @@ class CloudFrontWebFunctionOriginServingTest {@InjectS3Service s3Service;+ @Inject+ IamService iamService;+@RegisterExtensionfinal PartitionCleanup cleanup = new PartitionCleanup();@Testvoid anEndpointOriginIsReachedWhateverPortAndProtocolTheOriginNames() {String functionName = "cf-disabled-" + Long.toString(System.nanoTime(), 36);- String domain = createFunction(s3Service, cleanup, functionName, "ApplicationManaged");+ String domain = createFunction(s3Service, iamService, cleanup, functionName, "ApplicationManaged");given().contentType("application/json").body("{\"throttleConfig\": {\"rateLimit\": 0}}").when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev").then().statusCode(202);@@ -59,7 +64,7 @@ class CloudFrontWebFunctionOriginServingTest {@Testvoid anIamAuthEndpointRefusesTheUnsignedRequestOfADistributionWithoutOriginAccessControl() {- String domain = createFunction(s3Service, cleanup, "cf-iam-" + Long.toString(System.nanoTime(), 36), "IamAuth");+ String domain = createFunction(s3Service, iamService, cleanup, "cf-iam-" + Long.toString(System.nanoTime(), 36), "IamAuth");Distribution created = createDistribution(cloudFrontService, cleanup, domain,CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);@@ -72,7 +77,7 @@ class CloudFrontWebFunctionOriginServingTest {@Testvoid forwardingTheViewerHostToAnEndpointIsABadGateway() {- String domain = createFunction(s3Service, cleanup, "cf-host-" + Long.toString(System.nanoTime(), 36),+ String domain = createFunction(s3Service, iamService, cleanup, "cf-host-" + Long.toString(System.nanoTime(), 36),"ApplicationManaged");Distribution created = createDistribution(cloudFrontService, cleanup, domain,CloudFrontService.MANAGED_ALL_VIEWER_ORIGIN_REQUEST_POLICY_ID);@@ -81,7 +86,9 @@ class CloudFrontWebFunctionOriginServingTest {.then().statusCode(502);}- static String createFunction(S3Service s3Service, PartitionCleanup cleanup, String functionName, String authType) {+ static String createFunction(S3Service s3Service, IamService iamService, PartitionCleanup cleanup,+ String functionName, String authType) {+ LambdaWebRoles.trustLambda(iamService, ROLE);s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of());String domain = given().contentType("application/json")diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginTlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginTlsIntegrationTest.javaindex e591b3f076..82a241b4c4 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginTlsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebFunctionOriginTlsIntegrationTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudfront;import io.github.hectorvent.floci.config.SelfSignedTlsProfile;import io.github.hectorvent.floci.services.cloudfront.model.Distribution;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.s3.S3Service;import io.github.hectorvent.floci.testing.PartitionCleanup;import io.quarkus.test.junit.QuarkusTest;@@ -31,12 +32,15 @@ class CloudFrontWebFunctionOriginTlsIntegrationTest {@InjectS3Service s3Service;+ @Inject+ IamService iamService;+@RegisterExtensionfinal PartitionCleanup cleanup = new PartitionCleanup();@Testvoid aViewerOverTlsReachesAnEndpointOrigin() {- String domain = createFunction(s3Service, cleanup, "cf-tls-" + Long.toString(System.nanoTime(), 36), "IamAuth");+ String domain = createFunction(s3Service, iamService, cleanup, "cf-tls-" + Long.toString(System.nanoTime(), 36), "IamAuth");Distribution created = createDistribution(cloudFrontService, cleanup, domain,CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.javaindex 02ecf86fa1..90331588b9 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java@@ -421,6 +421,45 @@ class AssumeRolePolicyEvaluatorTest {assertFalse(evaluator.allows(doc, CALLER, CALLER_ACCOUNT, Map.of()));}+ @Test+ void aWildcardPrincipalNamesAServiceToo() {+ assertTrue(evaluator.allowsService(trust("{\"AWS\":\"*\"}"), "lambda.amazonaws.com"));+ assertTrue(evaluator.allowsService(trust("{\"AWS\":[\"*\"]}"), "lambda.amazonaws.com", null, null));+ assertTrue(evaluator.allowsService(trust("\"*\""), "lambda.amazonaws.com", null, null));+ assertFalse(evaluator.allowsService(trust("{\"AWS\":\"arn:aws:iam::000000000000:root\"}"),+ "lambda.amazonaws.com", null, null));+ String denied = """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"},+ {"Effect":"Deny","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"}]}+ """;+ assertFalse(evaluator.allowsService(denied, "lambda.amazonaws.com"));+ assertFalse(evaluator.allowsService(denied, "lambda.amazonaws.com", null, null));+ }++ @Test+ void serviceTrustSeesThePrincipalKeysOfTheService() {+ assertTrue(evaluator.allowsService(serviceTrust("{\"Bool\":{\"aws:PrincipalIsAWSService\":\"true\"}}"),+ "lambda.amazonaws.com", null, null));+ assertTrue(evaluator.allowsService(+ serviceTrust("{\"StringEquals\":{\"aws:PrincipalServiceName\":\"lambda.amazonaws.com\"}}"),+ "lambda.amazonaws.com", null, null));+ assertFalse(evaluator.allowsService(serviceTrust("{\"Bool\":{\"aws:PrincipalIsAWSService\":\"false\"}}"),+ "lambda.amazonaws.com", null, null));+ assertFalse(evaluator.allowsService(serviceTrust("{\"Null\":{\"aws:PrincipalIsAWSService\":\"true\"}}"),+ "lambda.amazonaws.com", null, null));+ assertFalse(evaluator.allowsService(serviceTrust("{\"Null\":{\"aws:PrincipalServiceName\":\"true\"}}"),+ "lambda.amazonaws.com", null, null));+ }++ private static String serviceTrust(String condition) {+ return """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole",+ "Condition":%s}]}+ """.formatted(condition);+ }+@Testvoid serviceTrustEvaluatesNegatedSourceConditions() {String doc = """diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.javaindex b6ad25b311..1c915b238c 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneDockerIntegrationTest.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.Distribution;import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;import io.github.hectorvent.floci.services.cloudfront.model.Origin;import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManager.Environment;import io.github.hectorvent.floci.services.s3.S3Service;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;@@ -125,6 +126,9 @@ class LambdaWebDataPlaneDockerIntegrationTest {@InjectS3Service s3Service;+ @Inject+ IamService iamService;+@InjectLambdaWebEnvironmentManager environments;@@ -531,6 +535,7 @@ class LambdaWebDataPlaneDockerIntegrationTest {private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment, String systemLogLevel,String mode, String authType, String nodeOptions) throws IOException {functionName = "dp-docker-" + Long.toString(System.nanoTime(), 36);+ LambdaWebRoles.trustLambda(iamService, ROLE);s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, functionName + ".zip", zip(APP), "application/zip", Map.of());return given().contentType("application/json")diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.javaindex 180949790a..d75d2e31fc 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebDataPlaneIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.lambdaweb;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.s3.S3Service;import io.quarkus.test.junit.QuarkusTest;import io.restassured.RestAssured;@@ -37,6 +38,9 @@ class LambdaWebDataPlaneIntegrationTest {@InjectS3Service s3Service;+ @Inject+ IamService iamService;+@InjectLambdaWebMetrics metrics;@@ -126,6 +130,35 @@ class LambdaWebDataPlaneIntegrationTest {given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);}+ @Test+ void anEnvironmentDoesNotStartWhenLambdaCanNoLongerAssumeTheRole() {+ String functionName = "dp-role-" + Long.toString(System.nanoTime(), 36);+ String domain = createFunction(functionName, "ApplicationManaged", LambdaWebZips.indexJs(""),+ "arn:aws:iam::000000000000:role/" + functionName);+ iamService.updateAssumeRolePolicy(functionName, """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""");++ Response response = given().header("Host", domain).when().get("/");+ response.then().statusLine("HTTP/1.1 502 Bad Gateway")+ .header("content-type", "text/html")+ .header("connection", "keep-alive")+ .header("lambda-web-error-type", "Platform.CannotAssumeRole")+ .header("lambda-web-request-id", matchesPattern(REQUEST_ID))+ .header("lambda-web-logstream", nullValue())+ .header("content-length", "228")+ .body(equalTo(LambdaWebErrorPages.html(LambdaWebErrorPages.CANNOT_ASSUME_ROLE,+ response.header("lambda-web-request-id"))));++ iamService.deleteRole(functionName);+ given().header("Host", domain).when().get("/")+ .then().statusCode(502).header("lambda-web-error-type", "Platform.CannotAssumeRole");+ given().contentType("application/json").body("{}")+ .when().post(BASE + "/web-functions/" + functionName + "/list-revisions")+ .then().statusCode(200).body("revisions[0].state", equalTo("Active"));+ given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);+ }+private static String readUntil(InputStream in, String end) throws IOException {StringBuilder read = new StringBuilder();while (!read.toString().endsWith(end)) {@@ -282,6 +315,11 @@ class LambdaWebDataPlaneIntegrationTest {}private String createFunction(String functionName, String authType, byte[] code) {+ return createFunction(functionName, authType, code, ROLE);+ }++ private String createFunction(String functionName, String authType, byte[] code, String role) {+ LambdaWebRoles.trustLambda(iamService, role);s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, "app.zip", code, "application/zip", Map.of());return given().contentType("application/json")@@ -293,7 +331,7 @@ class LambdaWebDataPlaneIntegrationTest {"serviceConfig": {"executionRoleArn": "%s"}},"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion","authType": "%s", "autoDeploymentMode": "LatestRevision"}}- """.formatted(functionName, BUCKET, ROLE, authType))+ """.formatted(functionName, BUCKET, role, authType)).when().put(BASE + "/web-functions").then().statusCode(202).extract().path("endpoint.domainName");diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.javaindex e32eb4e528..5018d494b7 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebEnvironmentManagerTest.java@@ -1,17 +1,36 @@package io.github.hectorvent.floci.services.lambdaweb;+import com.github.dockerjava.api.DockerClient;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;+import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;+import io.github.hectorvent.floci.services.lambda.launcher.ImageResolver;+import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;+import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManager.Environment;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManager.StartFailure;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;import org.junit.jupiter.api.Test;import java.time.Duration;import java.util.ArrayList;import java.util.List;+import java.util.Optional;import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;class LambdaWebEnvironmentManagerTest {@@ -53,6 +72,36 @@ class LambdaWebEnvironmentManagerTest {assertEquals(defaults, LambdaWebEnvironmentManager.nodeFlags("\"--max-old-space-size=1536\""));}+ @Test+ void aRoleDeletedAfterTheTrustCheckStartsNoContainer() {+ LambdaWebExecutionRole executionRole = mock(LambdaWebExecutionRole.class);+ when(executionRole.assumableFor(any(), any(), any())).thenReturn(true);+ LambdaExecutionRoleCredentials credentials = mock(LambdaExecutionRoleCredentials.class);+ when(credentials.forRole(any(), any(), any())).thenReturn(Optional.empty());+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);+ LambdaWebEnvironmentManager manager = new LambdaWebEnvironmentManager(+ mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), containerBuilder,+ mock(ContainerLifecycleManager.class), mock(DockerClient.class), mock(ImageResolver.class),+ mock(EcrRegistryManager.class), mock(LambdaWebCode.class), mock(ZipExtractor.class),+ mock(LaunchedContainerAwsEnv.class), credentials, executionRole, mock(LambdaWebLogs.class),+ mock(LambdaWebMetrics.class));+ WebFunction fn = new WebFunction();+ fn.functionName = "fn";+ fn.functionArn = "arn:aws:lambda:us-east-1:000000000000:web-function/fn";+ WebFunctionRevision revision = new WebFunctionRevision();+ revision.revisionId = "1";+ revision.buildConfig.runtime = "nodejs24.x";+ revision.serviceConfig.executionRoleArn = "arn:aws:iam::000000000000:role/web";+ try {+ StartFailure failure = assertThrows(StartFailure.class,+ () -> manager.acquire("000000000000", "us-east-1", fn, "endpoint", null, revision));+ assertEquals(LambdaWebErrorPages.CANNOT_ASSUME_ROLE, failure.page());+ verifyNoInteractions(containerBuilder);+ } finally {+ manager.shutdown();+ }+ }+private static List<String> flags(List<String> heap) {List<String> flags = new ArrayList<>(BASE);flags.addAll(heap);diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebExecutionRoleTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebExecutionRoleTest.javanew file mode 100644index 0000000000..0f570af0dd--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebExecutionRoleTest.java@@ -0,0 +1,142 @@+package io.github.hectorvent.floci.services.lambdaweb;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.model.IamRole;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Optional;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++class LambdaWebExecutionRoleTest {++ private static final String REGION = "us-east-1";+ private static final String ACCOUNT = "000000000000";+ private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:web-function/app";+ private static final String LAMBDA = "{\"Service\":\"lambda.amazonaws.com\"}";++ private final IamService iamService = mock(IamService.class);+ private final ObjectMapper mapper = new ObjectMapper();+ private final LambdaWebExecutionRole executionRole = new LambdaWebExecutionRole(iamService,+ new AssumeRolePolicyEvaluator(mapper, new IamPolicyEvaluator(mapper)));++ @Test+ void aRevisionNeedsARoleThatTrustsLambdaWithNoSourceGiven() {+ assertTrue(creates(role("lambda", "/", statement("Allow", LAMBDA, "sts:AssumeRole", null))));+ assertTrue(creates(role("array", "/", statement("Allow",+ "{\"Service\":[\"ec2.amazonaws.com\",\"lambda.amazonaws.com\"]}", "sts:AssumeRole", null))));+ assertTrue(creates(role("path", "/service-role/", statement("Allow", LAMBDA, "sts:AssumeRole", null))));+ assertTrue(creates(role("no-arn", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"Null\":{\"aws:SourceArn\":\"true\"}}"))));+ assertTrue(creates(role("no-account", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"Null\":{\"aws:SourceAccount\":\"true\"}}"))));++ assertFalse(creates("arn:aws:iam::000000000000:role/missing"));+ assertFalse(creates(role("ec2", "/", statement("Allow", "{\"Service\":\"ec2.amazonaws.com\"}",+ "sts:AssumeRole", null))));+ assertFalse(creates(role("deny", "/", statement("Allow", LAMBDA, "sts:AssumeRole", null) + ","+ + statement("Deny", LAMBDA, "sts:AssumeRole", null))));+ assertFalse(creates(role("account", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"StringEquals\":{\"aws:SourceAccount\":\"" + ACCOUNT + "\"}}"))));+ assertFalse(creates(role("arn", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"ArnEquals\":{\"aws:SourceArn\":\"" + FUNCTION_ARN + "\"}}"))));+ assertFalse(creates(role("root", "/", statement("Allow", "{\"AWS\":\"arn:aws:iam::" + ACCOUNT + ":root\"}",+ "sts:AssumeRole", null))));+ assertFalse(creates(role("tag", "/", statement("Allow", LAMBDA, "sts:TagSession", null))));+ assertFalse(creates("arn:aws:iam::000000000000:role/path"));+ String lambda = role("lambda", "/", statement("Allow", LAMBDA, "sts:AssumeRole", null));+ Optional<IamRole> found = iamService.findRole(ACCOUNT, "lambda");+ when(iamService.findRole(ACCOUNT, "LAMBDA")).thenReturn(found);+ assertFalse(creates(lambda.replace("lambda", "LAMBDA")));+ assertFalse(creates(lambda.replace("arn:aws:", "arn:aws-cn:")));+ }++ @Test+ void theRefusalNamesTheRoleAndLambda() {+ AwsException refused = assertThrows(AwsException.class,+ () -> executionRole.requireAssumable(REGION, "arn:aws:iam::000000000000:role/missing"));+ assertEquals("ValidationException", refused.getErrorCode());+ assertEquals(400, refused.getHttpStatus());+ assertEquals("The execution role arn:aws:iam::000000000000:role/missing cannot be assumed by"+ + " lambda.amazonaws.com. Verify its trust policy. If the role was just created, retry in a few"+ + " seconds.", refused.getMessage());+ }++ @Test+ void anEnvironmentAssumesTheRoleWithTheFunctionAsItsSource() {+ assertTrue(starts(role("account", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"StringEquals\":{\"aws:SourceAccount\":\"" + ACCOUNT + "\"}}"))));+ assertTrue(starts(role("arn", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"ArnEquals\":{\"aws:SourceArn\":\"" + FUNCTION_ARN + "\"}}"))));++ assertFalse(starts(role("no-arn", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"Null\":{\"aws:SourceArn\":\"true\"}}"))));+ assertFalse(starts(role("ec2", "/", statement("Allow", "{\"Service\":\"ec2.amazonaws.com\"}",+ "sts:AssumeRole", null))));+ assertFalse(starts("arn:aws:iam::000000000000:role/missing"));+ }++ @Test+ void lambdaAssumesTheRoleAsAServicePrincipal() {+ String allow = statement("Allow", LAMBDA, "sts:AssumeRole", null);+ List<String> accepted = List.of(+ role("everyone", "/", statement("Allow", "{\"AWS\":\"*\"}", "sts:AssumeRole", null)),+ role("service", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"Bool\":{\"aws:PrincipalIsAWSService\":\"true\"}}")),+ role("service-name", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"StringEquals\":{\"aws:PrincipalServiceName\":\"lambda.amazonaws.com\"}}")));+ List<String> refused = List.of(+ role("deny-everyone", "/", allow + ","+ + statement("Deny", "{\"AWS\":\"*\"}", "sts:AssumeRole", null)),+ role("not-service", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"Bool\":{\"aws:PrincipalIsAWSService\":\"false\"}}")),+ role("no-service", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"Null\":{\"aws:PrincipalIsAWSService\":\"true\"}}")),+ role("no-service-name", "/", statement("Allow", LAMBDA, "sts:AssumeRole",+ "{\"Null\":{\"aws:PrincipalServiceName\":\"true\"}}")));+ for (String roleArn : accepted) {+ assertTrue(creates(roleArn), roleArn);+ assertTrue(starts(roleArn), roleArn);+ }+ for (String roleArn : refused) {+ assertFalse(creates(roleArn), roleArn);+ assertFalse(starts(roleArn), roleArn);+ }+ }++ private boolean creates(String roleArn) {+ try {+ executionRole.requireAssumable(REGION, roleArn);+ return true;+ } catch (AwsException e) {+ return false;+ }+ }++ private boolean starts(String roleArn) {+ return executionRole.assumableFor(REGION, FUNCTION_ARN, roleArn);+ }++ private String role(String name, String path, String statements) {+ String arn = "arn:aws:iam::" + ACCOUNT + ":role" + path + name;+ IamRole role = new IamRole("AROA" + name, name, path, arn,+ "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");+ when(iamService.findRole(ACCOUNT, name)).thenReturn(Optional.of(role));+ return arn;+ }++ private static String statement(String effect, String principal, String action, String condition) {+ return "{\"Effect\":\"" + effect + "\",\"Principal\":" + principal + ",\"Action\":\"" + action + "\""+ + (condition == null ? "" : ",\"Condition\":" + condition) + "}";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIamAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIamAuthIntegrationTest.javaindex 1c6acdff69..8b6a6b312e 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIamAuthIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIamAuthIntegrationTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.lambdaweb;import com.github.dockerjava.api.DockerClient;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.s3.S3Service;import io.github.hectorvent.floci.testing.EnforcementFixtures;import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;@@ -52,6 +53,9 @@ class LambdaWebIamAuthIntegrationTest {@InjectS3Service s3Service;+ @Inject+ IamService iamService;+@InjectLambdaWebEnvironmentManager environments;@@ -65,6 +69,7 @@ class LambdaWebIamAuthIntegrationTest {@BeforeEachvoid createFunction() throws IOException {functionName = "iam-auth-" + Long.toString(System.nanoTime(), 36);+ LambdaWebRoles.trustLambda(iamService, "arn:aws:iam::000000000000:role/web");s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, functionName + ".zip", zip(), "application/zip", Map.of());int port = baseUri.getPort();diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.javaindex b28c3ba6ee..45c10ce103 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.lambdaweb;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.s3.S3Service;import io.quarkus.test.junit.QuarkusTest;import jakarta.inject.Inject;@@ -45,12 +46,16 @@ class LambdaWebIntegrationTest {@InjectS3Service s3Service;+ @Inject+ IamService iamService;+private static String revision1;private static String revision2;private static String domainName;@BeforeAllvoid seedCode() {+ LambdaWebRoles.trustLambda(iamService, ROLE);s3Service.createBucket(BUCKET, "us-east-1");s3Service.putObject(BUCKET, KEY, LambdaWebZips.indexJs(""), "application/zip", Map.of());}@@ -394,6 +399,27 @@ class LambdaWebIntegrationTest {.body("message", equalTo("The environmentVariables cannot contain reserved keys."+ " The request specified the reserved keys [AWS_REGION]."));+ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}}+ """.formatted(BUILD, "arn:aws:iam::000000000000:role/web-it-missing"))+ .when().post(revisions)+ .then().statusCode(400)+ .header("X-Amzn-Errortype", "ValidationException")+ .body("message", equalTo("The execution role arn:aws:iam::000000000000:role/web-it-missing cannot be"+ + " assumed by lambda.amazonaws.com. Verify its trust policy. If the role was just created,"+ + " retry in a few seconds."));++ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}}+ """.formatted(BUILD, ROLE.replace("000000000000", "111122223333")))+ .when().post(revisions)+ .then().statusCode(403)+ .header("X-Amzn-Errortype", "AccessDeniedException")+ .body("Message", equalTo("Cross-account pass role is not allowed."))+ .body("message", nullValue());+given().contentType("application/json").body("""{"buildConfig": %s, "serviceConfig": {}}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebRoles.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebRoles.javanew file mode 100644index 0000000000..06fd9bd28a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebRoles.java@@ -0,0 +1,24 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.services.iam.IamService;++/** Execution roles for tests that create Web Function revisions. */+public final class LambdaWebRoles {++ private static final String LAMBDA_TRUST = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";++ private LambdaWebRoles() {+ }++ /** Creates the role {@code roleArn} names, trusting Lambda, unless it exists. */+ public static void trustLambda(IamService iamService, String roleArn) {+ AwsArnUtils.Arn arn = AwsArnUtils.parse(roleArn);+ String name = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);+ if (iamService.findRole(arn.accountId(), name).isEmpty()) {+ iamService.createRole(name, "/", LAMBDA_TRUST, null, 0, null);+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.javaindex 14a2d99988..faeaaa8ed8 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java@@ -70,10 +70,15 @@ class LambdaWebServiceTest {}private LambdaWebService service(StorageFactory storage, String baseUrl, S3Service s3Service) {+ return service(storage, baseUrl, s3Service, mock(LambdaWebExecutionRole.class));+ }++ private LambdaWebService service(StorageFactory storage, String baseUrl, S3Service s3Service,+ LambdaWebExecutionRole executionRole) {EmulatorConfig config = mock(EmulatorConfig.class);when(config.effectiveBaseUrl()).thenReturn(baseUrl);LambdaWebService service = new LambdaWebService(new RegionResolver(REGION, ACCOUNT_ID), storage, config,- s3Service, new LambdaWebCode(storageDir.resolve("code")), mapper, null);+ s3Service, new LambdaWebCode(storageDir.resolve("code")), mapper, null, executionRole);service.initializeStorage();return service;}@@ -87,6 +92,12 @@ class LambdaWebServiceTest {return config;}+ private ObjectNode revisionConfig(String executionRoleArn) {+ ObjectNode config = revisionConfig(30);+ ((ObjectNode) config.get("serviceConfig")).put("executionRoleArn", executionRoleArn);+ return config;+ }+private ObjectNode endpointConfig(String name) {return mapper.createObjectNode().put("endpointName", name).put("endpointType", "HomeRegion").put("authType", "ApplicationManaged").put("autoDeploymentMode", "LatestRevision");@@ -276,6 +287,43 @@ class LambdaWebServiceTest {error(() -> service.updateEndpoint(REGION, "missing", "dev", update)).getErrorCode());}+ @Test+ void executionRoleIsCheckedInTheOrderAwsChecksIt() {+ String missingRole = "arn:aws:iam::000000000000:role/missing";+ LambdaWebExecutionRole executionRole = mock(LambdaWebExecutionRole.class);+ doThrow(new AwsException("ValidationException", "cannot be assumed", 400))+ .when(executionRole).requireAssumable(REGION, missingRole);+ LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", null, executionRole);+ service.createFunction(REGION, createRequest("app"));++ ObjectNode otherAccount = revisionConfig("arn:aws:iam::111122223333:role/web");+ ((ObjectNode) otherAccount.get("serviceConfig")).putObject("environmentVariables").put("AWS_REGION", "x");+ assertEquals("Invalid function name or ARN 'bad.name'",+ message(() -> service.createRevision(REGION, "bad.name", otherAccount)));+ AwsException denied = error(() -> service.createRevision(REGION, "missing", otherAccount));+ assertEquals("AccessDeniedException", denied.getErrorCode());+ assertEquals(403, denied.getHttpStatus());+ assertEquals("Cross-account pass role is not allowed.", denied.getMessage());++ ObjectNode reserved = revisionConfig(missingRole);+ ((ObjectNode) reserved.get("serviceConfig")).putObject("environmentVariables").put("AWS_REGION", "x");+ assertEquals("The environmentVariables cannot contain reserved keys. The request specified the reserved keys"+ + " [AWS_REGION].", message(() -> service.createRevision(REGION, "app", reserved)));++ ObjectNode runtime = revisionConfig(missingRole);+ ((ObjectNode) runtime.path("buildConfig").path("runtimeConfig")).put("runtime", "nodejs22.x");+ assertEquals("cannot be assumed", message(() -> service.createRevision(REGION, "missing", runtime)));+ assertEquals("cannot be assumed", message(() -> service.createRevision(REGION, "app", runtime)));++ ObjectNode existing = createRequest("app");+ existing.set("revisionConfig", revisionConfig(missingRole));+ assertEquals("cannot be assumed", message(() -> service.createFunction(REGION, existing)));+ ObjectNode multiRegion = createRequest("other");+ multiRegion.set("revisionConfig", revisionConfig(missingRole));+ ((ObjectNode) multiRegion.get("endpointConfig")).put("endpointType", "MultiRegion");+ assertEquals("cannot be assumed", message(() -> service.createFunction(REGION, multiRegion)));+ }+@Testvoid aRejectedEndpointUpdateChangesNothing() {LambdaWebService service = service();