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

The following examples show how to use com.amazonaws.services.identitymanagement.model.AttachedPolicy. 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: IAMAccessGrantForNonAdminAccountRule.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks for the property "AdministratorAccess" and
 * "IAMFullAccess" in the list of attached policies for a Role
 * 
 * @param attachedPolicies
 * @param isAdmin
 * @return true if the attached policy contains "AdministratorAccess"
 *         property false otherwise.
 */
private boolean isValidPoliciesForNonAdminRole(
        List<AttachedPolicy> attachedPolicies) {
    for (AttachedPolicy policy : attachedPolicies) {
        String policyName = policy.getPolicyName();
        if(!StringUtils.isEmpty(policyName)){
        if (policyName
                .equalsIgnoreCase(PacmanRuleConstants.ADMINISTRATOR_ACCESS)) {
            return true;
        }
        if (policyName
                .equalsIgnoreCase(PacmanRuleConstants.IAM_FULL_ACCESS)) {
            return true;
        }
    }
    }
    return false;
}
 
Example #2
Source File: PolicyProviderTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRolePolicies() throws Exception {
    when(clientMock.listAttachedRolePolicies(any()))
            .thenReturn(new ListAttachedRolePoliciesResult().withAttachedPolicies(
                    new AttachedPolicy().withPolicyName("bar1"),
                    new AttachedPolicy().withPolicyName("bar2")));
    when(clientMock.listRolePolicies(any()))
            .thenReturn(new ListRolePoliciesResult().withPolicyNames("foo", "bar"));
    when(clientMock.getRolePolicy(any()))
            .thenReturn(new GetRolePolicyResult().withPolicyDocument("%7B%22hello%22%3A%22world%22%7D"));

    final RolePolicies rolePolicies = policyProvider.getRolePolicies("foo", Region.getRegion(US_EAST_1), "123456789012");
    assertThat(rolePolicies).isNotNull();
    assertThat(rolePolicies.getAttachedPolicyNames()).containsOnly("bar1", "bar2");
    assertThat(rolePolicies.getInlinePolicyNames()).containsOnly("foo", "bar");
    assertThat(rolePolicies.getMainPolicy()).isEqualTo("{\"hello\":\"world\"}");

    verify(clientMock).listAttachedRolePolicies(any());
    verify(clientMock).listRolePolicies(any());
    verify(clientMock).getRolePolicy(any());
}
 
Example #3
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 #4
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 #5
Source File: ServiceAccountPrivilegesRuleTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Test
public void test()throws Exception{
	 AttachedPolicy attachedPolicies = new AttachedPolicy();
     attachedPolicies.setPolicyName("IAMFullAccess");
     List<AttachedPolicy> policies = new ArrayList<>();
     policies.add(attachedPolicies);
    
    mockStatic(PacmanUtils.class);
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString(),anyString(),anyString())).thenReturn(
            true);
    
    Map<String,Object>map=new HashMap<String, Object>();
    map.put("client", identityManagementClient);
    ServiceAccountPrivilegesRule spy = Mockito.spy(new ServiceAccountPrivilegesRule());
    
    Mockito.doReturn(map).when((BaseRule)spy).getClientFor(anyObject(), anyString(), anyObject());
    
    mockStatic(IAMUtils.class);
    when(PacmanUtils.splitStringToAList(anyString(),anyString())).thenReturn(CommonTestUtils.getListString());
    when(IAMUtils.getAllowedActionsByUserPolicy(anyObject(),anyString())).thenReturn(CommonTestUtils.getSetString("svc_123"));
    spy.execute(CommonTestUtils.getMapString("svc_123 "),CommonTestUtils.getMapString("svc_123 "));
    
    spy.execute(CommonTestUtils.getMapString("svec_123 "),CommonTestUtils.getMapString("svec_123 "));
    
    
    when(IAMUtils.getAttachedPolicyOfIAMUser(anyString(),anyObject())).thenThrow(new RuleExecutionFailedExeption());
    assertThatThrownBy( 
            () -> serviceAccountPrivilegesRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
    
    
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString(),anyString(),anyString())).thenReturn(
            false);
    assertThatThrownBy(
            () -> serviceAccountPrivilegesRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
}
 
