mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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
+27
-18
@@ -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 (service.isArray()) {
|
||||
for (JsonNode entry : service) {
|
||||
if (entry.isTextual() && ServicePrincipals.canonical(entry.asText()).equals(wanted)) {
|
||||
if (node.isTextual()) {
|
||||
return matches.test(node.asText());
|
||||
}
|
||||
if (node.isArray()) {
|
||||
for (JsonNode entry : node) {
|
||||
if (entry.isTextual() && matches.test(entry.asText())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
+16
@@ -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());
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -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))
|
||||
|
||||
+15
@@ -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();
|
||||
}
|
||||
+3
-5
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+53
@@ -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();
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@Inject
|
||||
public 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) {
|
||||
|
||||
Reference in new issue
Block a user