diff --git a/docs/services/iam.md b/docs/services/iam.md index 75b7ecc48d..6a2530e711 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -131,7 +131,7 @@ type. | Action | Description | |--------|-------------| -| CreateInstanceProfile | Creates an IAM instance profile. | +| CreateInstanceProfile | Creates an IAM instance profile, applying any `Tags` given at creation. | | GetInstanceProfile | Returns an instance profile and its roles. | | DeleteInstanceProfile | Deletes an instance profile from the local IAM store. | | ListInstanceProfiles | Lists IAM instance profiles. | @@ -142,6 +142,13 @@ type. | UntagInstanceProfile | Removes tags from an instance profile. | | ListInstanceProfileTags | Lists tags stored for an instance profile. | +`CreateInstanceProfile`, `GetInstanceProfile` and `ListInstanceProfilesForRole` include an instance +profile's own tags inline. `ListInstanceProfiles` omits them: like `ListRoles`, its own operation +documentation says "this operation does not return tags, even though they are an attribute of the +returned object", even though the `InstanceProfile` shape itself carries no such exclusion note. +Tags on a role embedded in `InstanceProfileList` are always omitted, matching `GetInstanceProfile`'s +own documented role subset. + ### Access Keys | Action | Description | @@ -319,6 +326,16 @@ read; the comparison is driven entirely by the policy's own condition operator ( | Action | Description | |--------|-------------| | GetAccountSummary | Returns entity counts (users, groups, roles, customer-managed policies, instance profiles) and IAM quota values. `Providers` counts OIDC providers only; SAML providers are not included. Resources Floci does not track (MFA devices, server certificates) are reported as zero rather than omitted. | +| GetAccountAuthorizationDetails | Returns every user, group and role in the account, and the policies relevant to them: every local (customer-managed) policy, and every AWS-managed policy actually attached to or used as a permissions boundary by something in the account. | + +`Filter`, `MaxItems` and `Marker` are not honored: the response always includes everything, with +`IsTruncated` always `false`. `AttachmentCount` and `PermissionsBoundaryUsageCount` are computed by +scanning the account's own users, groups and roles rather than read off a stored counter, so they +are correctly scoped to the calling account even for an AWS-managed policy (see the note on +`IamService.getAccountAuthorizationDetails` for why that distinction matters). Policy documents are +returned as plain JSON, not URL-encoded as AWS documents them; this matches every other IAM action +that returns a policy document (`GetPolicyVersion`, `GetRolePolicy`, and so on), none of which +URL-encode either. ### Organizations Root Access diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index 6fe2768fcd..1e65d8f1b1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -133,6 +133,7 @@ public class IamQueryHandler { case "ListPolicies" -> handleListPolicies(params); case "ListEntitiesForPolicy" -> handleListEntitiesForPolicy(params); case "GetAccountSummary" -> handleGetAccountSummary(params); + case "GetAccountAuthorizationDetails" -> handleGetAccountAuthorizationDetails(params); case "CreatePolicyVersion" -> handleCreatePolicyVersion(params); case "GetPolicyVersion" -> handleGetPolicyVersion(params); case "DeletePolicyVersion" -> handleDeletePolicyVersion(params); @@ -854,6 +855,137 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelope("GetAccountSummary", AwsNamespaces.IAM, xml.build())).build(); } + // Filter, MaxItems and Marker are not honored: every user, group, role and relevant policy + // is always returned in one response, matching this handler's general convention elsewhere + // (ListInstanceProfiles, SimulatePrincipalPolicy, ...) of not implementing pagination. + private Response handleGetAccountAuthorizationDetails(MultivaluedMap params) { + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + XmlBuilder xml = new XmlBuilder().start("UserDetailList"); + for (IamUser user : details.users()) { + xml.start("member").raw(userDetailXml(user)).end("member"); + } + xml.end("UserDetailList").start("GroupDetailList"); + for (IamGroup group : details.groups()) { + xml.start("member").raw(groupDetailXml(group)).end("member"); + } + xml.end("GroupDetailList").start("RoleDetailList"); + for (IamRole role : details.roles()) { + xml.start("member").raw(roleDetailXml(role)).end("member"); + } + xml.end("RoleDetailList").start("Policies"); + for (IamPolicy policy : details.policies()) { + xml.start("member") + .raw(managedPolicyDetailXml(policy, details.attachmentCounts(), details.permissionsBoundaryUsageCounts())) + .end("member"); + } + xml.end("Policies").elem("IsTruncated", false); + return Response.ok(AwsQueryResponse.envelope("GetAccountAuthorizationDetails", AwsNamespaces.IAM, xml.build())).build(); + } + + private String userDetailXml(IamUser u) { + XmlBuilder xml = new XmlBuilder() + .raw(userXml(u, true)) + .raw(policyDetailListXml("UserPolicyList", u.getInlinePolicies())) + .start("GroupList"); + for (String groupName : u.getGroupNames()) { + xml.elem("member", groupName); + } + return xml.end("GroupList") + .raw(attachedManagedPoliciesXml(iamService.listAttachedUserPolicies(u.getUserName(), null))) + .raw(permissionsBoundaryXml(u.getPermissionsBoundaryArn())) + .build(); + } + + private String groupDetailXml(IamGroup g) { + return new XmlBuilder() + .raw(groupXml(g)) + .raw(policyDetailListXml("GroupPolicyList", g.getInlinePolicies())) + .raw(attachedManagedPoliciesXml(iamService.listAttachedGroupPolicies(g.getGroupName(), null))) + .build(); + } + + // RoleDetail is not the same subset as ListRoles's Role type: it carries + // AssumeRolePolicyDocument (which ListRoles also carries) but, per the wire model, never + // MaxSessionDuration or Description, so this does not reuse roleXml's general fragment. + private String roleDetailXml(IamRole r) { + XmlBuilder xml = new XmlBuilder() + .elem("Path", r.getPath()) + .elem("RoleName", r.getRoleName()) + .elem("RoleId", r.getRoleId()) + .elem("Arn", r.getArn()) + .elem("CreateDate", isoDate(r.getCreateDate())) + .elem("AssumeRolePolicyDocument", r.getAssumeRolePolicyDocument()) + .raw(tagsElement(r.getTags())) + .start("InstanceProfileList"); + for (InstanceProfile profile : iamService.listInstanceProfilesForRole(r.getRoleName())) { + xml.start("member").raw(instanceProfileXml(profile, true)).end("member"); + } + return xml.end("InstanceProfileList") + .raw(policyDetailListXml("RolePolicyList", r.getInlinePolicies())) + .raw(attachedManagedPoliciesXml(iamService.listAttachedRolePolicies(r.getRoleName(), null))) + .raw(permissionsBoundaryXml(r.getPermissionsBoundaryArn())) + .build(); + } + + // AttachmentCount and PermissionsBoundaryUsageCount come from the caller's account-scoped + // scan (see IamService.getAccountAuthorizationDetails), not IamPolicy.getAttachmentCount(): + // for an AWS-managed policy that field is shared process-wide across every account. + private String managedPolicyDetailXml(IamPolicy p, Map attachmentCounts, + Map permissionsBoundaryUsageCounts) { + XmlBuilder xml = new XmlBuilder() + .elem("PolicyName", p.getPolicyName()) + .elem("PolicyId", p.getPolicyId()) + .elem("Arn", p.getArn()) + .elem("Path", p.getPath()) + .elem("DefaultVersionId", p.getDefaultVersionId()) + .elem("AttachmentCount", (long) attachmentCounts.getOrDefault(p.getArn(), 0)) + .elem("PermissionsBoundaryUsageCount", + (long) permissionsBoundaryUsageCounts.getOrDefault(p.getArn(), 0)) + .elem("IsAttachable", true) + .elem("Description", p.getDescription()) + .elem("CreateDate", isoDate(p.getCreateDate())) + .elem("UpdateDate", isoDate(p.getUpdateDate())) + .start("PolicyVersionList"); + for (PolicyVersion version : p.getVersions().values()) { + xml.start("member").raw(policyVersionXml(version)).end("member"); + } + return xml.end("PolicyVersionList").build(); + } + + private String policyDetailListXml(String wrapperName, Map inlinePolicies) { + XmlBuilder xml = new XmlBuilder().start(wrapperName); + for (Map.Entry entry : inlinePolicies.entrySet()) { + xml.start("member") + .elem("PolicyName", entry.getKey()) + .elem("PolicyDocument", entry.getValue()) + .end("member"); + } + return xml.end(wrapperName).build(); + } + + private String attachedManagedPoliciesXml(List attached) { + XmlBuilder xml = new XmlBuilder().start("AttachedManagedPolicies"); + for (IamPolicy p : attached) { + xml.start("member") + .elem("PolicyName", p.getPolicyName()) + .elem("PolicyArn", p.getArn()) + .end("member"); + } + return xml.end("AttachedManagedPolicies").build(); + } + + private String permissionsBoundaryXml(String boundaryArn) { + if (boundaryArn == null) { + return ""; + } + return new XmlBuilder().start("PermissionsBoundary") + .elem("PermissionsBoundaryType", "Policy") + .elem("PermissionsBoundaryArn", boundaryArn) + .end("PermissionsBoundary") + .build(); + } + private Response handleCreatePolicyVersion(MultivaluedMap params) { String policyArn = getParam(params, "PolicyArn"); String document = getParam(params, "PolicyDocument"); @@ -1159,15 +1291,20 @@ public class IamQueryHandler { // ========================================================================= private Response handleCreateInstanceProfile(MultivaluedMap params) { + Map tags = extractTags(params); InstanceProfile profile = iamService.createInstanceProfile( getParam(params, "InstanceProfileName"), getParam(params, "Path")); - String result = new XmlBuilder().start("InstanceProfile").raw(instanceProfileXml(profile)).end("InstanceProfile").build(); + if (!tags.isEmpty()) { + iamService.tagInstanceProfile(profile.getInstanceProfileName(), tags); + profile = iamService.getInstanceProfile(profile.getInstanceProfileName()); + } + String result = new XmlBuilder().start("InstanceProfile").raw(instanceProfileXml(profile, true)).end("InstanceProfile").build(); return Response.ok(AwsQueryResponse.envelope("CreateInstanceProfile", AwsNamespaces.IAM, result)).build(); } private Response handleGetInstanceProfile(MultivaluedMap params) { InstanceProfile profile = iamService.getInstanceProfile(getParam(params, "InstanceProfileName")); - String result = new XmlBuilder().start("InstanceProfile").raw(instanceProfileXml(profile)).end("InstanceProfile").build(); + String result = new XmlBuilder().start("InstanceProfile").raw(instanceProfileXml(profile, true)).end("InstanceProfile").build(); return Response.ok(AwsQueryResponse.envelope("GetInstanceProfile", AwsNamespaces.IAM, result)).build(); } @@ -1180,7 +1317,8 @@ public class IamQueryHandler { List profiles = iamService.listInstanceProfiles(getParam(params, "PathPrefix")); var xml = new XmlBuilder().start("InstanceProfiles"); for (InstanceProfile p : profiles) { - xml.start("member").raw(instanceProfileXml(p)).end("member"); + // Documented listing subset: tags are omitted here, unlike GetInstanceProfile. + xml.start("member").raw(instanceProfileXml(p, false)).end("member"); } xml.end("InstanceProfiles").elem("IsTruncated", false); return Response.ok(AwsQueryResponse.envelope("ListInstanceProfiles", AwsNamespaces.IAM, xml.build())).build(); @@ -1200,7 +1338,7 @@ public class IamQueryHandler { List profiles = iamService.listInstanceProfilesForRole(getParam(params, "RoleName")); var xml = new XmlBuilder().start("InstanceProfiles"); for (InstanceProfile p : profiles) { - xml.start("member").raw(instanceProfileXml(p)).end("member"); + xml.start("member").raw(instanceProfileXml(p, true)).end("member"); } xml.end("InstanceProfiles").elem("IsTruncated", false); return Response.ok(AwsQueryResponse.envelope("ListInstanceProfilesForRole", AwsNamespaces.IAM, xml.build())).build(); @@ -1425,7 +1563,13 @@ public class IamQueryHandler { return xml.elem("CreateDate", isoDate(k.getCreateDate())).build(); } - private String instanceProfileXml(InstanceProfile p) { + // detailed is per-operation, not per-profile, mirroring roleXml/userXml/policyXml: + // ListInstanceProfiles documents itself as a listing subset ("this operation does not + // return tags, even though they are an attribute of the returned object"), the same note + // ListRoles carries. GetInstanceProfile, CreateInstanceProfile, ListInstanceProfilesForRole + // and the InstanceProfileList embedded in GetAccountAuthorizationDetails's RoleDetail carry + // no such note, so they stay detailed. + private String instanceProfileXml(InstanceProfile p, boolean detailed) { var xml = new XmlBuilder() .elem("InstanceProfileName", p.getInstanceProfileName()) .elem("InstanceProfileId", p.getInstanceProfileId()) @@ -1439,7 +1583,8 @@ public class IamQueryHandler { xml.start("member").raw(roleXml(role, false)).end("member"); } catch (AwsException ignored) {} } - return xml.end("Roles").build(); + xml.end("Roles"); + return xml.raw(detailed ? tagsElement(p.getTags()) : "").build(); } private String attachedPoliciesXml(List policyList) { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index bf76e145c9..40e21d2e5e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -41,6 +41,7 @@ import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.UUID; @@ -2794,4 +2795,81 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public Map listInstanceProfileTags(String instanceProfileName) { return getInstanceProfile(instanceProfileName).getTags(); } + + /** + * Every user, group and role in the account, plus the policies relevant to them: every + * local (customer-managed) policy, and every AWS-managed policy actually attached to or + * used as a boundary by something in the account. Backs GetAccountAuthorizationDetails. + * + *

