com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient Java Examples

The following examples show how to use com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient. 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: 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 #2
Source File: CrossAccountPolicyForIAMJobTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.violationSinkMock = mock(ViolationSink.class);
    this.clientProviderMock = mock(ClientProvider.class);
    this.accountIdSupplierMock = mock(AccountIdSupplier.class);
    this.jobsPropertiesMock = mock(JobsProperties.class);
    this.mockAmazonIdentityManagementClient = mock(AmazonIdentityManagementClient.class);
    this.mockAwsApplications = mock(AwsApplications.class);

    mockListRolesResult = new ListRolesResult();
    mockListRolesResult.setRoles(asList(
            createRole("aws-service-role", AWS_SERVICE_POLICY_DOCUMENT),
            createRole("cross-account-role", CROSS_ACCOUNT_POLICY_DOCUMENT),
            createRole("same-account-role", SAME_ACCOUNT_POLICY_DOCUMENT),
            createRole("deleted-role-reference-role", DELETED_ROLE_POLICY_DOCUMENT),
            createRole("management-account-role", MANAGEMENT_POLICY_DOCUMENT)));

    when(clientProviderMock.getClient(any(), any(String.class), any(Region.class))).thenReturn(mockAmazonIdentityManagementClient);
}
 
Example #3
Source File: IdentityManagementDataSource.java    From fullstop with Apache License 2.0 6 votes vote down vote up
GetCredentialReportResult getCredentialReportCSV(final String accountId) {
    final AmazonIdentityManagementClient client = getIAMClient(accountId);

    GenerateCredentialReportResult generationReport;
    int i = 0;
    do {
        Assert.state(i < MAX_RETRIES, "Maximum retries to generate credentials report exceeded");
        log.debug("Poll credentials report for account {}", accountId);
        try {
            MILLISECONDS.sleep(RETRY_TIMEOUT_MILLIS * i);
        } catch (final InterruptedException e) {
            throw new RuntimeException("Could not pull credentials report", e);
        }
        generationReport = client.generateCredentialReport();
        i++;

    } while (!COMPLETE.toString().equals(generationReport.getState()));

    return client.getCredentialReport();
}
 
Example #4
Source File: SetUpOpsWorksTestsTask.java    From aws-ant-tasks with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the "instanceProfile" and "serviceRole" properties according to the
 * set parameters.
 */
public void execute() {
    checkParams();
    AmazonIdentityManagementClient iamClient = getOrCreateClient(AmazonIdentityManagementClient.class);
    getProject()
            .setProperty(
                    "instanceProfileArn",
                    iamClient
                            .getInstanceProfile(
                                    new GetInstanceProfileRequest()
                                            .withInstanceProfileName(instanceProfile))
                            .getInstanceProfile().getArn());
    getProject()
            .setProperty(
                    "serviceRoleArn",
                    iamClient
                            .getRole(
                                    new GetRoleRequest()
                                            .withRoleName(serviceRole))
                            .getRole().getArn());

}
 
Example #5
Source File: Configuration.java    From reinvent2013-mobile-photo-share with Apache License 2.0 6 votes vote down vote up
private static String getAWSAccountID() {
    try {
        String accessKey = AWS_ACCESS_KEY_ID;
        String secretKey = AWS_SECRET_KEY;

        if (Utilities.isEmpty(accessKey) || Utilities.isEmpty(secretKey)) {
            return null;
        }

        AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
        AmazonIdentityManagementClient iam = new AmazonIdentityManagementClient(creds);
        return iam.getUser().getUser().getArn().split(":")[4];
    } catch (AmazonClientException e) {
        throw new RuntimeException("Failed to get AWS account id", e);
    }
}
 
Example #6
Source File: LDAPIAMPoller.java    From aws-iam-ldap-bridge with Apache License 2.0 6 votes vote down vote up
private void populateRolesFromIAM() {
    AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials);

    try {
        ListRolesResult res = client.listRoles();
        while (true) {
            for (Role role : res.getRoles()) {
                try {
                    Entry groupEntry = getOrCreateRoleGroup(role);
                    addRole(role, groupEntry);
                    LOG.debug("Added role " + role.getRoleName() + " at " + rolesDN);
                } catch (Throwable e) {
                    LOG.error("Exception processing role " + role.getRoleName(), e);
                }
            }
            if (res.isTruncated()) {
                res = client.listRoles(new ListRolesRequest().withMarker(res.getMarker()));
            } else {
                break;
            }
        }
    } finally {
        client.shutdown();
    }
}
 
