mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambdaweb): check the execution role as AWS does (#6347)
* feat(lambdaweb): check the execution role as AWS does
AWS refuses a revision whose execution role is in another account with
403 AccessDeniedException. It refuses a role that does not exist or does
not trust lambda.amazonaws.com with 400 ValidationException, and that
check gives no aws:SourceAccount or aws:SourceArn. An environment
assumes the role with the function as its source, and a request gets
502 Platform.CannotAssumeRole when Lambda can no longer assume it.
* fix(iam): match a wildcard principal and the service keys in service trust
{"AWS": "*"} lets Lambda assume a role, and a Deny on it refuses the role.
Lambda sets aws:PrincipalIsAWSService to true and aws:PrincipalServiceName
to its principal when it checks the role and when an environment assumes it.
* fix(lambdaweb): answer CannotAssumeRole when the role goes during a start
A role deleted after the trust check gave the container the account's
placeholder credentials. AWS answers 502 Platform.CannotAssumeRole for a
deleted role.
This commit is contained in:
1 parent
99171dcbe0
commit
7e6439cf86
24 files changed
+605
-44
No files matched your search
+7
@@ -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 {
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Test
|
||||
void 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 {
|
||||
|
||||
@Test
|
||||
void 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),
|
||||
|
||||
+11
-4
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior
|
||||
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.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 {
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void 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 {
|
||||
|
||||
@Test
|
||||
void 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 {
|
||||
|
||||
@Test
|
||||
void 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")
|
||||
|
||||
+5
-1
@@ -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 {
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void 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);
|
||||
|
||||
|
||||
+39
@@ -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);
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceTrustEvaluatesNegatedSourceConditions() {
|
||||
String doc = """
|
||||
|
||||
+5
@@ -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 {
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
LambdaWebEnvironmentManager 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")
|
||||
|
||||
+39
-1
@@ -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 {
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
LambdaWebMetrics 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");
|
||||
|
||||
+49
@@ -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);
|
||||
|
||||
+142
@@ -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) + "}";
|
||||
}
|
||||
}
|
||||
+5
@@ -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 {
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
LambdaWebEnvironmentManager environments;
|
||||
|
||||
@@ -65,6 +69,7 @@ class LambdaWebIamAuthIntegrationTest {
|
||||
@BeforeEach
|
||||
void 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();
|
||||
|
||||
+26
@@ -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 {
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
private static String revision1;
|
||||
private static String revision2;
|
||||
private static String domainName;
|
||||
|
||||
@BeforeAll
|
||||
void 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": {}}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
-1
@@ -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)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRejectedEndpointUpdateChangesNothing() {
|
||||
LambdaWebService service = service();
|
||||
|
||||
Reference in new issue
Block a user