fix(lambda-web): write resource policies back in the form AWS returns (#7023)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-30 10:31:35 -04:00
1 parent ddae4fdbe9
commit 485f78656b
6 files changed
+357 -4

No files matched your search

+1 -1
View File
@@ -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`. An action is `*` or `<service>:<action>`, and each one names `lambda` in any case unless the list also holds `*`, as on AWS. AWS reads only the service and the resource of a `Resource`, so `lambda` with `web-function/<name>`, `web-function/<name>*` or `web-function/<name>/...` passes in any partition, region or account, as on AWS. 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.
- **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`. An action is `*` or `<service>:<action>`, and each one names `lambda` in any case unless the list also holds `*`, as on AWS. AWS reads only the service and the resource of a `Resource`, so `lambda` with `web-function/<name>`, `web-function/<name>*` or `web-function/<name>/...` passes in any partition, region or account, as on AWS. 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. `PutResourcePolicy` answers and keeps the policy in Lambda's own form, as on AWS. It is compact JSON with the elements in a fixed order, a missing `Version` as `2008-10-17`, a statement object as a list of one, the effect capitalized, a list of one value as the value, and condition values as text with numbers as written. An operator without keys is left out, and the operators come in the order AWS gives them. `GetResourcePolicy` also names an account id by its root ARN and drops repeated principals. AWS orders the keys of a condition, and in `GetResourcePolicy` the principals, at random on each call. Floci keeps the keys in the order they were written and the principals in the order `PutResourcePolicy` gives them. An `IamAuth` endpoint evaluates the policy on requests, as below.
- **Endpoint quota:** a function holds up to 10 endpoints, as on AWS. Another one is `402 ServiceQuotaExceededException` "The function <arn> has reached the maxEndpointsPerFunction quota of 10.", checked after the revisions it routes to, so a missing, `Failed` or connector revision is refused first, as on AWS. A deleted endpoint frees its place at once.
- **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.
@@ -22,7 +22,7 @@ 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}");
static final Pattern ACCOUNT_ID = Pattern.compile("[0-9]{12}");
private final IamService iamService;
@@ -0,0 +1,169 @@
package io.github.hectorvent.floci.services.lambdaweb;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* A resource policy as Lambda writes it back (measured, us-east-1). PutResourcePolicy answers and keeps the
* document in its own compact form: the elements in a fixed order, a missing Version as {@code 2008-10-17}, a
* statement object as a list of one, the effect capitalized, a list of one value written as the value, condition
* values as text with numbers as written, an operator without keys left out, and the operators in the order a
* {@link HashMap} filled in name order holds them. GetResourcePolicy also names an account id by its root ARN and
* drops repeated principals. AWS orders the keys of a condition, and in GetResourcePolicy the principals, at random
* on every call, so the keys stay as written and the principals as PutResourcePolicy writes them.
*/
final class LambdaWebPolicyText {
private static final String DEFAULT_VERSION = "2008-10-17";
private static final List<String> STATEMENT_KEYS = List.of(
"Sid", "Effect", "Principal", "NotPrincipal", "Action", "NotAction", "Resource", "NotResource", "Condition");
private static final List<String> PRINCIPAL_TYPES = List.of("AWS", "CanonicalUser", "Federated", "Service");
private LambdaWebPolicyText() {
}
/** The policy as PutResourcePolicy answers and keeps it. {@code policy} has passed the policy checks. */
static String kept(ObjectMapper mapper, String policy) {
JsonNode document = parse(mapper.reader()
.with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
.without(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES), policy);
ObjectNode kept = mapper.createObjectNode();
kept.set("Version", document.has("Version") ? document.get("Version") : TextNode.valueOf(DEFAULT_VERSION));
if (document.has("Id")) {
kept.set("Id", document.get("Id"));
}
JsonNode statements = document.get("Statement");
ArrayNode keptStatements = kept.putArray("Statement");
for (JsonNode statement : statements.isArray() ? statements : List.of(statements)) {
keptStatements.add(statement(mapper, statement));
}
return write(mapper, kept);
}
/** The kept policy as GetResourcePolicy answers it. */
static String read(ObjectMapper mapper, String kept, String partition) {
JsonNode document = parse(mapper.reader(), kept);
for (JsonNode statement : document.path("Statement")) {
for (String member : List.of("Principal", "NotPrincipal")) {
if (!(statement.get(member) instanceof ObjectNode principal)) {
continue;
}
Iterator<Map.Entry<String, JsonNode>> types = principal.fields();
while (types.hasNext()) {
Map.Entry<String, JsonNode> type = types.next();
LinkedHashSet<String> distinct = new LinkedHashSet<>();
for (String value : texts(type.getValue())) {
boolean account = "AWS".equals(type.getKey())
&& LambdaWebPolicyPrincipals.ACCOUNT_ID.matcher(value).matches();
distinct.add(account ? AwsArnUtils.Arn.global(partition, "iam", value, "root").toString() : value);
}
type.setValue(written(mapper, List.copyOf(distinct)));
}
}
}
return write(mapper, document);
}
private static ObjectNode statement(ObjectMapper mapper, JsonNode statement) {
ObjectNode kept = mapper.createObjectNode();
for (String key : STATEMENT_KEYS) {
JsonNode value = statement.get(key);
if (value == null) {
continue;
}
kept.set(key, switch (key) {
case "Effect" -> TextNode.valueOf(value.textValue().equalsIgnoreCase("Allow") ? "Allow" : "Deny");
case "Principal", "NotPrincipal" -> principal(mapper, value);
case "Condition" -> condition(mapper, value);
default -> values(mapper, value);
});
}
return kept;
}
private static JsonNode principal(ObjectMapper mapper, JsonNode principal) {
if (!principal.isObject()) {
return principal;
}
ObjectNode kept = mapper.createObjectNode();
for (String type : PRINCIPAL_TYPES) {
if (principal.has(type)) {
kept.set(type, values(mapper, principal.get(type)));
}
}
return kept;
}
private static JsonNode condition(ObjectMapper mapper, JsonNode condition) {
if (!condition.isObject()) {
return condition;
}
Map<String, JsonNode> byName = new TreeMap<>();
condition.fields().forEachRemaining(operator -> byName.put(operator.getKey(), operator.getValue()));
Map<String, ObjectNode> operators = new HashMap<>();
byName.forEach((operator, keyValues) -> {
if (keyValues.isObject() && !keyValues.isEmpty()) {
ObjectNode keys = mapper.createObjectNode();
keyValues.fields().forEachRemaining(key -> keys.set(key.getKey(), values(mapper, key.getValue())));
operators.put(operator, keys);
}
});
ObjectNode kept = mapper.createObjectNode();
operators.forEach(kept::set);
return kept;
}
/** A value or a list of values, kept as text, the list of one written as its value. */
private static JsonNode values(ObjectMapper mapper, JsonNode node) {
return node.isNull() ? node : written(mapper, texts(node));
}
private static JsonNode written(ObjectMapper mapper, List<String> values) {
if (values.size() == 1) {
return TextNode.valueOf(values.getFirst());
}
ArrayNode list = mapper.createArrayNode();
values.forEach(list::add);
return list;
}
private static List<String> texts(JsonNode node) {
List<String> values = new ArrayList<>();
for (JsonNode item : node.isArray() ? node : List.of(node)) {
values.add(item.asText());
}
return values;
}
private static JsonNode parse(ObjectReader reader, String policy) {
try {
return reader.readTree(policy);
} catch (JsonProcessingException e) {
throw new IllegalStateException("A checked policy is JSON", e);
}
}
private static String write(ObjectMapper mapper, JsonNode document) {
try {
return mapper.writeValueAsString(document);
} catch (JsonProcessingException e) {
throw new IllegalStateException("A kept policy is written as JSON", e);
}
}
}
@@ -1344,7 +1344,7 @@ public class LambdaWebService implements Resettable {
throw new AwsException("ConflictException", "The policy was updated or deleted by another request."
+ " Try again with the latest policy revisionId.", 409);
}
fn.policy = policy;
fn.policy = LambdaWebPolicyText.kept(objectMapper, policy);
fn.policyRevisionId = UUID.randomUUID().toString();
fn.updatedAt = now();
persist(region, fn);
@@ -1358,7 +1358,8 @@ public class LambdaWebService implements Resettable {
if (fn.policy == null) {
throw noPolicy();
}
return new ResourcePolicy(fn.policy, fn.policyRevisionId);
String partition = regionResolver.partitionForRegion(region);
return new ResourcePolicy(LambdaWebPolicyText.read(objectMapper, fn.policy, partition), fn.policyRevisionId);
}
public void deleteResourcePolicy(String region, String resourceArn, String revisionId) {
@@ -569,6 +569,22 @@ class LambdaWebIntegrationTest {
.then().statusCode(404)
.body("message", equalTo("The function does not have a policy."));
// Lambda writes the policy back in its own form, and GetResourcePolicy names an account by its root.
String written = "{\"Statement\":{\"Resource\":[\"" + ARN + "/endpoint/*\"],\"Principal\":{\"AWS\":"
+ "\"000000000000\"},\"Effect\":\"allow\",\"Action\":\"lambda:InvokeWebFunctionEndpoint\"}}";
String kept = "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":"
+ "\"000000000000\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + ARN
+ "/endpoint/*\"}]}";
given().contentType("application/json").body(Map.of("Policy", written))
.when().put(policyPath)
.then().statusCode(200)
.body("Policy", equalTo(kept));
given().when().get(policyPath)
.then().statusCode(200)
.body("Policy", equalTo(kept.replace("\"000000000000\"", "\"arn:aws:iam::000000000000:root\"")));
given().when().delete(policyPath)
.then().statusCode(204);
// 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\","
@@ -0,0 +1,167 @@
package io.github.hectorvent.floci.services.lambdaweb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
class LambdaWebPolicyTextTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ROOT = "arn:aws:iam::111122223333:root";
private static final String ENDPOINTS = "arn:aws:lambda:us-east-1:111122223333:web-function/app/endpoint/*";
private static final String GRANT = "'Principal':{'AWS':'" + ROOT + "'},'Action':'lambda:InvokeWebFunctionEndpoint',"
+ "'Resource':'" + ENDPOINTS + "'";
@Test
void aPolicyIsWrittenCompactWithItsElementsInAFixedOrder() throws Exception {
String expected = json("{'Version':'2012-10-17','Statement':[{'Effect':'Allow'," + GRANT + "}]}");
assertEquals(expected, kept(json("{'Statement':[{'Action':'lambda:InvokeWebFunctionEndpoint','Effect':'Allow',"
+ "'Principal':{'AWS':'" + ROOT + "'},'Resource':'" + ENDPOINTS + "'}],'Version':'2012-10-17'}")));
assertEquals(expected, kept(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(MAPPER.readTree(expected))));
assertEquals(json("{'Version':'2012-10-17','Id':'i','Statement':[{'Sid':'s1','Effect':'Allow'," + GRANT
+ ",'Condition':{'StringEquals':{'aws:SourceAccount':'111122223333'}}}]}"),
kept(json("{'Statement':[{'Condition':{'StringEquals':{'aws:SourceAccount':'111122223333'}},'Resource':'"
+ ENDPOINTS + "','Action':'lambda:InvokeWebFunctionEndpoint','Principal':{'AWS':'" + ROOT + "'},"
+ "'Effect':'Allow','Sid':'s1'}],'Id':'i','Version':'2012-10-17'}")));
}
@Test
void aMissingVersionIsTheOlderOneAndAStatementObjectIsAListOfOne() {
assertEquals(json("{'Version':'2008-10-17','Statement':[{'Effect':'Deny'," + GRANT + "}]}"),
kept(json("{'Statement':{'Effect':'deny'," + GRANT + "}}")));
}
@Test
void aListOfOneIsWrittenAsItsValueAndLongerListsKeepTheirRepeats() {
assertEquals(json("{'Version':'2012-10-17','Statement':[{'Effect':'Allow'," + GRANT
+ ",'Condition':{'StringEquals':{'aws:UserAgent':'x'}}}]}"),
kept(json("{'Version':'2012-10-17','Statement':[{'Effect':'Allow','Principal':{'AWS':['" + ROOT + "']},"
+ "'Action':['lambda:InvokeWebFunctionEndpoint'],'Resource':['" + ENDPOINTS + "'],"
+ "'Condition':{'StringEquals':{'aws:UserAgent':['x']}}}]}")));
String repeated = json("{'Version':'2012-10-17','Statement':[{'Effect':'Allow',"
+ "'Principal':{'AWS':['111122223333','" + ROOT + "','" + ROOT + "']},"
+ "'Action':['lambda:InvokeWebFunctionEndpoint','lambda:InvokeWebFunctionEndpoint'],"
+ "'Resource':['" + ENDPOINTS + "','" + ENDPOINTS + "'],'Condition':{'StringEquals':{'aws:UserAgent':['b','a','b']}}}]}");
assertEquals(repeated, kept(repeated));
}
@Test
void conditionValuesAreTextWithNumbersAsWritten() {
assertEquals(json("{'Version':'2012-10-17','Statement':[{'Effect':'Deny'," + GRANT + ",'Condition':"
+ "{'NumericLessThan':{'aws:MultiFactorAuthAge':['1.50','1E+3','-2','12345678901234567890']}}},"
+ "{'Effect':'Deny'," + GRANT + ",'Condition':{'Bool':{'aws:SecureTransport':'false'}}}]}"),
kept(json("{'Version':'2012-10-17','Statement':[{'Effect':'Deny'," + GRANT + ",'Condition':"
+ "{'NumericLessThan':{'aws:MultiFactorAuthAge':[1.50,1e3,-2,12345678901234567890]}}},"
+ "{'Effect':'Deny'," + GRANT + ",'Condition':{'Bool':{'aws:SecureTransport':false}}}]}")));
}
@Test
void operatorsComeInTheOrderAwsGivesThemWhateverOrderTheyAreWrittenIn() {
Map<List<String>, List<String>> written = Map.of(
List.of("StringEquals", "StringNotEquals", "StringEqualsIgnoreCase", "StringNotEqualsIgnoreCase",
"StringLike", "StringNotLike", "NumericEquals", "NumericNotEquals", "NumericLessThan",
"NumericLessThanEquals", "NumericGreaterThan", "NumericGreaterThanEquals", "DateEquals",
"DateNotEquals", "DateLessThan", "DateLessThanEquals", "DateGreaterThan", "DateGreaterThanEquals",
"Bool", "IpAddress", "NotIpAddress", "ArnEquals", "ArnNotEquals", "ArnLike", "ArnNotLike", "Null"),
List.of("StringEquals", "Null", "ArnNotEquals", "NumericGreaterThan", "NumericLessThan",
"DateLessThanEquals", "NumericEquals", "DateLessThan", "StringNotLike", "Bool",
"StringEqualsIgnoreCase", "DateEquals", "DateGreaterThan", "ArnLike", "ArnEquals",
"NumericNotEquals", "NumericLessThanEquals", "StringLike", "StringNotEquals",
"StringNotEqualsIgnoreCase", "DateGreaterThanEquals", "DateNotEquals", "NotIpAddress",
"ArnNotLike", "IpAddress", "NumericGreaterThanEquals"),
List.of("ArnLike", "BoolIfExists", "ForAllValues:ArnLike", "StringEqualsIfExists", "Bool",
"ForAnyValue:StringEqualsIfExists", "StringLike", "ForAnyValue:StringEquals", "Null",
"ForAllValues:StringEquals", "StringEquals"),
List.of("StringEquals", "Null", "StringLike", "ForAllValues:StringEquals", "Bool",
"ForAnyValue:StringEquals", "ForAllValues:ArnLike", "ForAnyValue:StringEqualsIfExists",
"StringEqualsIfExists", "BoolIfExists", "ArnLike"));
written.forEach((operators, expected) -> {
ObjectNode condition = MAPPER.createObjectNode();
operators.forEach(operator -> condition.putObject(operator).put("aws:UserAgent", "x"));
String policy = json("{'Version':'2012-10-17','Statement':[{'Effect':'Deny'," + GRANT + ",'Condition':")
+ condition + "}]}";
assertEquals(expected, fieldNames(statement(kept(policy)).get("Condition")));
assertEquals(expected, fieldNames(statement(read(kept(policy), "aws")).get("Condition")));
});
}
@Test
void anOperatorWithoutKeysIsLeftOutButAnEmptyConditionStays() {
String expected = json("{'Version':'2012-10-17','Statement':[{'Effect':'Deny'," + GRANT + ",'Condition':{}}]}");
assertEquals(expected, kept(json("{'Version':'2012-10-17','Statement':[{'Effect':'Deny'," + GRANT
+ ",'Condition':{'StringEquals':{}}}]}")));
assertEquals(expected, kept(expected));
}
@Test
void principalTypesComeInAFixedOrderAndTheirValuesAsWritten() {
assertEquals(json("{'Version':'2012-10-17','Statement':[{'Effect':'Deny','Principal':{'AWS':'" + ROOT + "',"
+ "'Federated':'cognito-identity.amazonaws.com','Service':['s3.amazonaws.com',"
+ "'cloudfront.amazonaws.com','s3.amazonaws.com']},'Action':'lambda:InvokeWebFunctionEndpoint',"
+ "'Resource':'" + ENDPOINTS + "'}]}"),
kept(json("{'Version':'2012-10-17','Statement':[{'Effect':'Deny','Principal':{'Service':['s3.amazonaws.com',"
+ "'cloudfront.amazonaws.com','s3.amazonaws.com'],'Federated':'cognito-identity.amazonaws.com',"
+ "'AWS':'" + ROOT + "'},'Action':'lambda:InvokeWebFunctionEndpoint','Resource':'" + ENDPOINTS + "'}]}")));
}
@Test
void textIsWrittenWithTheEscapesJsonNeedsOnly() {
assertEquals("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"" + ROOT
+ "\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + ENDPOINTS + "\","
+ "\"Condition\":{\"StringEquals\":{\"aws:UserAgent\":\"a<b>&'\\\"\\t\\u0001
é😀 /xA\"}}}]}",
kept("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"" + ROOT
+ "\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\""
+ ENDPOINTS.replace("/", "\\/") + "\",\"Condition\":{\"StringEquals\":{\"aws:UserAgent\":"
+ "\"a<b>&'\\\"\\t\\u0001\\u2028\\u00e9\\ud83d\\ude00 \\/x\\u0041\"}}}]}"));
}
@Test
void getResourcePolicyNamesAnAccountByItsRootAndDropsRepeatedPrincipals() {
String kept = kept(json("{'Version':'2012-10-17','Statement':[{'Effect':'Allow','Principal':{'AWS':"
+ "'111122223333'},'Action':'lambda:InvokeWebFunctionEndpoint','Resource':'" + ENDPOINTS + "'},"
+ "{'Effect':'Deny','Principal':{'AWS':['111122223333','" + ROOT + "','arn:aws:iam::111122223333:role/r'],"
+ "'Service':['s3.amazonaws.com','cloudfront.amazonaws.com','s3.amazonaws.com']},"
+ "'Action':'lambda:InvokeWebFunctionEndpoint','Resource':'" + ENDPOINTS + "'}]}"));
assertEquals(json("{'Version':'2012-10-17','Statement':[{'Effect':'Allow','Principal':{'AWS':'" + ROOT + "'},"
+ "'Action':'lambda:InvokeWebFunctionEndpoint','Resource':'" + ENDPOINTS + "'},"
+ "{'Effect':'Deny','Principal':{'AWS':['" + ROOT + "','arn:aws:iam::111122223333:role/r'],"
+ "'Service':['s3.amazonaws.com','cloudfront.amazonaws.com']},"
+ "'Action':'lambda:InvokeWebFunctionEndpoint','Resource':'" + ENDPOINTS + "'}]}"),
read(kept, "aws"));
assertEquals("arn:aws-us-gov:iam::111122223333:root",
statement(read(kept, "aws-us-gov")).path("Principal").path("AWS").textValue());
}
private static String kept(String policy) {
return LambdaWebPolicyText.kept(MAPPER, policy);
}
private static String read(String kept, String partition) {
return LambdaWebPolicyText.read(MAPPER, kept, partition);
}
private static JsonNode statement(String policy) {
try {
return MAPPER.readTree(policy).path("Statement").get(0);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
private static String json(String singleQuoted) {
return singleQuoted.replace('\'', '"');
}
}