com.amazonaws.services.identitymanagement.model.AccessKeyMetadata Java Examples

The following examples show how to use com.amazonaws.services.identitymanagement.model.AccessKeyMetadata. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AccessKeyRotatedRule.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * This utility method is for calculating the duration between last rotation and current date
 * Returns true, if rotation exceeds 90 days. 
 * Returns false otherwise.
 * 
 * @param accessKeyMetadatas
 * @return boolean
 */
private boolean anyAccessKeysNotRotatedForLong(List<AccessKeyMetadata> accessKeyMetadatas) {
	Boolean keyNotRotated = Boolean.FALSE;
   	for(AccessKeyMetadata accessKeyMetadata : accessKeyMetadatas){
   		//Skip the inactive keys
   		if(accessKeyMetadata.getStatus().equals(StatusType.Inactive.toString())){ 
   			continue;
   		}
   		
   		Date keyCreationDate = accessKeyMetadata.getCreateDate();
   		DateTime creationDate = new DateTime(keyCreationDate);
   		DateTime currentDate = new DateTime();
   		if(Days.daysBetween(creationDate, currentDate).getDays() > PacmanRuleConstants.ACCESSKEY_ROTATION_DURATION){
   			keyNotRotated = Boolean.TRUE;
   		}
	}
	return keyNotRotated;
}
 
Example #2
Source File: IAMUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * This method will fetch the access key information of a particular user.
 * 
 * @param userName
 * @param iamClient
 * @return list of access key meta data
 */
public static List<AccessKeyMetadata> getAccessKeyInformationForUser(
        final String userName, AmazonIdentityManagementClient iamClient) {
    ListAccessKeysRequest accessKeysRequest = new ListAccessKeysRequest();
    accessKeysRequest.setUserName(userName);
    logger.debug("userName {} ",userName);
    List<AccessKeyMetadata> accessKeyMetadatas = new ArrayList<>();
    ListAccessKeysResult keysResult = null;
    do {
        keysResult = iamClient.listAccessKeys(accessKeysRequest);
        accessKeyMetadatas.addAll(keysResult.getAccessKeyMetadata());
        accessKeysRequest.setMarker(keysResult.getMarker());
    } while (keysResult.isTruncated());

    return accessKeyMetadatas;
}
 
Example #3
Source File: AwsIamAccountWithPermanentAccessKeysRule.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getAccessMap(
        List<AccessKeyMetadata> accessKeyMetadatas, String userId) {
    Map<String, String> accessMap = new HashMap<>();
    for (AccessKeyMetadata keyMetadata : accessKeyMetadatas) {
        if (keyMetadata.getAccessKeyId() != null) {
            accessMap.put(keyMetadata.getAccessKeyId(), userId);
        }
    }
    return accessMap;
}
 
Example #4
Source File: AccessKeyMetadataVH.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new access key metadata VH.
 *
 * @param access the access
 */
public AccessKeyMetadataVH(AccessKeyMetadata access){
	this.setAccessKeyId(access.getAccessKeyId());
	this.setCreateDate(access.getCreateDate());
	this.setUserName(access.getUserName());
	this.setStatus(access.getStatus());
}
 
Example #5
Source File: ListAccessKeys.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
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;
            }
        }
    }
 
Example #6
Source File: KeyRotationJobTest.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@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()))));
}
 
Example #7
Source File: KeyRotationViolationWriter.java    From fullstop with Apache License 2.0 5 votes vote down vote up
void writeViolation(final String accountId, final AccessKeyMetadata accessKey) {
    log.info("Found user {} with expired access key {} in account {}", accessKey.getUserName(), accessKey.getAccessKeyId(), accountId);
    violationSink.put(
            new ViolationBuilder()
                    .withAccountId(accountId)
                    .withRegion(NoPasswordViolationWriter.NO_REGION)
                    .withEventId("check-access-key_" + accessKey.getAccessKeyId())
                    .withType(ACTIVE_KEY_TOO_OLD)
                    .withPluginFullyQualifiedClassName(KeyRotationJob.class)
                    .withMetaInfo(metaMap(accessKey))
                    .build());
}
 