{@code attachmentCounts} and {@code permissionsBoundaryUsageCounts} are computed by + * scanning this account's own users, groups and roles, not read off {@link + * IamPolicy#getAttachmentCount()}. For an AWS-managed policy that field is shared process-wide + * across every account (see {@link #awsManagedPolicies}), so trusting it here would leak one + * account's attachments into another's response. A local policy's own counter is already + * account-scoped and would agree with this scan; computing it uniformly for both avoids + * special-casing and keeps this method independent of that stored field either way. + */ + public AccountAuthorizationDetails getAccountAuthorizationDetails() { + List allUsers = listUsers(null); + List allGroups = listGroups(null); + List allRoles = listRoles(null); + + Map attachmentCounts = new LinkedHashMap<>(); + Map boundaryUsageCounts = new LinkedHashMap<>(); + Set referencedAwsManagedArns = new LinkedHashSet<>(); + + for (IamUser user : allUsers) { + tallyAttachments(user.getAttachedPolicyArns(), attachmentCounts, referencedAwsManagedArns); + tallyBoundaryUsage(user.getPermissionsBoundaryArn(), boundaryUsageCounts, referencedAwsManagedArns); + } + for (IamGroup group : allGroups) { + tallyAttachments(group.getAttachedPolicyArns(), attachmentCounts, referencedAwsManagedArns); + } + for (IamRole role : allRoles) { + tallyAttachments(role.getAttachedPolicyArns(), attachmentCounts, referencedAwsManagedArns); + tallyBoundaryUsage(role.getPermissionsBoundaryArn(), boundaryUsageCounts, referencedAwsManagedArns); + } + + List allPolicies = new ArrayList<>(listPolicies("Local", null)); + for (String arn : referencedAwsManagedArns) { + allPolicies.add(getPolicy(arn)); + } + + return new AccountAuthorizationDetails( + allUsers, allGroups, allRoles, allPolicies, attachmentCounts, boundaryUsageCounts); + } + + private void tallyAttachments(List attachedPolicyArns, Map attachmentCounts, + Set referencedAwsManagedArns) { + for (String arn : attachedPolicyArns) { + attachmentCounts.merge(arn, 1, Integer::sum); + if (arn.startsWith(AwsManagedPolicies.ARN_PREFIX)) { + referencedAwsManagedArns.add(arn); + } + } + } + + private void tallyBoundaryUsage(String permissionsBoundaryArn, Map boundaryUsageCounts, + Set referencedAwsManagedArns) { + if (permissionsBoundaryArn == null) { + return; + } + boundaryUsageCounts.merge(permissionsBoundaryArn, 1, Integer::sum); + if (permissionsBoundaryArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) { + referencedAwsManagedArns.add(permissionsBoundaryArn); + } + } + + /** + * @param attachmentCounts arn -> number of users, groups and roles it is attached to + * @param permissionsBoundaryUsageCounts arn -> number of users and roles using it as a boundary + */ + public record AccountAuthorizationDetails( + List users, + List groups, + List roles, + List policies, + Map attachmentCounts, + Map permissionsBoundaryUsageCounts) { + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/GetAccountAuthorizationDetailsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/GetAccountAuthorizationDetailsIntegrationTest.java new file mode 100644 index 0000000000..d512653379 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/GetAccountAuthorizationDetailsIntegrationTest.java @@ -0,0 +1,184 @@ +package io.github.hectorvent.floci.services.iam; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; + +/** + * Verifies GetAccountAuthorizationDetails against the real wire shape (UserDetail, GroupDetail, + * RoleDetail, ManagedPolicyDetail). IAM state is shared across the whole test suite and this + * action returns everything unfiltered, so every assertion locates its own entities by name or + * ARN with a Groovy {@code find}, rather than asserting on the response as a whole. + */ +@QuarkusTest +class GetAccountAuthorizationDetailsIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request"; + + private static final String TRUST_POLICY = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}"; + + private static final String POLICY_DOCUMENT = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + private static io.restassured.specification.RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } + + @Test + void userDetailIncludesInlinePolicyGroupMembershipAttachedPolicyAndBoundary() { + String s = suffix(); + String user = "aad-user-" + s; + String group = "aad-group-" + s; + + iam("CreateUser").formParam("UserName", user) + .when().post("/").then().statusCode(200); + iam("PutUserPolicy").formParam("UserName", user) + .formParam("PolicyName", "inline").formParam("PolicyDocument", POLICY_DOCUMENT) + .when().post("/").then().statusCode(200); + iam("CreateGroup").formParam("GroupName", group) + .when().post("/").then().statusCode(200); + iam("AddUserToGroup").formParam("GroupName", group).formParam("UserName", user) + .when().post("/").then().statusCode(200); + iam("AttachUserPolicy").formParam("UserName", user) + .formParam("PolicyArn", "arn:aws:iam::aws:policy/ReadOnlyAccess") + .when().post("/").then().statusCode(200); + String boundaryArn = iam("CreatePolicy").formParam("PolicyName", "aad-boundary-" + s) + .formParam("PolicyDocument", POLICY_DOCUMENT) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + iam("PutUserPermissionsBoundary").formParam("UserName", user).formParam("PermissionsBoundary", boundaryArn) + .when().post("/").then().statusCode(200); + + iam("GetAccountAuthorizationDetails") + .when().post("/").then() + .statusCode(200) + .contentType("application/xml") + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".UserDetailList.member.find { it.UserName == '" + user + "' }.UserPolicyList.member.PolicyName", + equalTo("inline")) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".UserDetailList.member.find { it.UserName == '" + user + "' }.GroupList.member", + equalTo(group)) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".UserDetailList.member.find { it.UserName == '" + user + "' }" + + ".AttachedManagedPolicies.member.PolicyArn", + equalTo("arn:aws:iam::aws:policy/ReadOnlyAccess")) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".UserDetailList.member.find { it.UserName == '" + user + "' }" + + ".PermissionsBoundary.PermissionsBoundaryArn", + equalTo(boundaryArn)) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".UserDetailList.member.find { it.UserName == '" + user + "' }" + + ".PermissionsBoundary.PermissionsBoundaryType", + equalTo("Policy")); + } + + @Test + void groupDetailIncludesInlineAndAttachedPolicies() { + String s = suffix(); + String group = "aad-group2-" + s; + + iam("CreateGroup").formParam("GroupName", group) + .when().post("/").then().statusCode(200); + iam("PutGroupPolicy").formParam("GroupName", group) + .formParam("PolicyName", "inline").formParam("PolicyDocument", POLICY_DOCUMENT) + .when().post("/").then().statusCode(200); + iam("AttachGroupPolicy").formParam("GroupName", group) + .formParam("PolicyArn", "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess") + .when().post("/").then().statusCode(200); + + iam("GetAccountAuthorizationDetails") + .when().post("/").then() + .statusCode(200) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".GroupDetailList.member.find { it.GroupName == '" + group + "' }" + + ".GroupPolicyList.member.PolicyName", + equalTo("inline")) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".GroupDetailList.member.find { it.GroupName == '" + group + "' }" + + ".AttachedManagedPolicies.member.PolicyArn", + equalTo("arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess")); + } + + @Test + void roleDetailIncludesAssumeRolePolicyInstanceProfileAndAttachedPolicy() { + String s = suffix(); + String role = "aad-role-" + s; + String profile = "aad-profile-" + s; + + iam("CreateRole").formParam("RoleName", role).formParam("Path", "/") + .formParam("AssumeRolePolicyDocument", TRUST_POLICY) + .when().post("/").then().statusCode(200); + iam("CreateInstanceProfile").formParam("InstanceProfileName", profile) + .when().post("/").then().statusCode(200); + iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profile).formParam("RoleName", role) + .when().post("/").then().statusCode(200); + iam("AttachRolePolicy").formParam("RoleName", role) + .formParam("PolicyArn", "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole") + .when().post("/").then().statusCode(200); + + iam("GetAccountAuthorizationDetails") + .when().post("/").then() + .statusCode(200) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".RoleDetailList.member.find { it.RoleName == '" + role + "' }" + + ".InstanceProfileList.member.InstanceProfileName", + equalTo(profile)) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".RoleDetailList.member.find { it.RoleName == '" + role + "' }" + + ".AttachedManagedPolicies.member.PolicyArn", + equalTo("arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole")) + // RoleDetail's own AssumeRolePolicyDocument, not just the one embedded via + // InstanceProfileList's role subset. + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".RoleDetailList.member.find { it.RoleName == '" + role + "' }.AssumeRolePolicyDocument", + containsString("ec2.amazonaws.com")); + } + + @Test + void localPolicyIncludesVersionListAndAttachmentCountScopedToThisAccount() { + String s = suffix(); + String policyName = "aad-policy-" + s; + String user = "aad-policy-user-" + s; + + String arn = iam("CreatePolicy").formParam("PolicyName", policyName) + .formParam("PolicyDocument", POLICY_DOCUMENT) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + iam("CreatePolicyVersion").formParam("PolicyArn", arn) + .formParam("PolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"s3:PutObject\",\"Resource\":\"*\"}]}") + .formParam("SetAsDefault", "true") + .when().post("/").then().statusCode(200); + iam("CreateUser").formParam("UserName", user) + .when().post("/").then().statusCode(200); + iam("AttachUserPolicy").formParam("UserName", user).formParam("PolicyArn", arn) + .when().post("/").then().statusCode(200); + + iam("GetAccountAuthorizationDetails") + .when().post("/").then() + .statusCode(200) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".Policies.member.find { it.Arn == '" + arn + "' }.AttachmentCount", + equalTo("1")) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".Policies.member.find { it.Arn == '" + arn + "' }.PolicyVersionList.member.VersionId", + hasItem("v2")) + .body("GetAccountAuthorizationDetailsResponse.GetAccountAuthorizationDetailsResult" + + ".Policies.member.find { it.Arn == '" + arn + "' }.PolicyVersionList.member.Document", + hasItem(containsString("PutObject"))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamResourceTagsInResponseTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamResourceTagsInResponseTest.java index f7af710483..3d8b1e8675 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamResourceTagsInResponseTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamResourceTagsInResponseTest.java @@ -282,4 +282,92 @@ class IamResourceTagsInResponseTest { .body(not(containsString(""))) .body(not(containsString("profile-must-not-be-listed"))); } + + /** + * Unlike Role, User and Policy, AWS documents no listing-subset exclusion for + * InstanceProfile: ListInstanceProfiles uses the same InstanceProfile shape as + * CreateInstanceProfile and GetInstanceProfile, so its own tags (not the embedded role's) + * belong on all three. CreateInstanceProfile also accepts Tags at creation time, which it + * previously silently dropped. + */ + @Test + void createAndGetInstanceProfileEchoTheirOwnTags() { + String profile = "TagEchoProfile"; + + iam("CreateInstanceProfile") + .formParam("InstanceProfileName", profile) + .formParam("Tags.member.1.Key", "Environment") + .formParam("Tags.member.1.Value", "dev") + .when().post("/").then() + .statusCode(200) + .body(containsString("Environment")) + .body(containsString("dev")); + + iam("GetInstanceProfile") + .formParam("InstanceProfileName", profile) + .when().post("/").then() + .statusCode(200) + .body(containsString("Environment")) + .body(containsString("dev")); + } + + @Test + void getInstanceProfileOmitsTheTagsElementEntirelyWhenUntagged() { + String profile = "UntaggedEchoProfile"; + + iam("CreateInstanceProfile") + .formParam("InstanceProfileName", profile) + .when().post("/").then().statusCode(200); + + iam("GetInstanceProfile") + .formParam("InstanceProfileName", profile) + .when().post("/").then() + .statusCode(200) + .body(not(containsString(""))); + } + + @Test + void listInstanceProfilesOmitsTagsEvenForATaggedProfile() { + String profile = "ListSubsetProfile"; + + iam("CreateInstanceProfile") + .formParam("InstanceProfileName", profile) + .formParam("Tags.member.1.Key", "ListProfilesMarker") + .formParam("Tags.member.1.Value", "must-not-be-listed") + .when().post("/").then().statusCode(200); + + // ListInstanceProfiles documents itself as a listing subset, the same note ListRoles + // carries: "this operation does not return tags, even though they are an attribute of + // the returned object." + iam("ListInstanceProfiles") + .when().post("/").then() + .statusCode(200) + .body(containsString("" + profile + "")) + .body(not(containsString(""))) + .body(not(containsString("must-not-be-listed"))); + } + + @Test + void listInstanceProfilesForRoleAndGetAccountAuthorizationDetailsStillIncludeInstanceProfileTags() { + String s = Long.toString(System.nanoTime(), 36); + String role = "ListForRoleTagRole-" + s; + String profile = "ListForRoleTagProfile-" + s; + + iam("CreateRole").formParam("RoleName", role).formParam("Path", "/") + .formParam("AssumeRolePolicyDocument", TRUST_POLICY) + .when().post("/").then().statusCode(200); + iam("CreateInstanceProfile") + .formParam("InstanceProfileName", profile) + .formParam("Tags.member.1.Key", "ListForRoleMarker") + .formParam("Tags.member.1.Value", "must-be-listed") + .when().post("/").then().statusCode(200); + iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profile).formParam("RoleName", role) + .when().post("/").then().statusCode(200); + + // Unlike ListInstanceProfiles, this operation carries no listing-subset note. + iam("ListInstanceProfilesForRole").formParam("RoleName", role) + .when().post("/").then() + .statusCode(200) + .body(containsString("must-be-listed")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index 84d77b79cb..9b109e5dfb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java @@ -1953,4 +1953,106 @@ class IamServiceTest { iamService.createAccountAlias("a".repeat(63)); assertEquals("a".repeat(63), iamService.getAccountAlias().orElseThrow()); } + + // ========================================================================= + // GetAccountAuthorizationDetails + // ========================================================================= + + @Test + void accountAuthorizationDetailsAlwaysIncludesLocalPoliciesEvenUnattached() { + IamPolicy unattached = iamService.createPolicy("aad-unattached", "/", null, + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}", + null); + + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + assertTrue(details.policies().stream().anyMatch(p -> p.getArn().equals(unattached.getArn()))); + } + + @Test + void accountAuthorizationDetailsExcludesAnAwsManagedPolicyNotAttachedToAnything() { + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + // A freshly constructed IamService has attached nothing, so a well-known AWS-managed + // policy this test never touches must not appear. + assertTrue(details.policies().stream() + .noneMatch(p -> p.getArn().equals("arn:aws:iam::aws:policy/AdministratorAccess"))); + } + + @Test + void accountAuthorizationDetailsIncludesAnAwsManagedPolicyOnceAttachedToAUser() { + iamService.createUser("aad-user", "/"); + iamService.attachUserPolicy("aad-user", "arn:aws:iam::aws:policy/AdministratorAccess"); + + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + assertTrue(details.policies().stream() + .anyMatch(p -> p.getArn().equals("arn:aws:iam::aws:policy/AdministratorAccess"))); + } + + /** + * AttachmentCount is computed by scanning this account's own users, groups and roles, not + * read off {@code IamPolicy.getAttachmentCount()}: for an AWS-managed policy that field is + * shared process-wide across every {@code IamService} instance's account, so a second, + * independent instance attaching the same ARN must not change what this instance reports. + */ + @Test + void attachmentCountIsScopedToThisAccountNotTheSharedAwsManagedPolicyObject() { + String arn = "arn:aws:iam::aws:policy/AdministratorAccess"; + iamService.createUser("aad-scoped-user", "/"); + iamService.attachUserPolicy("aad-scoped-user", arn); + + IamService other = iamService(false); + other.createUser("other-account-user", "/"); + other.attachUserPolicy("other-account-user", arn); + other.createUser("other-account-user-2", "/"); + other.attachUserPolicy("other-account-user-2", arn); + + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + assertEquals(1, details.attachmentCounts().get(arn)); + } + + @Test + void attachmentCountTalliesAcrossUsersGroupsAndRoles() { + String arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"; + iamService.createUser("aad-tally-user", "/"); + iamService.attachUserPolicy("aad-tally-user", arn); + iamService.createGroup("aad-tally-group", "/"); + iamService.attachGroupPolicy("aad-tally-group", arn); + iamService.createRole("aad-tally-role", "/", "{}", null, 0, null); + iamService.attachRolePolicy("aad-tally-role", arn); + + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + assertEquals(3, details.attachmentCounts().get(arn)); + } + + @Test + void permissionsBoundaryUsageCountTalliesAcrossUsersAndRoles() { + IamPolicy boundary = iamService.createPolicy("aad-boundary", "/", null, + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}", + null); + iamService.createUser("aad-boundary-user", "/"); + iamService.putUserPermissionsBoundary("aad-boundary-user", boundary.getArn()); + iamService.createRole("aad-boundary-role", "/", "{}", null, 0, null); + iamService.putRolePermissionsBoundary("aad-boundary-role", boundary.getArn()); + + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + assertEquals(2, details.permissionsBoundaryUsageCounts().get(boundary.getArn())); + } + + @Test + void accountAuthorizationDetailsListsEveryUserGroupAndRole() { + iamService.createUser("aad-list-user", "/"); + iamService.createGroup("aad-list-group", "/"); + iamService.createRole("aad-list-role", "/", "{}", null, 0, null); + + IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails(); + + assertTrue(details.users().stream().anyMatch(u -> u.getUserName().equals("aad-list-user"))); + assertTrue(details.groups().stream().anyMatch(g -> g.getGroupName().equals("aad-list-group"))); + assertTrue(details.roles().stream().anyMatch(r -> r.getRoleName().equals("aad-list-role"))); + } }