feat(iam): list entities attached to managed policies (#1808)

This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-01 16:36:11 -05:00
1 parent a8ed218c57
commit 78ba5b3457
6 files changed
+196 -1

No files matched your search

@@ -45,6 +45,7 @@ import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;
import software.amazon.awssdk.services.iam.model.ListAttachedUserPoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListAttachedUserPoliciesResponse;
import software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyResponse;
import software.amazon.awssdk.services.iam.model.ListGroupsForUserRequest;
import software.amazon.awssdk.services.iam.model.ListGroupsForUserResponse;
import software.amazon.awssdk.services.iam.model.ListInstanceProfilesResponse;
@@ -112,6 +113,13 @@ class IamTest {
iam.detachUserPolicy(DetachUserPolicyRequest.builder()
.userName(USER_NAME).policyArn(policyArn).build());
} catch (Exception ignored) {}
try {
iam.detachGroupPolicy(request -> request
.groupName(GROUP_NAME).policyArn(policyArn));
} catch (Exception cleanupError) {
System.err.printf("Could not detach IAM test group policy during cleanup: %s%n",
cleanupError.getMessage());
}
}
try {
iam.deleteRole(DeleteRoleRequest.builder().roleName(ROLE_NAME).build());
@@ -376,6 +384,32 @@ class IamTest {
.anyMatch(p -> policyArn.equals(p.policyArn()));
}
@Test
@Order(100)
void listEntitiesForPolicy() {
Assumptions.assumeTrue(policyArn != null);
iam.attachGroupPolicy(request -> request
.groupName(GROUP_NAME).policyArn(policyArn));
ListEntitiesForPolicyResponse response = iam.listEntitiesForPolicy(request -> request
.policyArn(policyArn));
assertThat(response.policyRoles()).anySatisfy(role -> {
assertThat(role.roleName()).isEqualTo(ROLE_NAME);
assertThat(role.roleId()).isNotBlank();
});
assertThat(response.policyUsers()).anySatisfy(user -> {
assertThat(user.userName()).isEqualTo(USER_NAME);
assertThat(user.userId()).isNotBlank();
});
assertThat(response.policyGroups()).anySatisfy(group -> {
assertThat(group.groupName()).isEqualTo(GROUP_NAME);
assertThat(group.groupId()).isNotBlank();
});
assertThat(response.isTruncated()).isFalse();
}
@Test
@Order(24)
void simulatePrincipalPolicy() {
+5
View File
@@ -51,6 +51,7 @@
| GetPolicy | Returns metadata for a managed IAM policy. |
| DeletePolicy | Deletes a managed IAM policy. |
| ListPolicies | Lists managed IAM policies, including seeded AWS managed policies. |
| ListEntitiesForPolicy | Lists roles, users, and groups with a direct managed-policy attachment. |
| CreatePolicyVersion | Creates a new version of a managed policy. |
| GetPolicyVersion | Returns a managed policy version document. |
| DeletePolicyVersion | Deletes a non-default managed policy version. |
@@ -60,6 +61,10 @@
| UntagPolicy | Removes tags from a managed policy. |
| ListPolicyTags | Lists tags stored for a managed policy. |
`ListEntitiesForPolicy` currently returns direct permissions-policy attachments. `EntityFilter`,
`PathPrefix`, `PolicyUsageFilter`, and pagination are not yet applied; responses return
`IsTruncated=false`.
### Permission Boundaries
| Action | Description |
@@ -82,7 +82,7 @@ public class AwsQueryController {
"CreateGroup", "GetGroup", "DeleteGroup", "ListGroups",
"AddUserToGroup", "RemoveUserFromGroup", "ListGroupsForUser",
"CreateRole", "GetRole", "DeleteRole", "ListRoles", "UpdateRole",
"CreatePolicy", "GetPolicy", "DeletePolicy", "ListPolicies",
"CreatePolicy", "GetPolicy", "DeletePolicy", "ListPolicies", "ListEntitiesForPolicy",
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion",
"ListPolicyVersions", "SetDefaultPolicyVersion",
"AttachUserPolicy", "DetachUserPolicy", "ListAttachedUserPolicies",
@@ -92,6 +92,7 @@ public class IamQueryHandler {
case "GetPolicy" -> handleGetPolicy(params);
case "DeletePolicy" -> handleDeletePolicy(params);
case "ListPolicies" -> handleListPolicies(params);
case "ListEntitiesForPolicy" -> handleListEntitiesForPolicy(params);
case "CreatePolicyVersion" -> handleCreatePolicyVersion(params);
case "GetPolicyVersion" -> handleGetPolicyVersion(params);
case "DeletePolicyVersion" -> handleDeletePolicyVersion(params);
@@ -475,6 +476,27 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListPolicies", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleListEntitiesForPolicy(MultivaluedMap<String, String> params) {
IamService.PolicyEntities entities = iamService.listEntitiesForPolicy(getParam(params, "PolicyArn"));
var xml = new XmlBuilder().start("PolicyGroups");
for (IamGroup group : entities.groups()) {
xml.start("member").elem("GroupName", group.getGroupName())
.elem("GroupId", group.getGroupId()).end("member");
}
xml.end("PolicyGroups").start("PolicyUsers");
for (IamUser user : entities.users()) {
xml.start("member").elem("UserName", user.getUserName())
.elem("UserId", user.getUserId()).end("member");
}
xml.end("PolicyUsers").start("PolicyRoles");
for (IamRole role : entities.roles()) {
xml.start("member").elem("RoleName", role.getRoleName())
.elem("RoleId", role.getRoleId()).end("member");
}
xml.end("PolicyRoles").elem("IsTruncated", false);
return Response.ok(AwsQueryResponse.envelope("ListEntitiesForPolicy", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleCreatePolicyVersion(MultivaluedMap<String, String> params) {
String policyArn = getParam(params, "PolicyArn");
String document = getParam(params, "PolicyDocument");
@@ -497,6 +497,28 @@ public class IamService implements SessionAccountLookup {
LOG.infov("Deleted IAM policy: {0}", policyArn);
}
/** The roles, users and groups a managed policy is currently attached to. */
public record PolicyEntities(List<IamRole> roles, List<IamUser> users, List<IamGroup> groups) {}
/**
* Lists the entities (roles, users, groups) a managed policy is attached to — the read behind
* IAM's ListEntitiesForPolicy and what a caller must detach before {@link #deletePolicy} will
* succeed. Attachments are tracked on the principals, so this scans them for the given ARN.
*/
public PolicyEntities listEntitiesForPolicy(String policyArn) {
getPolicy(policyArn); // AWS raises NoSuchEntity for an unknown policy ARN; fail fast likewise.
List<IamRole> attachedRoles = roles.scan(k -> true).stream()
.filter(r -> r.getAttachedPolicyArns().contains(policyArn))
.toList();
List<IamUser> attachedUsers = users.scan(k -> true).stream()
.filter(u -> u.getAttachedPolicyArns().contains(policyArn))
.toList();
List<IamGroup> attachedGroups = groups.scan(k -> true).stream()
.filter(g -> g.getAttachedPolicyArns().contains(policyArn))
.toList();
return new PolicyEntities(attachedRoles, attachedUsers, attachedGroups);
}
public List<IamPolicy> listPolicies(String scope, String pathPrefix) {
if (scope != null && !scope.isBlank()
&& !"All".equalsIgnoreCase(scope)
@@ -0,0 +1,112 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies the IAM ListEntitiesForPolicy query action returns the roles, users and groups a managed
* policy is attached to under PolicyRoles/PolicyUsers/PolicyGroups, and an empty result for a policy
* with no attachments. IAM is the Query API (form-encoded request, XML response); Docker-free.
*/
@QuarkusTest
class IamListEntitiesForPolicyIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request";
private String iam(String action, String... kv) {
var req = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", action);
for (int i = 0; i + 1 < kv.length; i += 2) {
req = req.formParam(kv[i], kv[i + 1]);
}
return req.when().post("/").then().statusCode(200).extract().asString();
}
private String listEntities(String policyArn) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "ListEntitiesForPolicy")
.formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(200).extract().asString();
}
@Test
void listsRolesUsersAndGroupsAPolicyIsAttachedTo() {
String suffix = Long.toString(System.nanoTime(), 36);
String policyName = "lefp-policy-" + suffix;
String roleName = "lefp-role-" + suffix;
String userName = "lefp-user-" + suffix;
String groupName = "lefp-group-" + suffix;
String createPolicy = iam("CreatePolicy",
"PolicyName", policyName,
"PolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}");
String policyArn = XmlParser.extractFirst(createPolicy, "Arn", null);
assertNotNull(policyArn, "CreatePolicy should return an ARN");
iam("CreateRole", "RoleName", roleName, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
iam("CreateUser", "UserName", userName);
iam("CreateGroup", "GroupName", groupName);
// A policy with no attachments yet: all three entity lists are empty.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "ListEntitiesForPolicy")
.formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(200)
.body(allOf(not(containsString(roleName)), not(containsString(userName)), not(containsString(groupName))));
iam("AttachRolePolicy", "RoleName", roleName, "PolicyArn", policyArn);
iam("AttachUserPolicy", "UserName", userName, "PolicyArn", policyArn);
iam("AttachGroupPolicy", "GroupName", groupName, "PolicyArn", policyArn);
// Now the response exposes all three entity groups with SDK-readable names and ids.
String entities = listEntities(policyArn);
assertEquals(List.of("PolicyGroups", "PolicyUsers", "PolicyRoles", "IsTruncated"),
XmlParser.childElementNames(entities, "ListEntitiesForPolicyResult"));
List<Map<String, String>> members = XmlParser.extractGroups(entities, "member");
assertMember(members, "RoleName", roleName, "RoleId");
assertMember(members, "UserName", userName, "UserId");
assertMember(members, "GroupName", groupName, "GroupId");
}
@Test
void unknownPolicyArnReturnsNoSuchEntity() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "ListEntitiesForPolicy")
.formParam("PolicyArn", "arn:aws:iam::000000000000:policy/does-not-exist-"
+ Long.toString(System.nanoTime(), 36))
.when().post("/").then()
.statusCode(404)
.body(containsString("NoSuchEntity"));
}
private static void assertMember(List<Map<String, String>> members, String nameElement,
String expectedName, String idElement) {
assertTrue(members.stream().anyMatch(member -> expectedName.equals(member.get(nameElement))
&& member.get(idElement) != null && !member.get(idElement).isBlank()),
() -> expectedName + " should have a non-blank " + idElement + "; members were: " + members);
}
}