Example #8
Source File: KeyRotationViolationWriter.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private Map<?, ?> metaMap(final AccessKeyMetadata accessKey) {
    return ImmutableMap.builder()
            .put("access_key_id", accessKey.getAccessKeyId())
            .put("user_name", accessKey.getUserName())
            .put("access_key_created", accessKey.getCreateDate())
            .build();
}
 
Example #9
Source File: Handler.java    From billow with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(String target,
                   Request baseRequest,
                   HttpServletRequest request,
                   HttpServletResponse response) {
    try {
        final Map<String, String[]> paramMap = request.getParameterMap();

        final AWSDatabase current = dbHolder.getCurrent();

        final long age = current.getAgeInMs();
        final float ageInSeconds = (float) age / 1000.0f;
        response.setHeader("Age", String.format("%.3f", ageInSeconds));
        response.setHeader("Cache-Control", String.format("public, max-age=%d", dbHolder.getCacheTimeInMs() / 1000));

        switch (target) {
            case "/ec2":
                handleComplexEC2(response, paramMap, current);
                break;
            case "/rds":
                handleComplexRDS(response, paramMap, current);
                break;
            case "/ec2/all":
                handleSimpleRequest(response, current.getEc2Instances());
                break;
            case "/rds/all":
                handleSimpleRequest(response, current.getRdsInstances());
                break;
            case "/ec2/sg":
                handleSimpleRequest(response, current.getEc2SGs());
                break;
            case "/elasticsearch":
                handleSimpleRequest(response, current.getElasticsearchClusters());
                break;
            case "/iam": // backwards compatibility with documented feature
                final ArrayList<AccessKeyMetadata> justKeys = Lists.<AccessKeyMetadata>newArrayList();
                for (IAMUserWithKeys userWithKeys : current.getIamUsers())
                    justKeys.addAll(userWithKeys.getKeys());
                handleSimpleRequest(response, justKeys);
                break;
            case "/iam/users":
                handleSimpleRequest(response, current.getIamUsers());
                break;
            case "/dynamo":
                handleComplexDynamo(response, paramMap, current);
                break;
            case "/sqs":
                handleComplexSQS(response, paramMap, current);
                break;
            case "/elasticache/cluster":
                handleComplexElasticacheCluster(response, paramMap, current);
                break;
            default:
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    } finally {
        baseRequest.setHandled(true);
    }
}
 
Example #10
Source File: KeyRotationJobTest.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private AccessKeyMetadata active(final AccessKeyMetadata accessKeyMetadata) {
    accessKeyMetadata.setStatus("Active");
    return accessKeyMetadata;
}
 
Example #11
Source File: KeyRotationJobTest.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private AccessKeyMetadata inactive(final AccessKeyMetadata accessKeyMetadata) {
    accessKeyMetadata.setStatus("Inactive");
    return accessKeyMetadata;
}
 
Example #12
Source File: KeyRotationJobTest.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private AccessKeyMetadata upToDate(final AccessKeyMetadata accessKeyMetadata) {
    accessKeyMetadata.setCreateDate(new Date());
    return accessKeyMetadata;
}
 
Example #13
Source File: KeyRotationJobTest.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private AccessKeyMetadata expired(final AccessKeyMetadata accessKeyMetadata) {
    accessKeyMetadata.setCreateDate(now().minusDays(31).toDate());
    return accessKeyMetadata;
}
 
Example #14
Source File: AccessKeyMetadataPredicates.java    From fullstop with Apache License 2.0 4 votes vote down vote up
static Predicate<AccessKeyMetadata> isActiveAndOlderThanDays(final int days) {
    return IS_ACTIVE.and(withDaysOlderThan(days));
}
 
Example #15
Source File: AccessKeyMetadataPredicates.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private static Predicate<AccessKeyMetadata> withDaysOlderThan(final int days) {
    return t -> (t.getCreateDate().getTime() < LocalDate.now().minusDays(days).toDate().getTime());
}
 
Example #16
Source File: AccessKeyMetadataPredicates.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private static Predicate<AccessKeyMetadata> activity(final String value) {
    return t -> value.equals(t.getStatus());
}
 
Example #17
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Fetch IAM users test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchIAMUsersTest() throws Exception {
    
    mockStatic(AmazonIdentityManagementClientBuilder.class);
    AmazonIdentityManagement iamClient = PowerMockito.mock(AmazonIdentityManagement.class);
    AmazonIdentityManagementClientBuilder amazonIdentityManagementClientBuilder = PowerMockito.mock(AmazonIdentityManagementClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonIdentityManagementClientBuilder.standard()).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.withCredentials(anyObject())).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.withRegion(anyString())).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.build()).thenReturn(iamClient);
    
    ListUsersResult listUsersResult = new ListUsersResult();
    List<User> users = new ArrayList<>();
    User user = new User();
    user.setUserName("name");
    users.add(user);
    listUsersResult.setUsers(users);
    when(iamClient.listUsers(anyObject())).thenReturn(listUsersResult);
    
    ListAccessKeysResult listAccessKeysResult = new ListAccessKeysResult();
    List<AccessKeyMetadata> accessKeyMetadataList = new ArrayList<>();
    AccessKeyMetadata accessKeyMetadata = new AccessKeyMetadata();
    accessKeyMetadata.setAccessKeyId("accessKeyId");
    accessKeyMetadataList.add(accessKeyMetadata);
    listAccessKeysResult.setAccessKeyMetadata(accessKeyMetadataList );
    when(iamClient.listAccessKeys(anyObject())).thenReturn(listAccessKeysResult);
    
    GetAccessKeyLastUsedResult getAccessKeyLastUsedResult = new GetAccessKeyLastUsedResult();
    AccessKeyLastUsed accessKeyLastUsed = new AccessKeyLastUsed();
    accessKeyLastUsed.setLastUsedDate(new Date());
    getAccessKeyLastUsedResult.setAccessKeyLastUsed(accessKeyLastUsed );
    when(iamClient.getAccessKeyLastUsed(anyObject())).thenReturn(getAccessKeyLastUsedResult);
    
    GetLoginProfileResult getLoginProfileResult = new GetLoginProfileResult();
    LoginProfile loginProfile = new LoginProfile();
    loginProfile.setCreateDate(new Date());
    loginProfile.setPasswordResetRequired(false);
    getLoginProfileResult.setLoginProfile(loginProfile );
    when(iamClient.getLoginProfile(anyObject())).thenReturn(getLoginProfileResult );
    
    ListGroupsForUserResult listGroupsForUserResult = new ListGroupsForUserResult();
    List<Group> groups = new ArrayList<>();
    Group group = new Group();
    group.setGroupName("groupName");
    groups.add(group);
    listGroupsForUserResult.setGroups(groups );
    when(iamClient.listGroupsForUser(anyObject())).thenReturn(listGroupsForUserResult );
    
    ListMFADevicesResult listMFADevicesResult = new ListMFADevicesResult();
    listMFADevicesResult.setMFADevices(new ArrayList<>());;
    when(iamClient.listMFADevices(anyObject())).thenReturn(listMFADevicesResult );
    
    assertThat(inventoryUtil.fetchIAMUsers(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"),
            "account","accountName").size(), is(1));
    
    listMFADevicesResult = new ListMFADevicesResult();
    List<MFADevice> mfaDevices = new ArrayList<>();
    mfaDevices.add(new MFADevice());
    listMFADevicesResult.setMFADevices(mfaDevices);
    when(iamClient.listMFADevices(anyObject())).thenReturn(listMFADevicesResult );
    
    assertThat(inventoryUtil.fetchIAMUsers(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"),
            "account","accountName").size(), is(1));
}
 