Example #6
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch IAM group info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param account the account
 * @return the map
 */
public static  Map<String,List<GroupVH>> fetchIAMGroups(BasicSessionCredentials temporaryCredentials,String account, String accountName) {
	log.info("Fetch IAMGroups info start");
	AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(InventoryConstants.REGION_US_WEST_2).build();
	List<Group> groups = new ArrayList<>();
	ListGroupsResult rslt;
	String marker = null;
	do{
		rslt =  iamClient.listGroups(new ListGroupsRequest().withMarker(marker));
		groups.addAll(rslt.getGroups());
		marker = rslt.getMarker();
	}while(marker!=null);

	List<GroupVH> groupList = new ArrayList<>();
	Map<String,List<GroupVH>> iamGroups = new HashMap<>();
	iamGroups.put(account+delimiter+accountName,  groupList);
	groups.parallelStream().forEach(group -> {
		GroupVH groupTemp = new GroupVH(group);
		String groupName = group.getGroupName();

		List<AttachedPolicy> policies = iamClient.listAttachedGroupPolicies(new ListAttachedGroupPoliciesRequest().withGroupName(groupName)).getAttachedPolicies();
		List<String> policyList = new ArrayList<>();
		for(AttachedPolicy pol : policies){
			policyList.add(pol.getPolicyName());
		}
		groupTemp.setPolicies(policyList);
		synchronized (groupList) {
			groupList.add(groupTemp);
		}
	});

	return iamGroups;
}
 
Example #7
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 #8
Source File: IAMUtilsTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("static-access")
@Test
public void getActionListByPolicyTest() throws Exception {
	 AttachedPolicy attachedPolicies = new AttachedPolicy();
     attachedPolicies.setPolicyName("IAMFullAccess");
     List<AttachedPolicy> policies = new ArrayList<>();
     policies.add(attachedPolicies);
     
     PolicyVersion versions = new PolicyVersion();
     versions.setIsDefaultVersion(true);
     versions.setVersionId("123");
     versions.setDocument("{\"ag\":\"aws-all\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iam:*\"],\"Resource\":[\"iam:*\"]}],\"from\":0,\"searchtext\":\"\",\"size\":25}");
    ListPolicyVersionsResult policyVersions = new ListPolicyVersionsResult();
    policyVersions.setVersions(Arrays.asList(versions));
    
    
    ListAttachedUserPoliciesResult attachedUserPoliciesResult = new ListAttachedUserPoliciesResult();
    attachedUserPoliciesResult.setAttachedPolicies(policies);
    attachedUserPoliciesResult.setIsTruncated(false);
    
    ListUserPoliciesResult listUserPoliciesResult = new ListUserPoliciesResult();
    listUserPoliciesResult.setPolicyNames(Arrays.asList("123"));
    listUserPoliciesResult.setIsTruncated(false);
    
    GetUserPolicyResult policyResult = new GetUserPolicyResult();
    
    policyResult.setPolicyName("123");
    policyResult.setPolicyDocument("{\"ag\":\"aws-all\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iam:*\"],\"Resource\":[\"iam:*\"]}],\"from\":0,\"searchtext\":\"\",\"size\":25}");
    policyResult.setUserName("123");
     
    GetPolicyVersionResult versionResult = new GetPolicyVersionResult();
    versionResult.setPolicyVersion(versions);
    when(iamClient.listAttachedUserPolicies(anyObject())).thenReturn(attachedUserPoliciesResult);
    when(iamClient.listUserPolicies(anyObject())).thenReturn(listUserPoliciesResult);
    when(iamClient.getUserPolicy(anyObject())).thenReturn(policyResult);
    when(iamClient.listPolicyVersions(anyObject())).thenReturn(policyVersions);
    when(iamClient.getPolicyVersion(anyObject())).thenReturn(versionResult);
    mockStatic(URLDecoder.class);
    when(URLDecoder.decode(anyString(),anyString())).thenReturn("qeqwehgj");
    assertThat(iamUtils.getAllowedActionsByUserPolicy(iamClient,"133"),is(notNullValue()));
    
}
 
