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

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

PutResourcePolicy now looks up every AWS principal a policy names, as Lambda
does before it stores the policy. A role or user ARN has to name one IAM
holds in that account, under its own path, and a unique id one in the
function's account. A missing principal, an assumed-role session, a
CanonicalUser or an ARN in another partition gets the invalid principal
message, and a role or user named under another path gets the message
that the ARN does not match the actual one.

The principals are looked up after every statement passes its other
checks and before any statement is refused as public, which is the order
AWS checks them in.

* docs(lambdaweb): drop the principal check from the items not implemented yet

* refactor(lambdaweb): find policy principals through IamService and the resolver's partition

IamService.heldPrincipalArn now gives the ARN IAM holds what a principal
ARN names under, the root as given or the role or user at its own path.
DSQL's principal check and Lambda Web's use it, and Lambda Web keeps only
the path comparison and its messages. Lambda Web takes the partition from
RegionResolver.partitionForRegion, so a custom region falls back to the
deployment's partition.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-27 22:00:28 -04:00
1 parent 02cc40bb40
commit 701b04c410
8 files changed
+271 -20

No files matched your search

@@ -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
@@ -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
@@ -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);
}