Example #7
Source File: IAMUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the inline role policy.
 *
 * @param roleName
 *            the role name
 * @param amazonIdentityManagement
 *            the amazon identity management
 * @param actionSet
 *            the action set
 * @return the inline role policy
 */
private static Set<String> getInlineRolePolicyActionSet(String roleName,
		AmazonIdentityManagementClient amazonIdentityManagement) {
	Set<String> actionSet = new HashSet<>();

	List<String> inlineRolePolicyNameList = new ArrayList<>();
	ListRolePoliciesRequest listRolePoliciesRequest = new ListRolePoliciesRequest();
	listRolePoliciesRequest.setRoleName(roleName);
	ListRolePoliciesResult listRolePoliciesResult = null;
	do {
		listRolePoliciesResult = amazonIdentityManagement.listRolePolicies(listRolePoliciesRequest);
		inlineRolePolicyNameList.addAll(listRolePoliciesResult.getPolicyNames());
		listRolePoliciesRequest.setMarker(listRolePoliciesResult.getMarker());
	} while (listRolePoliciesResult.isTruncated());

	for (String policyName : inlineRolePolicyNameList) {
		Policy policy = getInlineRolePolicy(roleName, policyName, amazonIdentityManagement);
		actionSet.addAll(getActionSet(policy));
	}
	return actionSet;
}
 
Example #8
Source File: IAMUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the inline user policy.
 *
 * @param userName
 *            the user name
 * @param amazonIdentityManagement
 *            the amazon identity management
 * @param actionSet
 *            the action set
 * @return the inline user policy
 */
private static Set<String> getInlineUserPolicyActionSet(String userName,
		AmazonIdentityManagementClient amazonIdentityManagement) {
	Set<String> actionSet = new HashSet<>();

	List<String> inlineUserPolicyNameList = new ArrayList<>();
	ListUserPoliciesRequest listUserPoliciesRequest = new ListUserPoliciesRequest();
	listUserPoliciesRequest.setUserName(userName);
	ListUserPoliciesResult listUserPoliciesResult = null;
	do {
		listUserPoliciesResult = amazonIdentityManagement.listUserPolicies(listUserPoliciesRequest);
		inlineUserPolicyNameList.addAll(listUserPoliciesResult.getPolicyNames());
		listUserPoliciesRequest.setMarker(listUserPoliciesResult.getMarker());
	} while (listUserPoliciesResult.isTruncated());

	for (String policyName : inlineUserPolicyNameList) {
		Policy policy = getInlineUserPolicy(userName, policyName, amazonIdentityManagement);
		actionSet.addAll(getActionSet(policy));
	}
	return actionSet;
}
 
Example #9
Source File: LDAPIAMPoller.java    From aws-iam-ldap-bridge with Apache License 2.0 5 votes vote down vote up
private void populateGroupsFromIAM() {
    AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials);

    try {
        ListGroupsResult res = client.listGroups();
        Set<String> groupNames = new HashSet<String>();
        while (true) {
            for (Group group : res.getGroups()) {
                try {
                    addGroup(group);
                    groupNames.add(group.getGroupName());
                    LOG.debug("Added group " + group.getGroupName() + " at " + groupsDN);
                } catch (Throwable e) {
                    LOG.error("Exception processing group " + group.getGroupName(), e);
                }
            }
            if (res.isTruncated()) {
                res = client.listGroups(new ListGroupsRequest().withMarker(res.getMarker()));
            } else {
                break;
            }
        }
        removeDeletedGroups(groupNames);
    } finally {
        client.shutdown();
    }
}
 