Example #9
Source File: IAMUtilsTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("static-access")
@Test
public void getActionsByRolePolicyTest() throws Exception {
	 AttachedPolicy attachedPolicies = new AttachedPolicy();
     attachedPolicies.setPolicyName("IAMFullAccess");
     List<AttachedPolicy> policies = new ArrayList<>();
     policies.add(attachedPolicies);
     
     PolicyVersion versions = new PolicyVersion();
     versions.setIsDefaultVersion(true);
     versions.setVersionId("123");
     versions.setDocument("{\"ag\":\"aws-all\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iam:*\"],\"Resource\":[\"iam:*\"]}],\"from\":0,\"searchtext\":\"\",\"size\":25}");
    ListPolicyVersionsResult policyVersions = new ListPolicyVersionsResult();
    policyVersions.setVersions(Arrays.asList(versions));
    
    
    ListAttachedRolePoliciesResult attachedRolePoliciesResult = new ListAttachedRolePoliciesResult();
    attachedRolePoliciesResult.setAttachedPolicies(policies);
    attachedRolePoliciesResult.setIsTruncated(false);
    
    ListRolePoliciesResult rolePoliciesResult = new ListRolePoliciesResult();
    rolePoliciesResult.setPolicyNames(Arrays.asList("123"));
    rolePoliciesResult.setIsTruncated(false);
    
    GetRolePolicyResult policyResult = new GetRolePolicyResult();
    
    policyResult.setPolicyName("123");
    policyResult.setPolicyDocument("{\"ag\":\"aws-all\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iam:*\"],\"Resource\":[\"iam:*\"]}],\"from\":0,\"searchtext\":\"\",\"size\":25}");
    policyResult.setRoleName("123");
     
    GetPolicyVersionResult versionResult = new GetPolicyVersionResult();
    versionResult.setPolicyVersion(versions);
    when(iamClient.listAttachedRolePolicies(anyObject())).thenReturn(attachedRolePoliciesResult);
    when(iamClient.listRolePolicies(anyObject())).thenReturn(rolePoliciesResult);
    when(iamClient.getRolePolicy(anyObject())).thenReturn(policyResult);
    when(iamClient.listPolicyVersions(anyObject())).thenReturn(policyVersions);
    when(iamClient.getPolicyVersion(anyObject())).thenReturn(versionResult);
    mockStatic(URLDecoder.class);
    when(URLDecoder.decode(anyString(),anyString())).thenReturn("qeqwehgj");
    assertThat(iamUtils.getAllowedActionsByRolePolicy(iamClient,"133"),is(notNullValue()));
    
}
 
Example #10
Source File: AttachRolePolicy.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply a role name\n" +
        "Ex: AttachRolePolicy <role-name>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String role_name = args[0];

    final AmazonIdentityManagement iam =
        AmazonIdentityManagementClientBuilder.defaultClient();

    ListAttachedRolePoliciesRequest request =
        new ListAttachedRolePoliciesRequest()
            .withRoleName(role_name);

    List<AttachedPolicy> matching_policies = new ArrayList<>();

    boolean done = false;

    while(!done) {
        ListAttachedRolePoliciesResult response =
            iam.listAttachedRolePolicies(request);

        matching_policies.addAll(
                response.getAttachedPolicies()
                        .stream()
                        .filter(p -> p.getPolicyName().equals(role_name))
                        .collect(Collectors.toList()));

        if(!response.getIsTruncated()) {
            done = true;
        }
        request.setMarker(response.getMarker());
    }

    if (matching_policies.size() > 0) {
        System.out.println(role_name +
                " policy is already attached to this role.");
        return;
    }

    AttachRolePolicyRequest attach_request =
        new AttachRolePolicyRequest()
            .withRoleName(role_name)
            .withPolicyArn(POLICY_ARN);

    iam.attachRolePolicy(attach_request);

    System.out.println("Successfully attached policy " + POLICY_ARN +
            " to role " + role_name);
}