Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(lambdaweb): check resource policy statements in the order AWS does (#6788)

TATSUNO “Taz” Yasuhiroc55cb887d504
diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.md
index 0726aaf692..74b97a2c8c 100644
--- a/docs/services/lambda-web-functions.md
+++ b/docs/services/lambda-web-functions.md
@@ -41,7 +41,7 @@ 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 `Allow` for a `Federated` principal is public in the same way, unless its values include `*`, as on AWS. AWS checks no pattern on `Federated` and `CanonicalUser` values. 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.
+- **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 `Allow` for a `Federated` principal is public in the same way, unless its values include `*`, as on AWS. AWS checks no pattern on `Federated` and `CanonicalUser` values. 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.". Each check runs on every statement before the next check starts, in the order AWS reports them, so an `Effect` other than `Allow` or `Deny` ("Invalid effect: <value>") in any statement comes before a principal error in another. 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.
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 b17e9290d1..b98f012030 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
@@ -1385,9 +1385,9 @@ public class LambdaWebService implements Resettable {
}
/**
- * 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.
+ * The checks AWS runs on a policy document before it looks the function up. Each check runs on every statement
+ * before the next check starts, in the order AWS reports them. A statement that is not an object fails only
+ * once every principal exists.
*/
private void validatePolicy(String region, String policy, String functionArn) {
JsonNode document;
@@ -1409,39 +1409,116 @@ public class LambdaWebService implements Resettable {
if (each.isEmpty()) {
throw policySyntax();
}
- 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);
+ List<JsonNode> objects = each.stream().filter(JsonNode::isObject).toList();
+ String partition = regionResolver.partitionForRegion(region);
+ List<Consumer<JsonNode>> checks = List.of(
+ LambdaWebService::requireReadable,
+ LambdaWebService::validateStatement,
+ LambdaWebService::requireEffect,
+ LambdaWebService::validatePrincipalValues,
+ LambdaWebService::requirePrincipal,
+ statement -> validateGrant(statement, functionArn),
+ statement -> policyPrincipals.requireExisting(partition, statement.get("Principal")));
+ for (Consumer<JsonNode> check : checks) {
+ objects.forEach(check);
+ }
+ if (objects.size() < each.size()) {
+ throw policySyntax();
}
+ objects.forEach(LambdaWebService::requireNotPublic);
}
- private static void validateStatement(JsonNode statement, String functionArn) {
- if (!statement.isObject()) {
+ /** A null Effect or Principal, or an Effect with whitespace, fails before any other statement is checked. */
+ private static void requireReadable(JsonNode statement) {
+ JsonNode effect = statement.path("Effect");
+ boolean spaced = effect.isTextual() && effect.textValue().chars().anyMatch(Character::isWhitespace);
+ if (spaced || effect.isNull() || statement.path("Principal").isNull()) {
throw policySyntax();
}
- if (!statement.has("Effect")) {
- throw new AwsException("ValidationException", "Effect must be explicitly available for a statement", 400);
+ }
+
+ /** The principal's shape, then the effect, then the statement's keys, whatever order its members come in. */
+ private static void validateStatement(JsonNode statement) {
+ JsonNode principal = statement.path("Principal");
+ if (!principal.isMissingNode() && !principal.isObject() && !"*".equals(principal.textValue())) {
+ throw syntaxPosition();
+ }
+ Iterator<String> principalKeys = principal.fieldNames();
+ while (principalKeys.hasNext()) {
+ if (!PRINCIPAL_KEYS.contains(principalKeys.next())) {
+ throw syntaxPosition();
+ }
+ }
+ JsonNode effect = statement.path("Effect");
+ if (!effect.isMissingNode() && !effect.isTextual()) {
+ throw syntaxPosition();
+ }
+ if (effect.isTextual() && !effect.textValue().equalsIgnoreCase("Allow")
+ && !effect.textValue().equalsIgnoreCase("Deny")) {
+ throw new AwsException("ValidationException", "Invalid effect: " + effect.textValue(), 400);
}
Iterator<String> keys = statement.fieldNames();
while (keys.hasNext()) {
if (!STATEMENT_KEYS.contains(keys.next())) {
- throw new AwsException("ValidationException", "Syntax error at position (-1,-1)", 400);
+ throw syntaxPosition();
}
}
- String effect = statement.path("Effect").asText();
- if (!effect.equalsIgnoreCase("Allow") && !effect.equalsIgnoreCase("Deny")) {
- throw policySyntax();
+ }
+
+ private static void requireEffect(JsonNode statement) {
+ if (!statement.has("Effect")) {
+ throw new AwsException("ValidationException", "Effect must be explicitly available for a statement", 400);
+ }
+ }
+
+ /** Only an AWS ARN may carry a slash. An empty list is left to {@link #requirePrincipal}. */
+ private static void validatePrincipalValues(JsonNode statement) {
+ for (String member : List.of("Principal", "NotPrincipal")) {
+ Iterator<Map.Entry<String, JsonNode>> fields = statement.path(member).fields();
+ while (fields.hasNext()) {
+ Map.Entry<String, JsonNode> field = fields.next();
+ if (field.getValue().isArray() && field.getValue().isEmpty()) {
+ continue;
+ }
+ List<String> values = policyValues(field.getValue());
+ // AWS checks no pattern on these, so a slash or a "!" passes.
+ if ("Federated".equals(field.getKey()) || "CanonicalUser".equals(field.getKey())) {
+ continue;
+ }
+ for (String value : values) {
+ Pattern allowed = "Service".equals(field.getKey()) ? PRINCIPAL_SERVICE
+ : "AWS".equals(field.getKey()) && AwsArnUtils.isArn(value) ? PRINCIPAL_AWS_ARN : PRINCIPAL_AWS;
+ if (!"*".equals(value) && !allowed.matcher(value).matches()) {
+ throw new AwsException("ValidationException", "The provided input'" + value
+ + "'was invalid. Member must satisfy expression: " + allowed.pattern()
+ + " Please check your input and try again.", 400);
+ }
+ if ("Service".equals(field.getKey()) && "*".equals(value)) {
+ throw new AwsException("ValidationException", "The provided input'*'was invalid."
+ + " Member must satisfy expression: " + PRINCIPAL_SERVICE.pattern()
+ + " Please check your input and try again.", 400);
+ }
+ }
+ }
+ }
+ }
+
+ private static void requirePrincipal(JsonNode statement) {
+ JsonNode principal = statement.path("Principal");
+ if ((principal.isMissingNode() && !statement.has("NotPrincipal")) || (principal.isObject() && principal.isEmpty())) {
+ throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);
}
+ for (JsonNode value : principal) {
+ if (value.isArray() && value.isEmpty()) {
+ throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);
+ }
+ }
+ }
+
+ private static void validateGrant(JsonNode statement, String functionArn) {
if (statement.has("NotPrincipal") || statement.has("NotAction") || statement.has("NotResource")) {
throw policySyntax();
}
- JsonNode principal = statement.get("Principal");
- validatePrincipal(principal);
for (String action : policyValues(statement.get("Action"))) {
if (!action.startsWith("lambda:")) {
throw policySyntax();
@@ -1462,50 +1539,6 @@ public class LambdaWebService implements Resettable {
}
}
- private static void validatePrincipal(JsonNode principal) {
- if (principal == null || principal.isNull() || (principal.isObject() && principal.isEmpty())) {
- throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);
- }
- if (principal.isTextual()) {
- if (!"*".equals(principal.textValue())) {
- throw policySyntax();
- }
- return;
- }
- if (!principal.isObject()) {
- throw policySyntax();
- }
- Iterator<Map.Entry<String, JsonNode>> fields = principal.fields();
- while (fields.hasNext()) {
- Map.Entry<String, JsonNode> field = fields.next();
- if (!PRINCIPAL_KEYS.contains(field.getKey())) {
- throw policySyntax();
- }
- if (field.getValue().isArray() && field.getValue().isEmpty()) {
- throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);
- }
- List<String> values = policyValues(field.getValue());
- // AWS checks no pattern on these, so a slash or a "!" passes.
- if ("Federated".equals(field.getKey()) || "CanonicalUser".equals(field.getKey())) {
- continue;
- }
- for (String value : values) {
- Pattern allowed = "Service".equals(field.getKey()) ? PRINCIPAL_SERVICE
- : "AWS".equals(field.getKey()) && AwsArnUtils.isArn(value) ? PRINCIPAL_AWS_ARN : PRINCIPAL_AWS;
- if (!"*".equals(value) && !allowed.matcher(value).matches()) {
- throw new AwsException("ValidationException", "The provided input'" + value
- + "'was invalid. Member must satisfy expression: " + allowed.pattern()
- + " Please check your input and try again.", 400);
- }
- if ("Service".equals(field.getKey()) && "*".equals(value)) {
- throw new AwsException("ValidationException", "The provided input'*'was invalid."
- + " Member must satisfy expression: " + PRINCIPAL_SERVICE.pattern()
- + " Please check your input and try again.", 400);
- }
- }
- }
- }
-
/** A string or a list of strings. Anything else is a syntax error, and so is an absent member. */
private static List<String> policyValues(JsonNode node) {
if (node == null || node.isNull()) {
@@ -1588,6 +1621,10 @@ public class LambdaWebService implements Resettable {
return new AwsException("ValidationException", POLICY_SYNTAX, 400);
}
+ private static AwsException syntaxPosition() {
+ return new AwsException("ValidationException", "Syntax error at position (-1,-1)", 400);
+ }
+
// ---------------------------------------------------------------- identifiers
private WebFunction function(String region, String functionName) {
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 0557c8640a..0b44a433b0 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
@@ -527,8 +527,12 @@ class LambdaWebIntegrationTest {
.then().statusCode(400)
.body("message", equalTo("Lambda blocked the creation of this policy because it would grant public"
+ " access to your function."));
+ given().contentType("application/json").body(Map.of("Policy", publicPolicy.replace("\"Allow\"", "\"Maybe\"")))
+ .when().put(policyPath)
+ .then().statusCode(400)
+ .body("message", equalTo("Invalid effect: Maybe"));
- String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":"
+ String policy ="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":"
+ "{\"AWS\":\"arn:aws:iam::000000000000:root\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\","
+ "\"Resource\":\"" + ARN + "/endpoint/*\"}]}";
String revisionId = given().contentType("application/json").body(Map.of("Policy", policy))
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 e86c4d0bac..df083c3bb1 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
@@ -851,6 +851,70 @@ class LambdaWebServiceTest {
+ "\"Condition\":" + condition + "}]}";
}
+ @Test
+ void eachStatementCheckRunsOnEveryStatementBeforeTheNextOne() {
+ LambdaWebService service = service();
+ String missing = "arn:aws:lambda:us-east-1:000000000000:web-function/missing";
+ String account = "{\"AWS\":\"000000000000\"}";
+ String grant = "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + missing + "/endpoint/*\"";
+ String maybe = "{\"Effect\":\"Maybe\",\"Principal\":" + account + "," + grant + "}";
+ String spaced = "{\"Effect\":\" Allow\",\"Principal\":" + account + "," + grant + "}";
+ String unknownKey = "{\"Effect\":\"Allow\",\"Principal\":" + account + "," + grant + ",\"Foo\":1}";
+ String noEffect = "{\"Principal\":" + account + "," + grant + "}";
+ String notPrincipal = "{\"Effect\":\"Allow\",\"Principal\":" + account + ",\"NotPrincipal\":" + account + ","
+ + grant + "}";
+ String badAction = "{\"Effect\":\"Allow\",\"Principal\":" + account + ",\"Action\":\"s3:GetObject\","
+ + "\"Resource\":\"" + missing + "\"}";
+ String textPrincipal = statement("Allow", "\"foo\"", missing);
+ String nullPrincipal = statement("Allow", "null", missing);
+ String badPattern = statement("Allow", "{\"AWS\":\"bad!value\"}", missing);
+ String emptyPrincipal = statement("Allow", "{\"AWS\":[]}", missing);
+ String gone = statement("Allow", "{\"AWS\":\"arn:aws:iam::000000000000:role/gone\"}", missing);
+ String open = statement("Allow", "\"*\"", missing);
+ String syntax = "Policy has syntax errors.";
+ String position = "Syntax error at position (-1,-1)";
+ String noEffectMessage = "Effect must be explicitly available for a statement";
+ String invalid = "The provided principal was invalid. Please check the principal and try again.";
+ String pattern = "The provided input'bad!value'was invalid. Member must satisfy expression: [\\w+=,.@\\:-]*"
+ + " Please check your input and try again.";
+
+ for (List<String> pair : List.of(
+ List.of(maybe, spaced, syntax),
+ List.of(badPattern, nullPrincipal, syntax),
+ List.of(badPattern, maybe, "Invalid effect: Maybe"),
+ List.of(textPrincipal, badPattern, position),
+ List.of(noEffect, unknownKey, position),
+ List.of(noEffect, badPattern, noEffectMessage),
+ List.of(noEffect, badAction, noEffectMessage),
+ List.of(badAction, badPattern, pattern),
+ List.of(emptyPrincipal, badPattern, pattern),
+ List.of(emptyPrincipal, badAction, invalid),
+ List.of(notPrincipal, emptyPrincipal, invalid),
+ List.of("\"x\"", open, syntax))) {
+ for (String statements : List.of(pair.get(0) + "," + pair.get(1), pair.get(1) + "," + pair.get(0))) {
+ assertEquals(pair.get(2), message(() -> service.putResourcePolicy(REGION, missing,
+ policy("{\"Statement\":[" + statements + "]}"))), statements);
+ }
+ }
+ for (List<String> ordered : List.of(
+ List.of("[" + unknownKey + "," + maybe + "]", position),
+ List.of("[" + maybe + "," + unknownKey + "]", "Invalid effect: Maybe"),
+ List.of("[" + textPrincipal + "," + maybe + "]", position),
+ List.of("[" + maybe + "," + textPrincipal + "]", "Invalid effect: Maybe"),
+ List.of("[{\"Foo\":1,\"Effect\":\"Maybe\",\"Principal\":" + account + "," + grant + "}]",
+ "Invalid effect: Maybe"),
+ List.of("[\"x\"," + gone + "]", invalid),
+ List.of("[\"x\"," + badPattern + "]", pattern),
+ List.of("[" + statement("", account, missing) + "]", "Invalid effect: "),
+ List.of("[" + statement("Allow", "1", missing) + "]", position),
+ List.of("[" + statement("Allow", "{\"Foo\":\"x\"}", missing) + "]", position),
+ List.of("[{\"Effect\":1,\"Principal\":" + account + "," + grant + "}]", position),
+ List.of("[{\"Effect\":\"Allow\",\"NotPrincipal\":{\"AWS\":\"bad!value\"}," + grant + "}]", pattern))) {
+ assertEquals(ordered.get(1), message(() -> service.putResourcePolicy(REGION, missing,
+ policy("{\"Statement\":" + ordered.get(0) + "}"))), ordered.get(0));
+ }
+ }
+
private static String principalPolicy(String effect, String principal, String functionArn) {
return "{\"Statement\":[" + statement(effect, principal, functionArn) + "]}";
}