Example #10
Source File: CleanUpBeanstalkTestsTask.java    From aws-ant-tasks with Apache License 2.0 5 votes vote down vote up
public void execute() {
    AmazonIdentityManagementClient iamClient = getOrCreateClient(AmazonIdentityManagementClient.class);
    iamClient
            .removeRoleFromInstanceProfile(new RemoveRoleFromInstanceProfileRequest()
                    .withRoleName(INSTANCEPROFILE_ROLE)
                    .withInstanceProfileName(instanceProfile));
    iamClient.deleteInstanceProfile(new DeleteInstanceProfileRequest()
            .withInstanceProfileName(instanceProfile));
    AmazonS3Client client = getOrCreateClient(AmazonS3Client.class);

    AWSTestUtils.emptyAndDeleteBucket(client, bucketName);
}
 
Example #11
Source File: SetUpBeanstalkTestsTask.java    From aws-ant-tasks with Apache License 2.0 5 votes vote down vote up
public void execute() {
    AmazonIdentityManagementClient iamClient = getOrCreateClient(AmazonIdentityManagementClient.class);
    iamClient.createInstanceProfile(new CreateInstanceProfileRequest()
            .withInstanceProfileName(instanceProfile));
    iamClient
            .addRoleToInstanceProfile(new AddRoleToInstanceProfileRequest()
                    .withRoleName(INSTANCEPROFILE_ROLE)
                    .withInstanceProfileName(instanceProfile));
}
 
Example #12
Source File: LDAPIAMPoller.java    From aws-iam-ldap-bridge with Apache License 2.0 5 votes vote down vote up
private void populateUsersFromIAM() {
    AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials);

    try {
        ListUsersResult res = client.listUsers();
        Set<String> allUsers = new HashSet<String>();
        while (true) {
            for (User user : res.getUsers()) {
                try {
                    Collection<Group> groups = client.listGroupsForUser(new ListGroupsForUserRequest(user.getUserName())).getGroups();
                    Group primaryGroup = groups.size() > 0 ? groups.iterator().next() : null;
                    if (primaryGroup == null) {
                        LOG.warn("Unable to determine primary group for " + user.getUserName());
                        continue;
                    }
                    Entry groupEntry = getExistingGroup(primaryGroup);
                    if (groupEntry == null) {
                        LOG.warn("Unable to retrieve matching group entry for group " + primaryGroup.getGroupName() + " user " + user.getUserName());
                        continue;
                    }
                    addUser(user, getUserAccessKey(client, user), groupEntry, groups);
                    updateGroups(groups, user);
                    allUsers.add(user.getUserName());
                    LOG.debug("Added user " + user.getUserName());
                } catch (Throwable e) {
                    LOG.error("Exception processing user " + user.getUserName(), e);
                }
            }
            if (res.isTruncated()) {
                res = client.listUsers(new ListUsersRequest().withMarker(res.getMarker()));
            } else {
                break;
            }
        }
        removeDeletedUsers(allUsers);
    } finally {
        client.shutdown();
    }
}
 
Example #13
Source File: AWSClients.java    From aws-codedeploy-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Via the default provider chain (i.e., global keys for this Jenkins instance),  return the account ID for the
 * currently authenticated user.
 * @param proxyHost hostname of the proxy to use (if any)
 * @param proxyPort port of the proxy to use (if any)
 * @return 12-digit account id
 */
public static String getAccountId(String proxyHost, int proxyPort) {

    String arn = "";
    try {
        ClientConfiguration clientCfg = new ClientConfiguration();
        if (proxyHost != null && proxyPort > 0 ) {
            clientCfg.setProxyHost(proxyHost);
            clientCfg.setProxyPort(proxyPort);
        }
        AmazonIdentityManagementClient iam = new AmazonIdentityManagementClient(clientCfg);
        GetUserResult user = iam.getUser();
        arn = user.getUser().getArn();
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().compareTo("AccessDenied") == 0) {
            String msg = e.getMessage();
            int arnIdx = msg.indexOf("arn:aws");
            if (arnIdx != -1) {
                int arnSpace = msg.indexOf(" ", arnIdx);
                arn = msg.substring(arnIdx, arnSpace);
            }
        }
    }

    String accountId = arn.split(":")[ARN_ACCOUNT_ID_INDEX];
    return accountId;
}
 
