Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambdaweb): refuse an Allow for a federated principal as public (#6789)
TATSUNO “Taz” Yasuhiro0c549d267bd8
diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdindex 9bc2c36eb4..0726aaf692 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. 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.". 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.javaindex cc3d14635d..b17e9290d1 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@@ -1455,7 +1455,7 @@ public class LambdaWebService implements Resettable {}private static void requireNotPublic(JsonNode statement) {- if (statement.path("Effect").asText().equalsIgnoreCase("Allow") && isWildcardPrincipal(statement.get("Principal"))+ if (statement.path("Effect").asText().equalsIgnoreCase("Allow") && isPublicPrincipal(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);@@ -1484,7 +1484,12 @@ public class LambdaWebService implements Resettable {if (field.getValue().isArray() && field.getValue().isEmpty()) {throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);}- for (String value : policyValues(field.getValue())) {+ 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()) {@@ -1525,13 +1530,18 @@ public class LambdaWebService implements Resettable {return values;}- /** AWS counts a bare "*" and a "*" under AWS as public. Service and Federated wildcards are not. */- private static boolean isWildcardPrincipal(JsonNode principal) {+ /**+ * AWS counts a bare "*", a "*" under AWS and any Federated principal as public. A Service "*" is not, and+ * neither is a Federated list that holds "*".+ */+ private static boolean isPublicPrincipal(JsonNode principal) {if (principal.isTextual()) {return "*".equals(principal.textValue());}JsonNode aws = principal.get("AWS");- return aws != null && policyValues(aws).contains("*");+ JsonNode federated = principal.get("Federated");+ return (aws != null && policyValues(aws).contains("*"))+ || (federated != null && !policyValues(federated).contains("*"));}private static boolean hasTrustedCondition(JsonNode condition) {diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.javaindex fe9cf82206..0557c8640a 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@@ -520,6 +520,13 @@ class LambdaWebIntegrationTest {.then().statusCode(400).body("message", equalTo("Lambda blocked the creation of this policy because it would grant public"+ " access to your function."));+ String federatedPolicy = publicPolicy.replace("\"*\",\"Action\"",+ "{\"Federated\":\"cognito-identity.amazonaws.com\"},\"Action\"");+ given().contentType("application/json").body(Map.of("Policy", federatedPolicy))+ .when().put(policyPath)+ .then().statusCode(400)+ .body("message", equalTo("Lambda blocked the creation of this policy because it would grant public"+ + " access to your function."));String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":"+ "{\"AWS\":\"arn:aws:iam::000000000000:root\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\","diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.javaindex d7dd9957d1..e86c4d0bac 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@@ -721,9 +721,10 @@ class LambdaWebServiceTest {assertEquals("ResourceNotFoundException", error(() -> service.putResourcePolicy(REGION, missing,policy(members.formatted("{\"AWS\":\"arn:aws:iam::000000000000:user/path/alice\"}", invoke,"\"" + resource + "\"")))).getErrorCode());- assertEquals("ValidationException", error(() -> service.putResourcePolicy(REGION, missing,- policy(members.formatted("{\"CanonicalUser\":\"arn:aws:iam::000000000000:foo/bar\"}", invoke,- "\"" + resource + "\"")))).getErrorCode(), "only an AWS principal may carry a path");+ assertEquals("The provided principal was invalid. Please check the principal and try again.",+ message(() -> service.putResourcePolicy(REGION, missing,+ policy(members.formatted("{\"CanonicalUser\":\"arn:aws:iam::000000000000:foo/bar\"}", invoke,+ "\"" + resource + "\"")))), "a canonical user is never found, whatever its pattern");assertEquals("Lambda blocked the creation of this policy because it would grant public access to your function.",message(() -> service.putResourcePolicy(REGION, missing, policy("{\"Statement\":[{\"Effect\":\"Allow\","+ "\"Principal\":{\"AWS\":[\"arn:aws:iam::000000000000:root\",\"*\"]},"@@ -817,6 +818,39 @@ class LambdaWebServiceTest {policy("{\"Statement\":[" + open + "," + gone + "]}"))));}+ @Test+ void aFederatedPrincipalIsPublicUnlessAConditionPinsTheCaller() {+ LambdaWebService service = service();+ String missing = "arn:aws:lambda:us-east-1:000000000000:web-function/missing";+ String cognito = "{\"Federated\":\"cognito-identity.amazonaws.com\"}";+ for (String federated : List.of(cognito, "{\"Federated\":\"bad!value\"}", "{\"Federated\":\"\"}",+ "{\"Federated\":\"arn:aws:iam::000000000000:saml-provider/gone\"}",+ "{\"Federated\":[\"cognito-identity.amazonaws.com\",\"accounts.google.com\"]}",+ "{\"AWS\":\"000000000000\",\"Federated\":\"cognito-identity.amazonaws.com\"}")) {+ assertEquals("Lambda blocked the creation of this policy because it would grant public access to your"+ + " function.", message(() -> service.putResourcePolicy(REGION, missing,+ policy(principalPolicy("Allow", federated, missing)))), federated);+ }+ for (String accepted : List.of(principalPolicy("Deny", cognito, missing),+ principalPolicy("Deny", "{\"Federated\":\"a/b\"}", missing),+ principalPolicy("Deny", "{\"Federated\":\"arn:aws:iam::000000000000:saml-provider/gone\"}", missing),+ principalPolicy("Allow", "{\"Federated\":[\"*\",\"cognito-identity.amazonaws.com\"]}", missing),+ federatedPolicy(missing, "{\"StringEquals\":{\"aws:PrincipalAccount\":\"000000000000\"}}"),+ federatedPolicy(missing, "{\"Bool\":{\"aws:PrincipalIsAWSService\":\"true\"}}"))) {+ assertEquals("ResourceNotFoundException",+ error(() -> service.putResourcePolicy(REGION, missing, policy(accepted))).getErrorCode(), accepted);+ }+ assertEquals("Lambda blocked the creation of this policy because it would grant public access to your function.",+ message(() -> service.putResourcePolicy(REGION, missing, policy(federatedPolicy(missing,+ "{\"StringNotEquals\":{\"aws:PrincipalAccount\":\"000000000000\"}}")))));+ }++ private static String federatedPolicy(String functionArn, String condition) {+ return "{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Federated\":\"cognito-identity.amazonaws.com\"},"+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + functionArn + "/endpoint/*\","+ + "\"Condition\":" + condition + "}]}";+ }+private static String principalPolicy(String effect, String principal, String functionArn) {return "{\"Statement\":[" + statement(effect, principal, functionArn) + "]}";}