Example #18
Source File: AccessKeyRotatedRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Test
public void test()throws Exception{
    Date date = new Date(); // Or where ever you get it from
    Date daysAgo = new DateTime(date).minusDays(300).toDate();
    AccessKeyMetadata accessKeyMetadata = new AccessKeyMetadata();
    accessKeyMetadata.setAccessKeyId("123");
    accessKeyMetadata.setCreateDate(daysAgo);
    accessKeyMetadata.setStatus("Active");
   
    List<AccessKeyMetadata> accessKeyMetadatas  = new ArrayList<>();
    accessKeyMetadatas.add(accessKeyMetadata);

    AccessKeyMetadata accessKeyMetadataTest = new AccessKeyMetadata();
    accessKeyMetadataTest.setAccessKeyId("123");
    accessKeyMetadataTest.setCreateDate(new Date());
    accessKeyMetadataTest.setStatus("Inactive");
   
    List<AccessKeyMetadata> accessKeyMetadatasTest  = new ArrayList<>();
    accessKeyMetadatasTest.add(accessKeyMetadataTest);
    
    List<AccessKeyMetadata> emptyAccessKeyMetadatas  = new ArrayList<>();
    
    mockStatic(PacmanUtils.class);
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString())).thenReturn(
            true);
    
    
   
    
    Map<String,Object>map=new HashMap<String, Object>();
    map.put("client", identityManagementClient);
    AccessKeyRotatedRule spy = Mockito.spy(new AccessKeyRotatedRule());
    
    Mockito.doReturn(map).when((BaseRule)spy).getClientFor(anyObject(), anyString(), anyObject());
    
    mockStatic(IAMUtils.class);
    when(IAMUtils.getAccessKeyInformationForUser(anyString(),anyObject())).thenReturn(accessKeyMetadatas);
    spy.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "));
    
    
    when(IAMUtils.getAccessKeyInformationForUser(anyString(),anyObject())).thenReturn(accessKeyMetadatasTest);
    spy.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "));
    
    when(IAMUtils.getAccessKeyInformationForUser(anyString(),anyObject())).thenReturn(emptyAccessKeyMetadatas);
    spy.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "));
    
    
    assertThatThrownBy( 
            () -> accessKeyRotatedRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
    
    
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString())).thenReturn(
            false);
    assertThatThrownBy(
            () -> accessKeyRotatedRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
}
 