Example #14
Source File: PolicyProviderImpl.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private Set<String> fetchAttachedPolicyNames(String roleName, AmazonIdentityManagementClient iamClient) {
    return Optional.of(new ListAttachedRolePoliciesRequest().withRoleName(roleName))
            .map(iamClient::listAttachedRolePolicies)
            .map(ListAttachedRolePoliciesResult::getAttachedPolicies)
            .map(attachedPolicies -> attachedPolicies.stream().map(AttachedPolicy::getPolicyName).collect(toSet()))
            .orElseGet(Collections::emptySet);
}
 
Example #15
Source File: PolicyProviderImpl.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private Set<String> fetchInlinePolicyNames(String roleName, AmazonIdentityManagementClient iamClient) {
    return Optional.of(new ListRolePoliciesRequest().withRoleName(roleName))
            .map(iamClient::listRolePolicies)
            .map(ListRolePoliciesResult::getPolicyNames)
            .map(nameList -> nameList.stream().collect(toSet()))
            .orElseGet(Collections::emptySet);
}
 
Example #16
Source File: PolicyProviderImpl.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private String fetchMainPolicy(String roleName, AmazonIdentityManagementClient iamClient) {
    return Optional.of(new GetRolePolicyRequest().withRoleName(roleName).withPolicyName(roleName))
            .map(iamClient::getRolePolicy)
            .map(GetRolePolicyResult::getPolicyDocument)
            .map(PolicyProviderImpl::urlDecode)
            .orElse(EMPTY_JSON);
}
 
Example #17
Source File: PolicyProviderImpl.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Override
public RolePolicies getRolePolicies(String roleName, Region region, String accountId) {
    final AmazonIdentityManagementClient iamClient = clientProvider
            .getClient(AmazonIdentityManagementClient.class, accountId, region);
    final Set<String> attachedPolicyNames = fetchAttachedPolicyNames(roleName, iamClient);
    final Set<String> inlinePolicyNames = fetchInlinePolicyNames(roleName, iamClient);
    // assuming that there is an inline policy with the same name as the role itself
    final String mainPolicy = inlinePolicyNames.contains(roleName) ? fetchMainPolicy(roleName, iamClient) : EMPTY_JSON;

    return new RolePolicies(attachedPolicyNames, inlinePolicyNames, mainPolicy);
}
 
Example #18
Source File: LDAPIAMPoller.java    From aws-iam-ldap-bridge with Apache License 2.0 5 votes vote down vote up
private String getUserAccessKey(AmazonIdentityManagementClient client, User user) {
    ListAccessKeysResult res = client.listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName()));
    for (AccessKeyMetadata meta : res.getAccessKeyMetadata()) {
        if ("Active".equals(meta.getStatus())) {
            return meta.getAccessKeyId();
        }
    }
    return null;
}
 
Example #19
Source File: IAMUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * This method will fetch the attached policy a particular role.
 * 
 * @param roleName
 * @param iamClient
 * @return list of AttachedPolicy
 */
public static List<AttachedPolicy> getAttachedPolicyOfIAMUser(String userName,
		AmazonIdentityManagementClient iamClient) throws RuleExecutionFailedExeption {
	ListAttachedUserPoliciesRequest attachedUserPoliciesRequest = new ListAttachedUserPoliciesRequest();
	attachedUserPoliciesRequest.setUserName(userName);
	ListAttachedUserPoliciesResult userPoliciesResult = iamClient
			.listAttachedUserPolicies(attachedUserPoliciesRequest);
	return userPoliciesResult.getAttachedPolicies();
}
 
