@Test public void testAutoSuggestion() throws Exception { ListRolesRequest request = new ListRolesRequest().withMaxItems(1000); Role role1 = new Role().withRoleName("foobar1"); Role role2 = new Role().withRoleName("afoobar"); Role role3 = new Role().withRoleName("foooobar"); ListRolesResult mockResult = new ListRolesResult(); mockResult.withRoles(role1, role2, role3); when(mockClient.listRoles(request)).thenReturn(mockResult); List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("foobar"); assertEquals(list.size(), 2); assertEquals(list.get(0).name, "foobar1"); assertEquals(list.get(1).name, "afoobar"); verify(mockClient, times(1)).listRoles(request); }
@Test public void testAutoSuggestionCaseInsensitive() throws Exception { ListRolesRequest request = new ListRolesRequest().withMaxItems(1000); Role lowercase = new Role().withRoleName("foobar"); Role uppercase = new Role().withRoleName("FOOBAR"); Role mixedCase = new Role().withRoleName("FooBar"); ListRolesResult mockResult = new ListRolesResult(); mockResult.withRoles(lowercase, uppercase, mixedCase); when(mockClient.listRoles(request)).thenReturn(mockResult); List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("fOOb"); assertEquals(list.size(), 3); assertEquals(list.get(0).name, "foobar"); assertEquals(list.get(1).name, "FOOBAR"); assertEquals(list.get(2).name, "FooBar"); }
boolean policyChanged(String localPolicyJSON, com.amazonaws.services.identitymanagement.model.InstanceProfile remoteInstanceProfile) { String instanceProfileName = remoteInstanceProfile.getInstanceProfileName(); List<Role> roles = remoteInstanceProfile.getRoles(); Asserts.isFalse(roles.isEmpty(), "instance profile does not not have role, please check whether the role failed to add to instance profile, instanceProfileName={}", instanceProfileName); Asserts.equals(roles.size(), 1, "instance profile should only have one role, check whether it's modified not by cmn, instanceProfileName={}, roles={}", instanceProfileName, roles); Role role = roles.get(0); Optional<Policy> remotePolicy = AWS.iam.findRolePolicy(role.getRoleName(), role.getRoleName()); if (!remotePolicy.isPresent()) { logger.warn("role policy doesn't exist, it could be due to failure of last sync, it will try to create this time, instanceProfileName={}", instanceProfileName); return true; } Policy localPolicy = Policy.fromJson(localPolicyJSON); return policyChanged(localPolicy, remotePolicy.get()); }
private static void cleanUpIAM(Regions testRegion, String testResourcePrefix, Date createdBeforeThreshold, AWSCredentialsProvider awsCredentials) { AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard() .withCredentials(awsCredentials) .withRegion(testRegion) .build(); IAMPolicyManager iamPolicyManager = IAMPolicyManager.fromCredentials(awsCredentials, new ClientConfiguration()); LOG.info("Cleaning IAM policies..."); ListPoliciesRequest listPoliciesRequest = new ListPoliciesRequest().withPathPrefix(IAMPolicyManager.PATH_PREFIX); List<Policy> policies = iamClient.listPolicies(listPoliciesRequest).getPolicies(); for (Policy policy: policies) { if (policy.getPolicyName().startsWith(testResourcePrefix) && policy.getCreateDate().before(createdBeforeThreshold)) { LOG.info("Cleaning up policy: " + policy.getPolicyName()); IAMPolicyName iamPolicyName = IAMPolicyName.fromString(policy.getPolicyName()); iamPolicyManager.detachAllPrincipals(iamPolicyName.group); DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest().withPolicyArn(policy.getArn()); iamClient.deletePolicy(deletePolicyRequest); } } LOG.info("Cleaning IAM roles created for the assume role tests..."); ListRolesRequest listRolesRequest = new ListRolesRequest().withPathPrefix(IAMHelper.PATH); List<Role> roles = iamClient.listRoles(listRolesRequest).getRoles(); for (Role role: roles) { if (role.getRoleName().startsWith(AssumedRoleTestContext.ROLE_PREFIX) && role.getCreateDate().before(createdBeforeThreshold)) { LOG.info("Cleaning up role: " + role.getRoleName()); DeleteRoleRequest deleteRoleRequest = new DeleteRoleRequest().withRoleName(role.getRoleName()); iamClient.deleteRole(deleteRoleRequest); } } }
private Role createRole(String name, String policyDocument) { return new Role() .withArn("arn:aws:iam::" + ACCOUNT_ID + ":role/" + name) .withRoleName(name) .withRoleId(randomAlphanumeric(21).toUpperCase()) // IDs look like: "AROAIM3TRURL24R6YZAS5" .withAssumeRolePolicyDocument(policyDocument); }
public List<AbstractResource<?>> toIamRoles(List<Role> roles, String accountId, DateTime dt) { List<AbstractResource<?>> resources = new ArrayList<>(); for (Role role : roles) { IamRole iamRole = new IamRole(); conf(iamRole, accountId, dt); iamRole.setResource(role); resources.add(iamRole); } log.debug("{} roles found via api and converted to IamRole", resources.size()); return resources; }
/** * @inheritDoc */ @Override public void createAgentInstanceProfile( String profileName, String controlRoleArn, Identity identity ) { AmazonIdentityManagement iam = ActivityUtils.createClient( AmazonIdentityManagementClient.class, identity ); // Create role if necessary String roleName = profileName + "-role"; Map<String, String> policyVariables = new HashMap<String, String>(); policyVariables.put( "CONTROLLER_ROLE_ARN", controlRoleArn ); Role role = ActivityUtils.createRole( roleName, iam, "datamung/agent-policy.json", policyVariables, "datamung/agent-trust.json", null ); // Create instance profile and associate role if necessary boolean roleAssociationRequired = true; try { iam.createInstanceProfile( new CreateInstanceProfileRequest().withInstanceProfileName( profileName ).withPath( role.getPath() ) ); } catch ( EntityAlreadyExistsException e ) { LOG.info( "Instance profile " + profileName + " already exists!" ); roleAssociationRequired = iam.getInstanceProfile( new GetInstanceProfileRequest().withInstanceProfileName( profileName ) ).getInstanceProfile().getRoles().isEmpty(); } if ( roleAssociationRequired ) { LOG.info( "Adding role " + roleName + " to instance profile " + profileName ); iam.addRoleToInstanceProfile( new AddRoleToInstanceProfileRequest().withInstanceProfileName( profileName ).withRoleName( roleName ) ); } }
private String getAccountIdFromInstanceProfile() throws IOException { URLConnection con = new URL( "http://169.254.169.254/latest/meta-data/iam/security-credentials/" ).openConnection(); con.setConnectTimeout( 5000 ); con.setReadTimeout( 2000 ); String text; InputStream in = con.getInputStream(); try { text = IOUtils.toString( in ); } finally { IOUtils.closeQuietly( in ); } LOG.info( "Read instance profile " + text + " from EC2 metadata" ); String profileName = StringUtils.trimToNull( text ); if ( profileName == null ) { throw new IllegalStateException( "Can't read profile name from content [" + profileName + "]" ); } Role role = aim.getRole( new GetRoleRequest().withRoleName( profileName ) ).getRole(); String[] parts = role.getArn().split( ":" ); if ( parts.length < 5 ) { throw new IllegalStateException( "Can't parse role ARN from " + role ); } return parts[4]; }
/** * @inheritDoc */ @Override public String createAgentControllerRole( String roleName, String workflowTaskList, Identity identity ) { Map<String, String> policyVariables = new HashMap<String, String>(); policyVariables.put( "CONTROLLER_ACCOUNT_ID", accountId ); policyVariables.put( "SWF_DOMAIN", contextProvider.getActivityExecutionContext().getDomain() ); policyVariables.put( "TASK_LIST", workflowTaskList ); AmazonIdentityManagement clientIam = ActivityUtils.createClient( AmazonIdentityManagementClient.class, identity ); Map<String, String> trustVariables = new HashMap<String, String>(); trustVariables.put( "CLIENT_EXTERNAL_ID", AgentConfig.ROLE_EXTERNAL_ID ); trustVariables.put( "CLIENT_ACCOUNT_ID", ActivityUtils.getAccountId( clientIam ) ); Role role = ActivityUtils.createRole( roleName, serverIam, "datamung/agent-controller-policy.json", policyVariables, "datamung/agent-controller-trust.json", trustVariables ); return role.getArn(); }