/** * * @param allMFANotEnabledUsers * @return List<Evaluation> returns list of Evaluation objects. */ private List<Evaluation> createEvaluations(List<User> allMFANotEnabledUsers) { List<Evaluation> evaluations = new ArrayList<>(); if ( allMFANotEnabledUsers == null || allMFANotEnabledUsers.size() > 0 ) { for(User user: allMFANotEnabledUsers) { String userName = user.getUserName(); Evaluation evaluation = new Evaluation(); evaluation.setComplianceResourceId(userName); evaluation.setComplianceResourceType(COMPLIANCE_RESOURCE_TYPE); evaluation.setComplianceType(ComplianceType.NON_COMPLIANT); evaluation.setOrderingTimestamp(new Date()); evaluations.add(evaluation); } } System.out.println("INFO : Number of evaluations : " + evaluations.size()); return evaluations; }
/** * Returns all Iam users for whom MFA is not enabled. * @param allIamUsers * @return List<User> :- return all Iam users whose MFA is not enabled. */ public List<User> getAllMFANotEnabledUsers(List<User> allIamUsers) { List<User> allMFANotEnabledUsers = new ArrayList<>(); if ( allIamUsers != null || allIamUsers.size() > 0 ) { for ( User user: allIamUsers) { if (! isMFAEnabled(user)) { allMFANotEnabledUsers.add(user); } } } System.out.println("INFO : Number of MFA Not Enabled Users : " + allMFANotEnabledUsers.size()); System.out.println("INFO : All MFA Not Enabled Users : " + allMFANotEnabledUsers); return allMFANotEnabledUsers; }
/** * Checks if user MFA is enabled or not. * @param user * @return returns true, if MFA is enabled for the user. */ public Boolean isMFAEnabled(User user) throws AmazonClientException { Boolean mfaDeviceEnabled = false; try { if ( user != null ) { ListMFADevicesRequest listMFADevicesRequest = new ListMFADevicesRequest(user.getUserName()); ListMFADevicesResult listMFADevicesResult = this.iamClient.listMFADevices(listMFADevicesRequest); if ( listMFADevicesResult.getMFADevices().size() > 0) { mfaDeviceEnabled = true; } } }catch(AmazonClientException e) { System.out.println("ERROR : Fetching list of MFA Devices."); e.printStackTrace(); throw e; } //System.out.println("INFO : MFA enabled for the user? " + mfaDeviceEnabled); return mfaDeviceEnabled; }
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 ServiceInstanceBinding createServiceInstanceBinding(String bindingId, ServiceInstance serviceInstance, String serviceId, String planId, String appGuid) { User user = iam.createUserForBinding(bindingId); AccessKey accessKey = iam.createAccessKey(user); // TODO create password and add to credentials iam.addUserToGroup(user, iam.getGroupNameForInstance(serviceInstance.getId())); String bucketName = s3.getBucketNameForInstance(serviceInstance.getId()); Map<String, Object> credentials = new HashMap<String, Object>(); credentials.put("bucket", bucketName); credentials.put("username", user.getUserName()); credentials.put("access_key_id", accessKey.getAccessKeyId()); credentials.put("secret_access_key", accessKey.getSecretAccessKey()); credentials.put("host", AMAZON_S3_HOST); credentials.put("uri", this.generateUri(accessKey.getAccessKeyId(), accessKey.getSecretAccessKey(), bucketName)); return new ServiceInstanceBinding(bindingId, serviceInstance.getId(), credentials, null, appGuid); }
@Before public void beforeEachTestRuns() { monitor = createMock(MonitorStackEvents.class); cfnRepository = createMock(CloudFormRepository.class); vpcRepository = createMock(VpcRepository.class); ELBRepository elbRepository = createMock(ELBRepository.class); cloudRepository = createStrictMock(CloudRepository.class); notificationSender = createStrictMock(NotificationSender.class); identityProvider = createStrictMock(IdentityProvider.class); user = new User("path", "userName", "userId", "arn", new Date()); aws = new AwsFacade(monitor, cfnRepository, vpcRepository, elbRepository, cloudRepository, notificationSender, identityProvider); }
/** * This method returns all Iam users. * @return List<User> returns all Iam users. * @throws AmazonClientException */ public List<User> getAllIamUsers() throws AmazonClientException { String marker = null; List<User> allIamUsers = new ArrayList<>(); try { // Fetch all iam users. while(true) { ListUsersRequest listUsersRequest = new ListUsersRequest(); listUsersRequest.setMarker(marker); ListUsersResult listUsersResult = this.iamClient.listUsers(listUsersRequest); allIamUsers.addAll(listUsersResult.getUsers()); // Check the listUsersResult is truncated. This method returns users in batches of 100. if ( listUsersResult.isTruncated() ) { marker = listUsersResult.getMarker(); } else { break; } } } catch(AmazonClientException e) { System.out.println("ERROR : fetching all iam users"); e.printStackTrace(); throw e; } List<String> allIamUsersName = allIamUsers.stream().map(e -> e.getUserName()).collect(Collectors.toList()); System.out.println("INFO : Number of Iam users : " + allIamUsers.size()); System.out.println("INFO : Iam users : " + allIamUsersName); return allIamUsers; }
@Test public void testGetAllIamUsers() { IamUtilsImpl iamUtilsImpl = mock(IamUtilsImpl.class); when(iamUtilsImpl.getAllIamUsers()).thenReturn(allIamUsers); List<User> output = iamUtilsImpl.getAllIamUsers(); assertEquals(3, output.size()); }
@Test public void testGetAllMFANotEnabledUsers() { // Not sure how to test this method. 'getAllMFANotEnabledUsers' method calls 'isMFAEnabled', // which inturn uses AWS api. So mocking below. IamUtilsImpl iamUtilsImpl = mock(IamUtilsImpl.class); when(iamUtilsImpl.getAllMFANotEnabledUsers(allIamUsers)).thenReturn(Arrays.asList(user3)); List<User> allMFANotEnabledUsers = iamUtilsImpl.getAllMFANotEnabledUsers(allIamUsers); assertEquals(1,allMFANotEnabledUsers.size()); }
@Before public void setUp() { mockIAMDataSource = mock(IdentityManagementDataSource.class); mockViolationWriter = mock(KeyRotationViolationWriter.class); mockAccountIdSupplier = mock(AccountIdSupplier.class); when(mockAccountIdSupplier.get()).thenReturn(newHashSet("account01", "account02")); when(mockIAMDataSource.getUsers(eq("account01"))).thenReturn(singletonList(new User())); when(mockIAMDataSource.getUsers(eq("account02"))).thenReturn(asList(new User(), new User())); when(mockIAMDataSource.getAccessKeys(eq("account01"), any())).thenReturn(asList( upToDate(active(new AccessKeyMetadata())), expired(active(new AccessKeyMetadata())), expired(inactive(new AccessKeyMetadata())))); when(mockIAMDataSource.getAccessKeys(eq("account02"), any())).thenReturn(singletonList(upToDate(inactive(new AccessKeyMetadata())))); }
@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")); }
public List<AbstractResource<?>> toIamUsers(List<User> users, String accountId, DateTime dt) { List<AbstractResource<?>> resources = new ArrayList<>(); for (User user : users) { IamUser iamUser = new IamUser(); conf(iamUser, accountId, dt); iamUser.setResource(user); resources.add(iamUser); } log.debug("{} users found via api and converted to IamUser", resources.size()); return resources; }
public CFNAssistNotification(String stackName, String stackStatus, User user) { this.stackName = stackName; this.stackStatus = stackStatus; if (user!=null) { this.userId = user.getUserId(); this.setUserName(user.getUserName()); } }
public User getUserId() { logger.debug("Get current user"); try { GetUserResult result = iamClient.getUser(); User user = result.getUser(); logger.info("Fetched current user: " + user); return user; } catch(AmazonServiceException exception) { logger.warn("Unable to fetch current user: " + exception.toString()); return null; } }
@Before public void beforeEachTestRuns() { monitor = createMock(MonitorStackEvents.class); cfnRepository = createMock(CloudFormRepository.class); VpcRepository vpcRepository = createMock(VpcRepository.class); elbRepository = createMock(ELBRepository.class); CloudRepository cloudRepository = createStrictMock(CloudRepository.class); notificationSender = createStrictMock(NotificationSender.class); identityProvider = createStrictMock(IdentityProvider.class); user = new User("path", "userName", "userId", "arn", new Date()); aws = new AwsFacade(monitor, cfnRepository, vpcRepository, elbRepository, cloudRepository, notificationSender, identityProvider); }
@Before public void beforeEachTestRuns() throws IOException { monitor = createMock(MonitorStackEvents.class); cfnRepository = createMock(CloudFormRepository.class); vpcRepository = createStrictMock(VpcRepository.class); ELBRepository elbRepository = createMock(ELBRepository.class); cloudRepository = createStrictMock(CloudRepository.class); notificationSender = createStrictMock(NotificationSender.class); identityProvider = createStrictMock(IdentityProvider.class); user = new User("path", "userName", "userId", "arn", new Date()); aws = new AwsFacade(monitor, cfnRepository, vpcRepository, elbRepository, cloudRepository, notificationSender, identityProvider); deleteFile(THIRD_FILE); }
public void doHandle(ConfigEvent event,Context context, AmazonConfig awsConfig, IamUtilsImpl iamUtilsImpl) throws IOException { // Fetch invoking event. JsonNode invokingEvent = new ObjectMapper().readTree(event.getInvokingEvent()); // Check if invoking event is of type ScheduleNotification or not. checkForInCompatibleTypes(invokingEvent); // Fetch all Iam Users. List<User> allIamUsers = iamUtilsImpl.getAllIamUsers(); // Fetch all MFA Not enabled Users. List<User> allMFANotEnabledUsers = iamUtilsImpl.getAllMFANotEnabledUsers(allIamUsers); List<Evaluation> evaluations = createEvaluations(allMFANotEnabledUsers); doPutEvaluations(awsConfig,event,evaluations); }
@Test public void parseInternal_customRdsInstance_createsRdsBeanAndUserTagsWithCustomRdsInstance() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-customRdsInstance.xml", getClass())); AmazonRDS clientMock = beanFactory.getBean("amazonRds", AmazonRDS.class); when(clientMock.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("test"). withDBInstanceIdentifier("test"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ).withReadReplicaDBInstanceIdentifiers("read1") ) ); AmazonIdentityManagement amazonIdentityManagement = beanFactory.getBean("myIdentityService", AmazonIdentityManagement.class); when(amazonIdentityManagement.getUser()).thenReturn(new GetUserResult().withUser(new User("/", "aemruli", "123456789012", "arn:aws:iam::1234567890:user/aemruli", new Date()))); when(clientMock.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); DataSource dataSource = beanFactory.getBean(DataSource.class); //Assert assertEquals("value2", dsTags.get("key1")); assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); }
public User createUserForBinding(String bindingId) { String userName = getUserNameForBinding(bindingId); logger.info("Creating user '{}' for service binding '{}'", userName, bindingId); return createUser(userName); }
private void sendNotification(String stackName, String status) throws CfnAssistException { User userId = identityProvider.getUserId(); notificationSender.sendNotification(new CFNAssistNotification(stackName, status, userId)); }
@Test public void shouldSendNotificationMessageOnTopic() throws CfnAssistException, MissingArgumentException, InterruptedException, IOException { User user = new User("path", "userName", "userId", "userArn", new Date()); CFNAssistNotification notification = new CFNAssistNotification("name", "complete", user); CreateTopicResult createResult = snsClient.createTopic(SNSNotificationSender.TOPIC_NAME); String SNSarn = createResult.getTopicArn(); assertNotNull(SNSarn); // test the SNS notification by creating a SQS and subscribing that to the SNS CreateQueueResult queueResult = createQueue(); String queueUrl = queueResult.getQueueUrl(); // give queue perms to subscribe to SNS Map<String, String> attribrutes = policyManager.getQueueAttributes(queueUrl); String queueArn = attribrutes.get(QueuePolicyManager.QUEUE_ARN_KEY); policyManager.checkOrCreateQueuePermissions(attribrutes, SNSarn, queueArn, queueUrl); // create subscription SubscribeRequest subscribeRequest = new SubscribeRequest(SNSarn, SNSEventSource.SQS_PROTO, queueArn); SubscribeResult subResult = snsClient.subscribe(subscribeRequest); String subscriptionArn = subResult.getSubscriptionArn(); // send SNS and then check right thing arrives at SQS sender.sendNotification(notification); ReceiveMessageRequest request = new ReceiveMessageRequest(). withQueueUrl(queueUrl). withWaitTimeSeconds(10); ReceiveMessageResult receiveResult = sqsClient.receiveMessage(request); List<Message> messages = receiveResult.getMessages(); sqsClient.deleteQueue(queueUrl); snsClient.unsubscribe(subscriptionArn); snsClient.deleteTopic(SNSarn); assertEquals(1, messages.size()); Message msg = messages.get(0); ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(msg.getBody()); JsonNode messageNode = rootNode.get("Message"); String json = messageNode.textValue(); CFNAssistNotification result = CFNAssistNotification.fromJSON(json); assertEquals(notification, result); }
@Test public void shouldGetUserId() { User result = identityProvider.getUserId(); assertNotNull(result); assertFalse(result.getUserName().isEmpty()); }
@Before public void beforeEachTestRuns() { user = new User("path", "userName", "userId", "userArn", new Date()); }
public List<User> getAllIamUsers() throws AmazonClientException;
public List<User> getAllMFANotEnabledUsers(List<User> allIamUsers);
public Boolean isMFAEnabled(User user) throws AmazonClientException;