Example #20
Source File: IAMPolicyManagerTest.java    From strongbox with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() {
    mockCredentials = mock(AWSCredentialsProvider.class);
    mockClient = mock(AmazonIdentityManagementClient.class);
    ClientConfiguration mockConfig = mock(ClientConfiguration.class);
    IAMPolicyManager policyManager = new IAMPolicyManager(mockClient, mockCredentials, mockConfig);

    // The mockito spy acts like original object but mocks out the getAccount() method. As the getAccount() calls
    // directly rather than via a client that we can pass in we need to mock this out using a spy.
    partiallyMockedPolicyManager = spy(policyManager);
    doReturn(ACCOUNT).when(partiallyMockedPolicyManager).getAccount();

    // Set up KMSEncryptor for testing the policy creation methods. This gets a bit complicated but we need to
    // mock all the AWS dependencies from the KMSManager before using it to create the KMSEncryptor. The getAliasArn
    // needs to be mocked out with a spy to stop the call to getAccount.
    mockKMSClient = mock(AWSKMSClient.class);
    KMSManager kmsManager = new KMSManager(mockKMSClient, mockCredentials, mockConfig, group);
    KMSManager partiallyMockedKMSManager = spy(kmsManager);
    doReturn(KMS_ALIAS_ARN).when(partiallyMockedKMSManager).getAliasArn();
    kmsEncryptor = new KMSEncryptor(partiallyMockedKMSManager, mockCredentials, mockConfig, group, mock(AwsCrypto.class), EncryptionStrength.AES_256);

    // Set up store for testing the policy creation methods. Mock out the getArn method with a spy to stop the
    // call to getAccount().
    mockDynamoDBClient = mock(AmazonDynamoDBClient.class);
    DynamoDB store = new DynamoDB(mockDynamoDBClient, mockCredentials, mockConfig, group, new ReentrantReadWriteLock());
    partiallyMockedStore = spy(store);
    doReturn(DYNAMODB_ARN).when(partiallyMockedStore).getArn();
}
 
Example #21
Source File: IAMUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * This method will fetch the attached policy a particular role.
 * 
 * @param roleName
 * @param iamClient
 * @return list of AttachedPolicy
 */
public static List<AttachedPolicy> getAttachedPolicyOfIAMRole(final String roleName,
		AmazonIdentityManagementClient iamClient) throws RuleExecutionFailedExeption {
	ListAttachedRolePoliciesRequest attachedUserPoliciesRequest = new ListAttachedRolePoliciesRequest();
	attachedUserPoliciesRequest.setRoleName(roleName);
	ListAttachedRolePoliciesResult rolePoliciesResult = iamClient
			.listAttachedRolePolicies(attachedUserPoliciesRequest);
	return rolePoliciesResult.getAttachedPolicies();
}
 
Example #22
Source File: PrincipalAutoSuggestionTest.java    From strongbox with Apache License 2.0 4 votes vote down vote up
@BeforeMethod
public void setUp() {
    mockClient = mock(AmazonIdentityManagementClient.class);
    PrincipalAutoSuggestion principalAutoSuggestion = new PrincipalAutoSuggestion(mockClient);
    partiallyMockedPrincipalAutoSuggestion= spy(principalAutoSuggestion);
}
 
Example #23
Source File: CheckIamIdentityProviderWithADFSRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    identityManagementClient = PowerMockito.mock(AmazonIdentityManagementClient.class); 
}
 
Example #24
Source File: AccessKeyRotatedRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    identityManagementClient = PowerMockito.mock(AmazonIdentityManagementClient.class); 
}
 
Example #25
Source File: AwsIamAccountWithPermanentAccessKeysRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    identityManagementClient = PowerMockito.mock(AmazonIdentityManagementClient.class); 
}
 
Example #26
Source File: ServiceAccountPrivilegesRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    identityManagementClient = PowerMockito.mock(AmazonIdentityManagementClient.class); 
}
 
Example #27
Source File: OpsWorksDeploymentTests.java    From aws-ant-tasks with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUp() {
    s3Client = new AmazonS3Client();
    client = new AWSOpsWorksClient();
    iamClient = new AmazonIdentityManagementClient();
}
 
Example #28
Source File: BrokerConfiguration.java    From s3-cf-service-broker with Apache License 2.0 4 votes vote down vote up
@Bean
public AmazonIdentityManagement amazonIdentityManagement() {
    return new AmazonIdentityManagementClient(awsCredentials(), awsClientConfiguration.toClientConfiguration());
}
 
Example #29
Source File: CheckIamPasswordPolicyRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    identityManagementClient = PowerMockito.mock(AmazonIdentityManagementClient.class); 
}
 
Example #30
Source File: IAMAccessGrantForNonAdminAccountRuleTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    identityManagementClient = PowerMockito.mock(AmazonIdentityManagementClient.class); 
}