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

The following examples show how to use com.amazonaws.services.identitymanagement.model.ListRolesRequest. 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: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch IAM roles.
 *
 * @param temporaryCredentials the temporary credentials
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static  Map<String,List<Role>>  fetchIAMRoles(BasicSessionCredentials temporaryCredentials,String accountId,String accountName) {

	AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(InventoryConstants.REGION_US_WEST_2).build();
	List<Role> roles = new ArrayList<>();
	ListRolesResult rslt;
	String marker = null;
	do{
		rslt =  iamClient.listRoles(new ListRolesRequest().withMarker(marker));
		roles.addAll(rslt.getRoles());
		marker = rslt.getMarker();
	}while(marker!=null);

	log.debug(InventoryConstants.ACCOUNT + accountId +" Type : IAM Roles >> "+roles.size());
	Map<String,List<Role>> iamRoles = new HashMap<>();
	iamRoles.put(accountId+delimiter+accountName, roles);
	return iamRoles;
}
 
Example #2
Source File: PrincipalAutoSuggestionTest.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoSuggestion() throws Exception {
    ListRolesRequest request = new ListRolesRequest().withMaxItems(1000);

    Role role1 = new Role().withRoleName("foobar1");
    Role role2 = new Role().withRoleName("afoobar");
    Role role3 = new Role().withRoleName("foooobar");
    ListRolesResult mockResult = new ListRolesResult();
    mockResult.withRoles(role1, role2, role3);

    when(mockClient.listRoles(request)).thenReturn(mockResult);
    List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("foobar");
    assertEquals(list.size(), 2);
    assertEquals(list.get(0).name, "foobar1");
    assertEquals(list.get(1).name, "afoobar");

    verify(mockClient, times(1)).listRoles(request);
}
 
Example #3
Source File: PrincipalAutoSuggestionTest.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoSuggestionCaseInsensitive() throws Exception {
    ListRolesRequest request = new ListRolesRequest().withMaxItems(1000);

    Role lowercase = new Role().withRoleName("foobar");
    Role uppercase = new Role().withRoleName("FOOBAR");
    Role mixedCase = new Role().withRoleName("FooBar");
    ListRolesResult mockResult = new ListRolesResult();
    mockResult.withRoles(lowercase, uppercase, mixedCase);

    when(mockClient.listRoles(request)).thenReturn(mockResult);

    List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("fOOb");
    assertEquals(list.size(), 3);
    assertEquals(list.get(0).name, "foobar");
    assertEquals(list.get(1).name, "FOOBAR");
    assertEquals(list.get(2).name, "FooBar");
}
 
Example #4
Source File: CrossAccountPolicyForIAMJobTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheck() throws Exception {
    when(accountIdSupplierMock.get()).thenReturn(newHashSet(ACCOUNT_ID));
    when(jobsPropertiesMock.getManagementAccount()).thenReturn(MANAGEMENT_ACCOUNT);
    when(mockAmazonIdentityManagementClient.listRoles(any(ListRolesRequest.class))).thenReturn(mockListRolesResult);

    final CrossAccountPolicyForIAMJob crossAccountPolicyForIAMJob = new CrossAccountPolicyForIAMJob(
            violationSinkMock,
            clientProviderMock,
            accountIdSupplierMock,
            jobsPropertiesMock,
            mock(JobExceptionHandler.class));

    crossAccountPolicyForIAMJob.run();

    verify(accountIdSupplierMock).get();
    verify(clientProviderMock).getClient(any(), any(String.class), any(Region.class));
    verify(mockAmazonIdentityManagementClient).listRoles(any(ListRolesRequest.class));
    verify(jobsPropertiesMock, atLeastOnce()).getManagementAccount();
    verify(violationSinkMock, times(1)).put(argThat(ViolationMatchers.hasType(CROSS_ACCOUNT_ROLE)));
}
 
Example #5
Source File: PrincipalAutoSuggestion.java    From strongbox with Apache License 2.0 5 votes vote down vote up
public List<Principal> autoSuggestion(final String name) {
    if (name.length() >= 3) {
        String lowerCaseName = name.toLowerCase();

        ListRolesRequest listRolesRequest = new ListRolesRequest();
        listRolesRequest.withMaxItems(1000);
        ListRolesResult result = client.listRoles(listRolesRequest);
        List<Principal> tmp = result.getRoles().stream()
                .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName))
                .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList());

        return tmp.subList(0, Math.min(5, tmp.size()));
    }
    return new ArrayList<>();
}
 
Example #6
Source File: IntegrationTestHelper.java    From strongbox with Apache License 2.0 5 votes vote down vote up
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);
        }
    }

}
 
Example #7
Source File: PrincipalAutoSuggestionTest.java    From strongbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoSuggestionShortName() throws Exception {
    // Won't call the list method if less than 3 chars.
    ListRolesRequest request = new ListRolesRequest().withMaxItems(1000);
    List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("fo");
    assertTrue(list.isEmpty());
    verify(mockClient, never()).listRoles(request);
}
 
Example #8
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Set<CloudAccessConfig> getAccessConfigByRole(AmazonIdentityManagement client) {
    LOGGER.info("Get all Roles from Amazon");
    String queryFailedMessage = "Could not get roles from Amazon: ";
    try {
        boolean finished = false;
        String marker = null;
        List<Role> roles = new LinkedList<>();
        while (!finished) {
            ListRolesRequest listRolesRequest = new ListRolesRequest();
            listRolesRequest.setMaxItems(fetchMaxItems);
            if (isNotEmpty(marker)) {
                listRolesRequest.setMarker(marker);
            }
            LOGGER.debug("About to fetch roles...");
            ListRolesResult listRolesResult = client.listRoles(listRolesRequest);
            roles.addAll(listRolesResult.getRoles());
            if (listRolesResult.isTruncated()) {
                marker = listRolesResult.getMarker();
            } else {
                finished = true;
            }
        }
        return roles.stream().map(this::roleToCloudAccessConfig).collect(Collectors.toSet());
    } catch (AmazonServiceException ase) {
        if (ase.getStatusCode() == UNAUTHORIZED) {
            String policyMessage = "Could not get roles because the user does not have enough permission. ";
            LOGGER.error(policyMessage + ase.getMessage(), ase);
            throw new CloudUnauthorizedException(ase.getErrorMessage(), ase);
        } else {
            LOGGER.info(queryFailedMessage + ase.getMessage(), ase);
            throw new CloudConnectorException(ase.getMessage(), ase);
        }
    } catch (Exception e) {
        LOGGER.warn(queryFailedMessage + e.getMessage(), e);
        throw new CloudConnectorException(e.getMessage(), e);
    }
}
 
Example #9
Source File: IdentityManagementImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public RoleCollection getRoles() {
    return getRoles((ListRolesRequest)null);
}
 
Example #10
Source File: IdentityManagementImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public RoleCollection getRoles(ListRolesRequest request) {
    ResourceCollectionImpl result = service.getCollection("Roles", request);
    if (result == null) return null;
    return new RoleCollectionImpl(result);
}
 
Example #11
Source File: IdentityManagement.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieves the Roles collection referenced by this resource.
 */
RoleCollection getRoles(ListRolesRequest request);