Example #19
Source File: AwsIamAccountWithPermanentAccessKeysRuleTest.java    From pacbot with Apache License 2.0 2 votes vote down vote up
@Test
public void test()throws Exception{
    AccessKeyMetadata accessKeyMetadata = new AccessKeyMetadata();
    accessKeyMetadata.setAccessKeyId("123");
   
    List<AccessKeyMetadata> accessKeyMetadatas  = new ArrayList<>();
    accessKeyMetadatas.add(accessKeyMetadata);
    
    ListAccessKeysResult keysResult  = new ListAccessKeysResult();
    keysResult.setAccessKeyMetadata(accessKeyMetadatas);
    
    

    
    List<AccessKeyMetadata> emptyAccessKeyMetadatas  = new ArrayList<>();
    ListAccessKeysResult emptyKeysResult  = new ListAccessKeysResult();
    
    mockStatic(PacmanUtils.class);
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString())).thenReturn(
            true);
    
    
   
    
    Map<String,Object>map=new HashMap<String, Object>();
    map.put("client", identityManagementClient);
    AwsIamAccountWithPermanentAccessKeysRule spy = Mockito.spy(new AwsIamAccountWithPermanentAccessKeysRule());
    
    Mockito.doReturn(map).when((BaseRule)spy).getClientFor(anyObject(), anyString(), anyObject());
    
    mockStatic(IAMUtils.class);
    when(IAMUtils.getAccessKeyInformationForUser(anyString(),anyObject())).thenReturn(accessKeyMetadatas);
    when(identityManagementClient.listAccessKeys(anyObject())).thenReturn(keysResult);
    spy.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "));
    
    
    when(IAMUtils.getAccessKeyInformationForUser(anyString(),anyObject())).thenReturn(emptyAccessKeyMetadatas);
    when(identityManagementClient.listAccessKeys(anyObject())).thenReturn(emptyKeysResult);
    spy.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "));
    
    
    
    spy.execute(CommonTestUtils.getMapString("svc_123 "),CommonTestUtils.getMapString("svc_123 "));
    when(identityManagementClient.listAccessKeys(anyObject())).thenThrow(new RuleExecutionFailedExeption());
    assertThatThrownBy( 
            () -> awsIamAccountWithPermanentAccessKeysRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
    
    
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString())).thenReturn(
            false);
    assertThatThrownBy(
            () -> awsIamAccountWithPermanentAccessKeysRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
}