Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(lambdaweb): reject resource policies whose principal does not exist (#6769)

TATSUNO “Taz” Yasuhiro701b04c41033
diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.md
index 89cfe10198..9bc2c36eb4 100644
--- a/docs/services/lambda-web-functions.md
+++ b/docs/services/lambda-web-functions.md
@@ -41,12 +41,12 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A
- **Revision cleanup:** when a revision turns `Active` and the function has more than 50, the oldest revisions that no endpoint routes to are deleted until 50 are left, `Failed` ones included, as on AWS. A new `Failed` revision deletes nothing. The revision that a `LatestRevision` endpoint leaves is not deleted before the next revision turns `Active`, as on AWS.
- **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.
- **Egress network connectors:** `egressNetworkConnectorArn` names a connector version by the connector id, in the function's region, as on AWS. A version that does not exist, a connector name, or another region is `404 ResourceNotFoundException` "The egress network connector <arn> does not exist.". A connector without `WebFunction` in its `AssociatedComputeResourceTypes` is `400 ValidationException`. An unknown region, a partition that is not the region's, or a version such as `0` or `01` is `400 ValidationException` "The egress network connector ARN: '<arn>' is not valid. ...", and a connector in another account is `403 AccessDeniedException`. A version past the 64-bit range is `500 InternalServerException` with the body `{}`, as on AWS. Only a `HomeRegion` endpoint can serve such a revision: `CreateWebFunction` with another endpoint type, and weights of a `PerRegion` or `MultiRegion` endpoint that name such a revision, are `400 ValidationException`. Floci settles a connector at once, so the AWS refusal of a `PENDING` version never happens. When IAM enforcement is on, the caller also needs `lambda:PassNetworkConnector` on the version ARN as the request gives it, refused as on AWS (see [IAM](iam.md)). Floci checks it before the request reaches Lambda, so a refusal comes before the ARN checks above, which AWS runs first. The connector does not change the network of the function's container.
-- **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.
+- **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. Every principal has to exist, as on AWS. A role or user is looked up by its ARN in the account the ARN names, or by its unique id (`AROA...`, `AIDA...`) in the function's account, and a missing one, an assumed-role session, a `CanonicalUser` or an ARN in another partition is `400 ValidationException` "The provided principal was invalid. Please check the principal and try again.". A role or user named under a path other than its own is "The principal arn provided does not match the actual principal arn. Please check your input and try again.". The principals are looked up once every statement passes its other checks, and before any statement is refused as public. Floci holds every account, so any account id or root is taken to exist, and it keeps no list of service principals, so an unknown one is accepted. An `IamAuth` endpoint evaluates the policy on requests, as below.
- **Function names** are unique across the regions of an account, as on AWS. A name that another region already has is `409 ConflictException` "A function named <name> already exists in the account. Function names must be unique across all regions in an account.".
- **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.
- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`, all with the same id, as on AWS.
-- **Not implemented yet:** SigV4a on `MultiRegion` endpoints and the check that a policy's principal exists.
+- **Not implemented yet:** SigV4a on `MultiRegion` endpoints.
### `aws lambda-web deploy`
diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
index 602cf87366..956069f404 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/DsqlPrincipals.java
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.dsql;
-import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
@@ -64,16 +63,7 @@ public class DsqlPrincipals {
* account's root always does; a role or a user is looked up in its account by its name.
*/
public boolean exists(String arn) {
- AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
- String resource = parsed.resource();
- String name = resource.substring(resource.lastIndexOf('/') + 1);
- if (resource.startsWith("role/")) {
- return iamService.findRole(parsed.accountId(), name).isPresent();
- }
- if (resource.startsWith("user/")) {
- return iamService.findUser(parsed.accountId(), name).isPresent();
- }
- return "root".equals(resource);
+ return iamService.heldPrincipalArn(arn).isPresent();
}
private String accessKeyId() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index 318100ec78..c9dbd3672e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -1337,6 +1337,38 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return requested.region().isEmpty() && requested.resource().equals(expectedResource);
}
+ /**
+ * The ARN IAM holds what an IAM principal ARN names under: the account root as given, or the role or user
+ * of the name the ARN ends with in the ARN's account, at its own path. Empty for any other ARN, and for a
+ * role or user IAM does not hold.
+ */
+ public Optional<String> heldPrincipalArn(String principalArn) {
+ if (!AwsArnUtils.isArn(principalArn)) {
+ return Optional.empty();
+ }
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(principalArn);
+ String resource = arn.resource();
+ if (!"iam".equals(arn.service())) {
+ return Optional.empty();
+ }
+ if ("root".equals(resource)) {
+ return Optional.of(principalArn);
+ }
+ String name = resource.substring(resource.lastIndexOf('/') + 1);
+ if (resource.startsWith("role/")) {
+ return findRole(arn.accountId(), name).map(role -> heldArn(arn, "role", role.getPath(), role.getRoleName()));
+ }
+ if (resource.startsWith("user/")) {
+ return findUser(arn.accountId(), name).map(user -> heldArn(arn, "user", user.getPath(), user.getUserName()));
+ }
+ return Optional.empty();
+ }
+
+ private static String heldArn(AwsArnUtils.Arn named, String type, String path, String name) {
+ return AwsArnUtils.Arn.global(named.partition(), "iam", named.accountId(), type + normalizePath(path) + name)
+ .toString();
+ }
+
/**
* AWS publishes UnmodifiableEntity on twelve role actions, and its message names the linked
* service the caller has to go through instead. This guards the ten of them that refuse a
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPolicyPrincipals.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPolicyPrincipals.java
new file mode 100644
index 0000000000..fa27dcb795
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebPolicyPrincipals.java
@@ -0,0 +1,94 @@
+package io.github.hectorvent.floci.services.lambdaweb;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.iam.IamService;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+/**
+ * Whether the principals of a resource policy exist, as Lambda checks them before it stores the policy. A role
+ * or a user is looked up in the account its ARN names, or in the function's account by its unique id, and an ARN
+ * that names one under another path is refused on its own. Floci holds every account, so an account id or its
+ * root always exists, and it keeps no list of service principals, so those are not checked.
+ */
+@ApplicationScoped
+public class LambdaWebPolicyPrincipals {
+
+ private static final String OTHER_ARN = "The principal arn provided does not match the actual principal arn."
+ + " Please check your input and try again.";
+ private static final Pattern ACCOUNT_ID = Pattern.compile("[0-9]{12}");
+
+ private final IamService iamService;
+
+ @Inject
+ public LambdaWebPolicyPrincipals(IamService iamService) {
+ this.iamService = iamService;
+ }
+
+ /** Refuses the statement's {@code principal} when one it names does not exist in {@code partition}. */
+ void requireExisting(String partition, JsonNode principal) {
+ if (!principal.isObject()) {
+ return;
+ }
+ if (principal.has("CanonicalUser")) {
+ throw invalid();
+ }
+ JsonNode aws = principal.get("AWS");
+ if (aws == null) {
+ return;
+ }
+ List<String> values = new ArrayList<>();
+ if (aws.isTextual()) {
+ values.add(aws.textValue());
+ } else {
+ aws.forEach(value -> values.add(value.textValue()));
+ }
+ for (String value : values) {
+ requireExisting(partition, value);
+ }
+ }
+
+ private void requireExisting(String partition, String value) {
+ if ("*".equals(value) || ACCOUNT_ID.matcher(value).matches()) {
+ return;
+ }
+ if (!AwsArnUtils.isArn(value)) {
+ if (!heldUniqueId(value)) {
+ throw invalid();
+ }
+ return;
+ }
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(value);
+ if (!arn.partition().equals(partition) || !arn.region().isEmpty()
+ || !ACCOUNT_ID.matcher(arn.accountId()).matches()) {
+ throw invalid();
+ }
+ if ("iam".equals(arn.service())) {
+ String held = iamService.heldPrincipalArn(value).orElseThrow(LambdaWebPolicyPrincipals::invalid);
+ if (!AwsArnUtils.parse(held).resource().equals(arn.resource())) {
+ throw new AwsException("ValidationException", OTHER_ARN, 400);
+ }
+ return;
+ }
+ if ("sts".equals(arn.service()) && arn.resource().startsWith("federated-user/")) {
+ return;
+ }
+ throw invalid();
+ }
+
+ /** A role's or a user's unique id, as IAM gives it to one in the function's account. */
+ private boolean heldUniqueId(String id) {
+ return iamService.listRoles("/").stream().anyMatch(role -> id.equals(role.getRoleId()))
+ || iamService.listUsers("/").stream().anyMatch(user -> id.equals(user.getUserId()));
+ }
+
+ private static AwsException invalid() {
+ return new AwsException("ValidationException", LambdaWebService.INVALID_PRINCIPAL, 400);
+ }
+}
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.java
index 838cc26818..cc3d14635d 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
@@ -103,7 +103,7 @@ public class LambdaWebService implements Resettable {
"Sid", "Effect", "Principal", "NotPrincipal", "Action", "NotAction", "Resource", "NotResource", "Condition");
private static final Set<String> PRINCIPAL_KEYS = Set.of("AWS", "Service", "Federated", "CanonicalUser");
private static final String POLICY_SYNTAX = "Policy has syntax errors.";
- private static final String INVALID_PRINCIPAL = "The provided principal was invalid. Please check the principal and try again.";
+ static final String INVALID_PRINCIPAL = "The provided principal was invalid. Please check the principal and try again.";
private static final String NOT_A_ZIP = "Failed to read zip file: zip: not a valid zip file";
private static final String INVALID_TAGS = "One or more of your tags are invalid. Please ensure none of your tag keys"
+ " start with \"aws:\", none are empty, and there are no duplicate tag keys.";
@@ -153,6 +153,7 @@ public class LambdaWebService implements Resettable {
private final LambdaWebExecutionRole executionRole;
private final ServiceCallAuthorizer serviceCalls;
private final LambdaMicrovmsService microvmsService;
+ private final LambdaWebPolicyPrincipals policyPrincipals;
/** Keyed {@code region/functionName}. The backend adds the caller's account to every key. */
private StorageBackend<String, WebFunction> functions;
@@ -166,7 +167,8 @@ public class LambdaWebService implements Resettable {
public LambdaWebService(RegionResolver regionResolver, StorageFactory storageFactory, EmulatorConfig config,
S3Service s3Service, LambdaWebCode code, ObjectMapper objectMapper,
Instance<RequestContext> requestContext, LambdaWebExecutionRole executionRole,
- ServiceCallAuthorizer serviceCalls, LambdaMicrovmsService microvmsService) {
+ ServiceCallAuthorizer serviceCalls, LambdaMicrovmsService microvmsService,
+ LambdaWebPolicyPrincipals policyPrincipals) {
this.regionResolver = regionResolver;
this.storageFactory = storageFactory;
this.config = config;
@@ -177,6 +179,7 @@ public class LambdaWebService implements Resettable {
this.executionRole = executionRole;
this.serviceCalls = serviceCalls;
this.microvmsService = microvmsService;
+ this.policyPrincipals = policyPrincipals;
}
@PostConstruct
@@ -1332,7 +1335,7 @@ public class LambdaWebService implements Resettable {
.length("policy", policy, 1, 20480)
.pattern("revisionId", revisionId, POLICY_REVISION_ID)
.throwIfAny();
- validatePolicy(policy, resourceArn);
+ validatePolicy(region, policy, resourceArn);
String functionName = resolveFunctionName(region, resourceArn, "PutResourcePolicy");
synchronized (lockFor(region, functionName)) {
WebFunction fn = function(region, functionName);
@@ -1381,8 +1384,12 @@ public class LambdaWebService implements Resettable {
return new AwsException("ResourceNotFoundException", "The function does not have a policy.", 404);
}
- /** The checks AWS runs on a policy document before it looks the function up. */
- private void validatePolicy(String policy, String functionArn) {
+ /**
+ * The checks AWS runs on a policy document before it looks the function up. Every statement passes its own
+ * checks before any principal is looked up, and every principal exists before any statement is refused as
+ * public.
+ */
+ private void validatePolicy(String region, String policy, String functionArn) {
JsonNode document;
try {
document = objectMapper.readTree(policy);
@@ -1405,6 +1412,12 @@ public class LambdaWebService implements Resettable {
for (JsonNode statement : each) {
validateStatement(statement, functionArn);
}
+ for (JsonNode statement : each) {
+ policyPrincipals.requireExisting(regionResolver.partitionForRegion(region), statement.get("Principal"));
+ }
+ for (JsonNode statement : each) {
+ requireNotPublic(statement);
+ }
}
private static void validateStatement(JsonNode statement, String functionArn) {
@@ -1439,7 +1452,10 @@ public class LambdaWebService implements Resettable {
throw policySyntax();
}
}
- if (effect.equalsIgnoreCase("Allow") && isWildcardPrincipal(principal)
+ }
+
+ private static void requireNotPublic(JsonNode statement) {
+ if (statement.path("Effect").asText().equalsIgnoreCase("Allow") && isWildcardPrincipal(statement.get("Principal"))
&& !hasTrustedCondition(statement.path("Condition"))) {
throw new AwsException("ValidationException", "Lambda blocked the creation of this policy"
+ " because it would grant public access to your function.", 400);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index 92e1a9c31a..430e25020e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -92,6 +92,26 @@ class IamServiceTest {
);
}
+ @Test
+ void aPrincipalArnNamesTheRootOrTheRoleOrUserIamHoldsAtItsOwnPath() {
+ iamService.createRole("reader", "/team/", "{}", null, 3600, null);
+ iamService.createUser("writer", "/team/");
+ String role = "arn:aws:iam::000000000000:role/team/reader";
+ String user = "arn:aws:iam::000000000000:user/team/writer";
+
+ assertEquals(Optional.of(role), iamService.heldPrincipalArn(role));
+ assertEquals(Optional.of(role), iamService.heldPrincipalArn("arn:aws:iam::000000000000:role/reader"));
+ assertEquals(Optional.of(user), iamService.heldPrincipalArn("arn:aws:iam::000000000000:user/x/writer"));
+ assertEquals(Optional.of("arn:aws:iam::111122223333:root"),
+ iamService.heldPrincipalArn("arn:aws:iam::111122223333:root"));
+ assertEquals(Optional.of("arn:aws-cn:iam::000000000000:role/team/reader"),
+ iamService.heldPrincipalArn("arn:aws-cn:iam::000000000000:role/reader"));
+ for (String none : List.of("arn:aws:iam::000000000000:role/gone", "arn:aws:iam::000000000000:group/team",
+ "arn:aws:sts::000000000000:assumed-role/reader/s", "AROAREADER")) {
+ assertEquals(Optional.empty(), iamService.heldPrincipalArn(none), none);
+ }
+ }
+
@Test
void updateRoleDescriptionAnswersTheRoleAndMovesNothingElse() {
// "This operation performs the same function as the Description parameter in the UpdateRole
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.java
index c2790b419b..fe9cf82206 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
@@ -545,6 +545,32 @@ class LambdaWebIntegrationTest {
given().when().delete(policyPath)
.then().statusCode(404)
.body("message", equalTo("The function does not have a policy."));
+
+ // The roles a policy names have to exist, under the path IAM holds them.
+ String reader = "web-it-reader-" + Long.toString(System.nanoTime(), 36);
+ iamService.createRole(reader, "/team/", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}", null, 3600, null);
+ String named = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":"
+ + "{\"AWS\":\"%s\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + ARN
+ + "/endpoint/*\"}]}";
+ given().contentType("application/json")
+ .body(Map.of("Policy", named.formatted("arn:aws:iam::000000000000:role/" + reader)))
+ .when().put(policyPath)
+ .then().statusCode(400)
+ .body("message", equalTo("The principal arn provided does not match the actual principal arn."
+ + " Please check your input and try again."));
+ given().contentType("application/json")
+ .body(Map.of("Policy", named.formatted("arn:aws:iam::000000000000:role/web-it-missing")))
+ .when().put(policyPath)
+ .then().statusCode(400)
+ .body("message", equalTo("The provided principal was invalid. Please check the principal and try again."));
+ given().contentType("application/json")
+ .body(Map.of("Policy", named.formatted("arn:aws:iam::000000000000:role/team/" + reader)))
+ .when().put(policyPath)
+ .then().statusCode(200);
+ given().when().delete(policyPath)
+ .then().statusCode(204);
+ iamService.deleteRole(reader);
}
@Test
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.java
index 1c33be5062..d7dd9957d1 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
@@ -15,6 +15,9 @@ import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.IamRole;
+import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;
@@ -30,6 +33,7 @@ import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.time.Clock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -48,6 +52,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -63,6 +68,8 @@ class LambdaWebServiceTest {
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
private final ServiceCallAuthorizer serviceCalls = mock(ServiceCallAuthorizer.class);
private final LambdaMicrovmsService microvms = new LambdaMicrovmsService(new RegionResolver(REGION, ACCOUNT_ID), null);
+ private final IamService iamService = new IamService(new MemoryStorageFactory(),
+ mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), new RegionResolver(REGION, ACCOUNT_ID), Clock.systemUTC());
@TempDir
Path storageDir;
@@ -89,7 +96,7 @@ class LambdaWebServiceTest {
when(config.effectiveBaseUrl()).thenReturn(baseUrl);
LambdaWebService service = new LambdaWebService(new RegionResolver(REGION, ACCOUNT_ID), storage, config,
s3Service, new LambdaWebCode(storageDir.resolve("code")), mapper, null, executionRole, serviceCalls,
- microvms);
+ microvms, new LambdaWebPolicyPrincipals(iamService));
service.initializeStorage();
return service;
}
@@ -710,6 +717,7 @@ class LambdaWebServiceTest {
assertEquals("The provided input'foo/bar'was invalid. Member must satisfy expression: [\\w+=,.@\\:-]*"
+ " Please check your input and try again.", message(() -> service.putResourcePolicy(REGION, missing,
policy(members.formatted("{\"AWS\":\"foo/bar\"}", invoke, "\"" + resource + "\"")))));
+ iamService.createUser("alice", "/path/");
assertEquals("ResourceNotFoundException", error(() -> service.putResourcePolicy(REGION, missing,
policy(members.formatted("{\"AWS\":\"arn:aws:iam::000000000000:user/path/alice\"}", invoke,
"\"" + resource + "\"")))).getErrorCode());
@@ -753,6 +761,71 @@ class LambdaWebServiceTest {
}
}
+ @Test
+ void theRolesAndUsersAPolicyNamesHaveToExist() {
+ LambdaWebService service = service();
+ String missing = "arn:aws:lambda:us-east-1:000000000000:web-function/missing";
+ String invalid = "The provided principal was invalid. Please check the principal and try again.";
+ String otherArn = "The principal arn provided does not match the actual principal arn."
+ + " Please check your input and try again.";
+ IamRole role = iamService.createRole("reader", "/team/", "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},"
+ + "\"Action\":\"sts:AssumeRole\"}]}", null, 3600, null);
+ IamUser user = iamService.createUser("writer", "/team/");
+
+ for (String exists : List.of("arn:aws:iam::000000000000:role/team/reader",
+ "arn:aws:iam::000000000000:user/team/writer", role.getRoleId(), user.getUserId(), "111122223333",
+ "arn:aws:iam::111122223333:root", "arn:aws:sts::000000000000:federated-user/bob")) {
+ assertEquals("ResourceNotFoundException", error(() -> service.putResourcePolicy(REGION, missing,
+ policy(principalPolicy("Allow", "{\"AWS\":\"" + exists + "\"}", missing)))).getErrorCode(), exists);
+ }
+ for (String other : List.of("arn:aws:iam::000000000000:role/reader", "arn:aws:iam::000000000000:role/x/reader",
+ "arn:aws:iam::000000000000:user/writer")) {
+ assertEquals(otherArn, message(() -> service.putResourcePolicy(REGION, missing,
+ policy(principalPolicy("Allow", "{\"AWS\":\"" + other + "\"}", missing)))), other);
+ }
+ for (String absent : List.of("{\"AWS\":\"arn:aws:iam::000000000000:role/gone\"}",
+ "{\"AWS\":\"arn:aws:iam::111122223333:role/reader\"}", "{\"AWS\":\"AROAGONE\"}",
+ "{\"AWS\":\"arn:aws-cn:iam::000000000000:root\"}",
+ "{\"AWS\":\"arn:aws:sts::000000000000:assumed-role/reader/s\"}",
+ "{\"AWS\":[\"arn:aws:iam::000000000000:role/team/reader\",\"arn:aws:iam::000000000000:role/gone\"]}",
+ "{\"CanonicalUser\":\"79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be\"}")) {
+ assertEquals(invalid, message(() -> service.putResourcePolicy(REGION, missing,
+ policy(principalPolicy("Allow", absent, missing)))), absent);
+ }
+ String gone = principalPolicy("Deny", "{\"AWS\":\"arn:aws:iam::000000000000:role/gone\"}", missing);
+ assertEquals(invalid, message(() -> service.putResourcePolicy(REGION, missing, policy(gone))));
+ }
+
+ @Test
+ void everyStatementPassesItsOwnChecksBeforeAnyPrincipalIsLookedUp() {
+ LambdaWebService service = service();
+ String missing = "arn:aws:lambda:us-east-1:000000000000:web-function/missing";
+ String gone = statement("Allow", "{\"AWS\":\"arn:aws:iam::000000000000:role/gone\"}", missing);
+ String badAction = "{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"000000000000\"},"
+ + "\"Action\":\"s3:GetObject\",\"Resource\":\"" + missing + "\"}";
+ String badPattern = statement("Allow", "{\"AWS\":\"bad!value\"}", missing);
+ String open = statement("Allow", "\"*\"", missing);
+
+ assertEquals("Policy has syntax errors.", message(() -> service.putResourcePolicy(REGION, missing,
+ policy("{\"Statement\":[" + gone + "," + badAction + "]}"))));
+ assertEquals("The provided input'bad!value'was invalid. Member must satisfy expression: [\\w+=,.@\\:-]*"
+ + " Please check your input and try again.", message(() -> service.putResourcePolicy(REGION, missing,
+ policy("{\"Statement\":[" + gone + "," + badPattern + "]}"))));
+ assertEquals("The provided principal was invalid. Please check the principal and try again.",
+ message(() -> service.putResourcePolicy(REGION, missing,
+ policy("{\"Statement\":[" + open + "," + gone + "]}"))));
+ }
+
+ private static String principalPolicy(String effect, String principal, String functionArn) {
+ return "{\"Statement\":[" + statement(effect, principal, functionArn) + "]}";
+ }
+
+ private static String statement(String effect, String principal, String functionArn) {
+ return "{\"Effect\":\"" + effect + "\",\"Principal\":" + principal
+ + ",\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + functionArn + "/endpoint/*\"}";
+ }
+
private ObjectNode policy(String document) {
return mapper.createObjectNode().put("Policy", document);
}