private AmazonIdentityManagement client() { return AmazonIdentityManagementClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(new AWSCredentials() { @Override public String getAWSAccessKeyId() { return bookmark.getCredentials().getUsername(); } @Override public String getAWSSecretKey() { return bookmark.getCredentials().getPassword(); } })) .withClientConfiguration(configuration) .withRegion(Regions.DEFAULT_REGION).build(); }
void addRolesToIdentityPool(String unauthenticatedRoleName, String unauthenticatedRole, String authenticatedRoleName, String authenticatedRole, String identityPoolId, AmazonCognitoIdentity client, LambdaLogger logger) { // First update the roles to use the actual pool id in their conditions logger .log("Updating authenticated and unauthenticated roles to use the actual identity pool id: " + identityPoolId); AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard().build(); UpdateAssumeRolePolicyRequest updateAssumeRolePolicyRequest = new UpdateAssumeRolePolicyRequest(); updateAssumeRolePolicyRequest.setRoleName(unauthenticatedRoleName); updateAssumeRolePolicyRequest.setPolicyDocument(getAssumeRolePolicyDocument(false, identityPoolId, logger)); iamClient.updateAssumeRolePolicy(updateAssumeRolePolicyRequest); updateAssumeRolePolicyRequest.setRoleName(authenticatedRoleName); updateAssumeRolePolicyRequest.setPolicyDocument(getAssumeRolePolicyDocument(true, identityPoolId, logger)); iamClient.updateAssumeRolePolicy(updateAssumeRolePolicyRequest); // And add the updated roles to the pool logger.log("Adding updated authenticated and unauthenticated roles to the identity pool"); SetIdentityPoolRolesRequest setIdentityPoolRolesRequest = new SetIdentityPoolRolesRequest(); setIdentityPoolRolesRequest.addRolesEntry("authenticated", authenticatedRole); setIdentityPoolRolesRequest.addRolesEntry("unauthenticated", unauthenticatedRole); setIdentityPoolRolesRequest.setIdentityPoolId(identityPoolId); client.setIdentityPoolRoles(setIdentityPoolRolesRequest); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a username\n" + "Ex: CreateUser <username>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String username = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreateUserRequest request = new CreateUserRequest() .withUserName(username); CreateUserResult response = iam.createUser(request); System.out.println("Successfully created user: " + response.getUser().getUserName()); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a certificate name\n" + "Ex: GetServerCertificate <certificate-name>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String cert_name = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); GetServerCertificateRequest request = new GetServerCertificateRequest() .withServerCertificateName(cert_name); GetServerCertificateResult response = iam.getServerCertificate(request); System.out.format("Successfully retrieved certificate with body %s", response.getServerCertificate().getCertificateBody()); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a policy arn\n" + "Ex: GetPolicy <policy-arn>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String policy_arn = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); GetPolicyRequest request = new GetPolicyRequest() .withPolicyArn(policy_arn); GetPolicyResult response = iam.getPolicy(request); System.out.format("Successfully retrieved policy %s", response.getPolicy().getPolicyName()); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a certificate name\n" + "Ex: DeleteServerCertificate <certificate-name>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String cert_name = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DeleteServerCertificateRequest request = new DeleteServerCertificateRequest() .withServerCertificateName(cert_name); DeleteServerCertificateResult response = iam.deleteServerCertificate(request); System.out.println("Successfully deleted server certificate " + cert_name); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a role name and policy arn\n" + "Ex: DetachRolePolicy <role-name> <policy-arn>>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String role_name = args[0]; String policy_arn = args[1]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DetachRolePolicyRequest request = new DetachRolePolicyRequest() .withRoleName(role_name) .withPolicyArn(policy_arn); DetachRolePolicyResult response = iam.detachRolePolicy(request); System.out.println("Successfully detached policy " + policy_arn + " from role " + role_name); }
public static void main(String[] args) { final String USAGE = "To run this example, supply an account alias\n" + "Ex: DeleteAccountAlias <account-alias>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String alias = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DeleteAccountAliasRequest request = new DeleteAccountAliasRequest() .withAccountAlias(alias); DeleteAccountAliasResult response = iam.deleteAccountAlias(request); System.out.println("Successfully deleted account alias " + alias); }
public static void main(String[] args) { final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); boolean done = false; ListUsersRequest request = new ListUsersRequest(); while(!done) { ListUsersResult response = iam.listUsers(request); for(User user : response.getUsers()) { System.out.format("Retrieved user %s", user.getUserName()); } request.setMarker(response.getMarker()); if(!response.getIsTruncated()) { done = true; } } }
public static void main(String[] args) { final String USAGE = "To run this example, supply an IAM user\n" + "Ex: CreateAccessKey <user>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String user = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreateAccessKeyRequest request = new CreateAccessKeyRequest() .withUserName(user); CreateAccessKeyResult response = iam.createAccessKey(request); System.out.println("Created access key: " + response.getAccessKey()); }
public static void main(String[] args) { final String USAGE = "To run this example, supply an access key id\n" + "Ex: AccessKeyLastUsed <access-key-id>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String access_id = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); GetAccessKeyLastUsedRequest request = new GetAccessKeyLastUsedRequest() .withAccessKeyId(access_id); GetAccessKeyLastUsedResult response = iam.getAccessKeyLastUsed(request); System.out.println("Access key was last used at: " + response.getAccessKeyLastUsed().getLastUsedDate()); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a policy name\n" + "Ex: CreatePolicy <policy-name>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String policy_name = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreatePolicyRequest request = new CreatePolicyRequest() .withPolicyName(policy_name) .withPolicyDocument(POLICY_DOCUMENT); CreatePolicyResult response = iam.createPolicy(request); System.out.println("Successfully created policy: " + response.getPolicy().getPolicyName()); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a username and access key id\n" + "Ex: DeleteAccessKey <username> <access-key-id>\n"; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String username = args[0]; String access_key = args[1]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DeleteAccessKeyRequest request = new DeleteAccessKeyRequest() .withAccessKeyId(access_key) .withUserName(username); DeleteAccessKeyResult response = iam.deleteAccessKey(request); System.out.println("Successfully deleted access key " + access_key + " from user " + username); }
public static void main(String[] args) { final String USAGE = "To run this example, supply an alias\n" + "Ex: CreateAccountAlias <alias>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String alias = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreateAccountAliasRequest request = new CreateAccountAliasRequest() .withAccountAlias(alias); CreateAccountAliasResult response = iam.createAccountAlias(request); System.out.println("Successfully created account alias: " + alias); }
@Override public void execute() throws MojoExecutionException, MojoFailureException { Proxy proxy = new Proxy(httpsProxyHost, httpsProxyPort, httpsProxyUsername, httpsProxyPassword); AwsKeyPair keyPair = Util.getAwsKeyPair(serverId, awsAccessKey, awsSecretAccessKey, settings, decrypter); final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); ClientConfiguration cc = Util.createConfiguration(proxy); AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder // .standard() // .withRegion(region) // .withCredentials(credentials) // .withClientConfiguration(cc) // .build(); String accountId = iam.getUser().getUser().getUserId(); project.getProperties().setProperty("aws.account.id", accountId); getLog().info("The following properties have been set for the project"); getLog().info("aws.account.id=" + accountId); }
public void createS3BucketProfile() { AmazonIdentityManagement aim = getClient(); String profile = getUserProperty( REPO_PROFILE ); String role = getUserProperty( REPO_ROLE ); if ( instanceProfileExists( profile ) ) { console.write( "Profile '" + profile + "' already exists" ); //$NON-NLS-1$ //$NON-NLS-2$ return; } CreateInstanceProfileResult result = aim.createInstanceProfile( new CreateInstanceProfileRequest().withInstanceProfileName( profile ) ); // add roles to profil aim.addRoleToInstanceProfile( new AddRoleToInstanceProfileRequest().withInstanceProfileName( profile ) .withRoleName( role ) ); console.write( "Profile '" + profile + "' created at " + result.getInstanceProfile().getCreateDate() ); //$NON-NLS-1$ //$NON-NLS-2$ }
private boolean checkIamOrS3Statement(String roleName, AmazonIdentityManagement client, String s) throws Exception { GetRolePolicyRequest getRolePolicyRequest = new GetRolePolicyRequest(); getRolePolicyRequest.setRoleName(roleName); getRolePolicyRequest.setPolicyName(s); GetRolePolicyResult rolePolicy = client.getRolePolicy(getRolePolicyRequest); String decode = URLDecoder.decode(rolePolicy.getPolicyDocument(), "UTF-8"); JsonNode object = JsonUtil.readTree(decode); JsonNode statement = object.get("Statement"); for (int i = 0; i < statement.size(); i++) { JsonNode action = statement.get(i).get("Action"); for (int j = 0; j < action.size(); j++) { String actionEntry = action.get(j).textValue().replaceAll(" ", "").toLowerCase(); if ("iam:createrole".equals(actionEntry) || "iam:*".equals(actionEntry)) { LOGGER.info("Role has able to operate on iam resources: {}.", action.get(j)); return true; } } } return false; }
public static void main(String... args) throws IOException { AWSCredentialsProvider credentials = CredentialsUtils.getAwsCredentials(); AmazonS3 storage = new AmazonS3Client(credentials); storage.setRegion(Region.getRegion(Regions.EU_WEST_1)); AmazonSQS queue = new AmazonSQSClient(credentials); queue.setRegion(Region.getRegion(Regions.EU_WEST_1)); AmazonEC2 machines = new AmazonEC2Client(credentials); machines.setRegion(Region.getRegion(Regions.EU_WEST_1)); AmazonIdentityManagement identityManagement = new AmazonIdentityManagementClient(credentials); identityManagement.setRegion(Region.getRegion(Regions.EU_WEST_1)); if ("launch".equals(args[0])) { setup(storage, queue, machines, identityManagement); manageAnswers(queue); } else if ("run".equals(args[0])) { run(storage, queue); } else { System.out.println("Huh hoh! Don't know what you intended to do..."); } }
public static PrincipalAutoSuggestion fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration) { AmazonIdentityManagement client = AmazonIdentityManagementClientBuilder.standard() .withCredentials(awsCredentials) .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration)) .withRegion(RegionResolver.getRegion()) .build(); return new PrincipalAutoSuggestion(client); }
public static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration) { AmazonIdentityManagement client = AmazonIdentityManagementClientBuilder.standard() .withCredentials(awsCredentials) .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration)) .withRegion(RegionResolver.getRegion()) .build(); return new IAMPolicyManager(client, awsCredentials, clientConfiguration); }
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); } } }
public static void main(String[] args) { final String USAGE = "To run this example, supply an IAM username\n" + "Ex: ListAccessKeys <username>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String username = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); boolean done = false; ListAccessKeysRequest request = new ListAccessKeysRequest() .withUserName(username); while (!done) { ListAccessKeysResult response = iam.listAccessKeys(request); for (AccessKeyMetadata metadata : response.getAccessKeyMetadata()) { System.out.format("Retrieved access key %s", metadata.getAccessKeyId()); } request.setMarker(response.getMarker()); if (!response.getIsTruncated()) { done = true; } } }
public static void main(String[] args) { final String USAGE = "To run this example, supply a username, access key id and status\n" + "Ex: UpdateAccessKey <username> <access-key-id> <Activate|Inactive>\n"; if (args.length != 3) { System.out.println(USAGE); System.exit(1); } String username = args[0]; String access_id = args[1]; String status = args[2]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); UpdateAccessKeyRequest request = new UpdateAccessKeyRequest() .withAccessKeyId(access_id) .withUserName(username) .withStatus(status); UpdateAccessKeyResult response = iam.updateAccessKey(request); System.out.printf( "Successfully updated status of access key %s to" + "status %s for user %s", access_id, status, username); }
public static void main(String[] args) { final String USAGE = "To run this example, supply the current certificate name and\n" + "a new name. Ex:\n\n" + "UpdateServerCertificate <current-name> <new-name>\n"; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String cur_name = args[0]; String new_name = args[1]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); UpdateServerCertificateRequest request = new UpdateServerCertificateRequest() .withServerCertificateName(cur_name) .withNewServerCertificateName(new_name); UpdateServerCertificateResult response = iam.updateServerCertificate(request); System.out.printf("Successfully updated server certificate to name %s", new_name); }
public static void main(String[] args) { final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); boolean done = false; ListServerCertificatesRequest request = new ListServerCertificatesRequest(); while(!done) { ListServerCertificatesResult response = iam.listServerCertificates(request); for(ServerCertificateMetadata metadata : response.getServerCertificateMetadataList()) { System.out.printf("Retrieved server certificate %s", metadata.getServerCertificateName()); } request.setMarker(response.getMarker()); if(!response.getIsTruncated()) { done = true; } } }
public static void main(String[] args) { final String USAGE = "To run this example, supply the current username and a new\n" + "username. Ex:\n\n" + "UpdateUser <current-name> <new-name>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String cur_name = args[0]; String new_name = args[1]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); UpdateUserRequest request = new UpdateUserRequest() .withUserName(cur_name) .withNewUserName(new_name); UpdateUserResult response = iam.updateUser(request); System.out.printf("Successfully updated user to username %s", new_name); }
public static void main(String[] args) { final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); ListAccountAliasesResult response = iam.listAccountAliases(); for (String alias : response.getAccountAliases()) { System.out.printf("Retrieved account alias %s", alias); } }
public static void main(String[] args) { final String USAGE = "To run this example, supply a username\n" + "Ex: DeleteUser <username>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String username = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DeleteUserRequest request = new DeleteUserRequest() .withUserName(username); try { iam.deleteUser(request); } catch (DeleteConflictException e) { System.out.println("Unable to delete user. Verify user is not" + " associated with any resources"); throw e; } System.out.println("Successfully deleted IAM user " + username); }
/** * Binds all the Amazon services used. */ @Override protected void configure() { final Region region = Region.getRegion(Regions.fromName(regionName)); bind(AmazonEC2.class).toInstance(createAmazonClientInstance(AmazonEC2Client.class, region)); bind(AmazonCloudFormation.class).toInstance(createAmazonClientInstance(AmazonCloudFormationClient.class, region)); bind(AmazonIdentityManagement.class).toInstance(createAmazonClientInstance(AmazonIdentityManagementClient.class, region)); bind(AWSKMS.class).toInstance(createAmazonClientInstance(AWSKMSClient.class, region)); bind(AmazonS3.class).toInstance(createAmazonClientInstance(AmazonS3Client.class, region)); bind(AmazonAutoScaling.class).toInstance(createAmazonClientInstance(AmazonAutoScalingClient.class, region)); bind(AWSSecurityTokenService.class).toInstance(createAmazonClientInstance(AWSSecurityTokenServiceClient.class, region)); bind(AWSLambda.class).toInstance(createAmazonClientInstance(AWSLambdaClient.class, region)); bind(AmazonSNS.class).toInstance(createAmazonClientInstance(AmazonSNSClient.class, region)); }
/** * Construct a service implementation using the specified client object. * * @param client The low-level client which the service implementation will * use to make API calls. */ public IdentityManagementImpl(AmazonIdentityManagement client) { ServiceModel model = V1ModelLoader.load(IdentityManagement.class, IdentityManagement.class.getAnnotation(V1ServiceInterface.class).model()); this.service = new ServiceImpl<AmazonIdentityManagement>(model, client); }
@Test public void getObject_instanceWithTagsConfiguredWithCustomResourceResolverAndCustomRegion_mapWithTagsReturned() throws Exception { //Arrange AmazonRDS amazonRds = mock(AmazonRDS.class); ResourceIdResolver resourceIdResolver = mock(ResourceIdResolver.class); AmazonIdentityManagement amazonIdentityManagement = mock(AmazonIdentityManagement.class); AmazonRdsDataSourceUserTagsFactoryBean factoryBean = new AmazonRdsDataSourceUserTagsFactoryBean(amazonRds, "test", amazonIdentityManagement); factoryBean.setResourceIdResolver(resourceIdResolver); factoryBean.setRegion(Region.getRegion(Regions.EU_WEST_1)); when(resourceIdResolver.resolveToPhysicalResourceId("test")).thenReturn("stack-test"); when(amazonIdentityManagement.getUser()).thenReturn(new GetUserResult().withUser(new User("/", "aemruli", "123456789012", "arn:aws:iam::1234567890:user/aemruli", new Date()))); when(amazonRds.listTagsForResource(new ListTagsForResourceRequest().withResourceName("arn:aws:rds:eu-west-1:1234567890:db:stack-test"))).thenReturn(new ListTagsForResourceResult().withTagList( new Tag().withKey("key1").withValue("value1"), new Tag().withKey("key2").withValue("value2") )); //Act factoryBean.afterPropertiesSet(); Map<String, String> userTagMap = factoryBean.getObject(); //Assert assertEquals("value1", userTagMap.get("key1")); assertEquals("value2", userTagMap.get("key2")); }
@Test public void getObject_instanceWithOutTags_emptyMapReturned() throws Exception { //Arrange AmazonRDS amazonRds = mock(AmazonRDS.class); ResourceIdResolver resourceIdResolver = mock(ResourceIdResolver.class); AmazonIdentityManagement amazonIdentityManagement = mock(AmazonIdentityManagement.class); AmazonRdsDataSourceUserTagsFactoryBean factoryBean = new AmazonRdsDataSourceUserTagsFactoryBean(amazonRds, "test", amazonIdentityManagement); factoryBean.setResourceIdResolver(resourceIdResolver); factoryBean.setResourceIdResolver(resourceIdResolver); factoryBean.setRegion(Region.getRegion(Regions.EU_WEST_1)); when(resourceIdResolver.resolveToPhysicalResourceId("test")).thenReturn("stack-test"); when(amazonIdentityManagement.getUser()).thenReturn(new GetUserResult().withUser(new User("/", "aemruli", "123456789012", "arn:aws:iam::1234567890:user/aemruli", new Date()))); when(amazonRds.listTagsForResource(new ListTagsForResourceRequest().withResourceName("arn:aws:rds:eu-west-1:1234567890:db:stack-test"))).thenReturn(new ListTagsForResourceResult()); //Act factoryBean.afterPropertiesSet(); Map<String, String> userTagMap = factoryBean.getObject(); //Assert assertTrue(userTagMap.isEmpty()); }
@Test public void getObject_instanceWithTagsAndNoResourceIdResolverAndDefaultRegion_mapWithTagsReturned() throws Exception { //Arrange AmazonRDS amazonRds = mock(AmazonRDS.class); AmazonIdentityManagement amazonIdentityManagement = mock(AmazonIdentityManagement.class); AmazonRdsDataSourceUserTagsFactoryBean factoryBean = new AmazonRdsDataSourceUserTagsFactoryBean(amazonRds, "test", amazonIdentityManagement); when(amazonIdentityManagement.getUser()).thenReturn(new GetUserResult().withUser(new User("/", "aemruli", "123456789012", "arn:aws:iam::1234567890:user/aemruli", new Date()))); when(amazonRds.listTagsForResource(new ListTagsForResourceRequest().withResourceName("arn:aws:rds:us-west-2:1234567890:db:test"))).thenReturn(new ListTagsForResourceResult().withTagList( new Tag().withKey("key1").withValue("value1"), new Tag().withKey("key2").withValue("value2") )); //Act factoryBean.afterPropertiesSet(); Map<String, String> userTagMap = factoryBean.getObject(); //Assert assertEquals("value1", userTagMap.get("key1")); assertEquals("value2", userTagMap.get("key2")); }
@Test public void parseInternal_userTagsDefined_createsUserTagBeanDefinition() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); beanDefinitionBuilder.setFactoryMethod("mock"); beanDefinitionBuilder.addConstructorArgValue(AmazonRDS.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), beanDefinitionBuilder.getBeanDefinition()); BeanDefinitionBuilder identityBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); identityBuilder.setFactoryMethod("mock"); identityBuilder.addConstructorArgValue(AmazonIdentityManagement.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonIdentityManagement.class.getName()), identityBuilder.getBeanDefinition()); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-userTags.xml", getClass())); AmazonRDS client = beanFactory.getBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), AmazonRDS.class); AmazonIdentityManagement amazonIdentityManagement = beanFactory.getBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonIdentityManagement.class.getName()), AmazonIdentityManagement.class); when(amazonIdentityManagement.getUser()).thenReturn(new GetUserResult().withUser(new User("/", "aemruli", "123456789012", "arn:aws:iam::1234567890:user/aemruli", new Date()))); when(client.listTagsForResource(new ListTagsForResourceRequest().withResourceName("arn:aws:rds:us-west-2:1234567890:db:test"))).thenReturn(new ListTagsForResourceResult().withTagList( new Tag().withKey("key1").withValue("value2") )); //Act Map<?, ?> dsTags = beanFactory.getBean("dsTags", Map.class); //Assert assertEquals("value2", dsTags.get("key1")); }
@Autowired public Iam(AmazonIdentityManagement iam, BucketGroupPolicy bucketGroupPolicy, @Value("${GROUP_PATH:/cloud-foundry/s3/}") String groupPath, @Value("${GROUP_NAME_PREFIX:cloud-foundry-s3-}") String groupNamePrefix, @Value("${POLICY_NAME_PREFIX:cloud-foundry-s3-}") String policyNamePrefix, @Value("${USER_PATH:/cloud-foundry/s3/}") String userPath, @Value("${USER_NAME_PREFIX:cloud-foundry-s3-}") String userNamePrefix) { this.iam = iam; this.bucketGroupPolicy = bucketGroupPolicy; this.groupPath = groupPath; this.groupNamePrefix = groupNamePrefix; this.policyNamePrefix = policyNamePrefix; this.userPath = userPath; this.userNamePrefix = userNamePrefix; }
@Autowired public BasicPlanIam(AmazonIdentityManagement iam, BucketGroupPolicy bucketGroupPolicy, @Value("${GROUP_PATH:/cloud-foundry/s3/}") String groupPath, @Value("${GROUP_NAME_PREFIX:cloud-foundry-s3-}") String groupNamePrefix, @Value("${POLICY_NAME_PREFIX:cloud-foundry-s3-}") String policyNamePrefix, @Value("${USER_PATH:/cloud-foundry/s3/}") String userPath, @Value("${USER_NAME_PREFIX:cloud-foundry-s3-}") String userNamePrefix) { super(iam, bucketGroupPolicy, groupPath, groupNamePrefix, policyNamePrefix, userPath, userNamePrefix); }
private boolean checkIamOrS3Access(AmazonIdentityManagement client, AttachedPolicy attachedPolicy) { GetPolicyRequest getRolePolicyRequest = new GetPolicyRequest(); getRolePolicyRequest.setPolicyArn(attachedPolicy.getPolicyArn()); GetPolicyResult policy = client.getPolicy(getRolePolicyRequest); if (policy.getPolicy().getArn().toLowerCase().contains("iam")) { LOGGER.info("Role has policy for iam resources: {}.", policy.getPolicy().getArn()); return true; } return false; }
@Override public CloudAccessConfigs accessConfigs(CloudCredential cloudCredential, Region region, Map<String, String> filters) throws Exception { String queryFailedMessage = "Could not get instance profile roles from Amazon: "; CloudAccessConfigs cloudAccessConfigs = new CloudAccessConfigs(new HashSet<>()); AwsCredentialView awsCredentialView = new AwsCredentialView(cloudCredential); AmazonIdentityManagement client = awsClient.createAmazonIdentityManagement(awsCredentialView); try { ListInstanceProfilesResult listRolesResult = client.listInstanceProfiles(); for (InstanceProfile instanceProfile : listRolesResult.getInstanceProfiles()) { Map<String, Object> properties = new HashMap<>(); properties.put("arn", instanceProfile.getArn()); properties.put("creationDate", instanceProfile.getCreateDate().toString()); if (!instanceProfile.getRoles().isEmpty()) { String roleName = instanceProfile.getRoles().get(0).getArn(); properties.put("roleArn", Strings.isNullOrEmpty(roleName) ? instanceProfile.getArn() : roleName); } cloudAccessConfigs.getCloudAccessConfigs().add( new CloudAccessConfig( instanceProfile.getInstanceProfileName(), instanceProfile.getInstanceProfileId(), properties)); } } catch (AmazonServiceException ase) { if (ase.getStatusCode() == UNAUTHORIZED) { String policyMessage = "Could not get instance profile roles because the user does not have enough permission."; LOGGER.info(policyMessage + ase); throw new CloudConnectorException(policyMessage, ase); } else { LOGGER.error(queryFailedMessage, ase); throw new CloudConnectorException(queryFailedMessage + ase.getMessage(), ase); } } catch (Exception e) { LOGGER.error(queryFailedMessage, e); throw new CloudConnectorException(queryFailedMessage + e.getMessage(), e); } return cloudAccessConfigs; }
private static void setup(AmazonS3 storage, AmazonSQS queue, AmazonEC2 machines, AmazonIdentityManagement identityManagement) throws IOException { S3Utils.checkCreateBucket(storage, CODE_MYPROJECT_COM); // Moved in local machine running code to avoid permission denied on EC2 machines SQSUtils.checkCreateQueues(queue, INPUT_QUEUE, REPORT_QUEUE); S3Utils.upload(storage, new FileInputStream("./target/" + JAR_FILE), CODE_MYPROJECT_COM, JAR_FILE, "application/java-archive", CannedAccessControlList.Private); String profileArn = IamUtils.setupRunnerSecurity(identityManagement, CODE_MYPROJECT_COM, SQSUtils.getQueueArn(queue, INPUT_QUEUE), SQSUtils.getQueueArn(queue, REPORT_QUEUE)); Ec2Utils.run(machines, "./shell/startupScript.sh", NUMBER_OF_MACHINES, profileArn); }
private AmazonIdentityManagement findClient(String accessKeyId, String secretAccessKey) { // TODO: need to config client config parameter. ignore it for now. AWSCredentials credential = new BasicAWSCredentials(accessKeyId, secretAccessKey); AmazonIdentityManagement iam = new AmazonIdentityManagementClient(credential); // iam.setEndpoint(Region.toIamEndpoint()); return iam; }