Search in sources :

Example 1 with AwsPermissionMissingException

use of com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException in project cloudbreak by hortonworks.

the class AwsCredentialConnectorTest method testVerifyIfRoleBasedCredentialVerificationThrowsSdkBaseExceptionThenFailedStatusShouldReturn.

@Test
public void testVerifyIfRoleBasedCredentialVerificationThrowsSdkBaseExceptionThenFailedStatusShouldReturn() throws AwsPermissionMissingException, IOException {
    URL url = Resources.getResource("definitions/aws-environment-minimal-policy.json");
    String awsEnvPolicy = Resources.toString(url, UTF_8);
    String encodedAwsEnvPolicy = Base64.getEncoder().encodeToString(awsEnvPolicy.getBytes());
    String roleArn = "someRoleArn";
    when(credentialView.getRoleArn()).thenReturn(roleArn);
    String exceptionMessageComesFromSdk = "SomethingTerribleHappened!";
    String expectedExceptionMessage = String.format("Unable to verify credential: check if the role '%s' exists and it's created with the correct " + "external ID. Cause: '%s'", roleArn, exceptionMessageComesFromSdk);
    Exception sdkException = new SdkBaseException(exceptionMessageComesFromSdk);
    when(awsPlatformParameters.getEnvironmentMinimalPoliciesJson()).thenReturn(Map.of(PolicyType.PUBLIC, encodedAwsEnvPolicy, PolicyType.GOV, encodedAwsEnvPolicy));
    doThrow(sdkException).when(awsCredentialVerifier).validateAws(credentialView, encodedAwsEnvPolicy);
    CloudCredentialStatus result = underTest.verify(authenticatedContext, CREDENTIAL_VERIFICATION_CONTEXT);
    assertNotNull(result);
    assertEquals(CredentialStatus.FAILED, result.getStatus());
    assertEquals(expectedExceptionMessage, result.getStatusReason());
    assertEquals(sdkException, result.getException());
    verify(awsCredentialVerifier, times(1)).validateAws(any(), any());
    verify(awsCredentialVerifier, times(1)).validateAws(credentialView, encodedAwsEnvPolicy);
}
Also used : SdkBaseException(com.amazonaws.SdkBaseException) URL(java.net.URL) SdkBaseException(com.amazonaws.SdkBaseException) AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) ExpectedException(org.junit.rules.ExpectedException) IOException(java.io.IOException) AwsConfusedDeputyException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsConfusedDeputyException) AmazonClientException(com.amazonaws.AmazonClientException) CloudCredentialStatus(com.sequenceiq.cloudbreak.cloud.model.CloudCredentialStatus) Test(org.junit.Test)

Example 2 with AwsPermissionMissingException

use of com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException in project cloudbreak by hortonworks.

the class AwsCredentialVerifierTest method verifyCredentialAndThrowFailExceptionBecauseOrganizatioRuleTest.

@Test
public void verifyCredentialAndThrowFailExceptionBecauseOrganizatioRuleTest() throws IOException {
    URL url = Resources.getResource("definitions/aws-environment-minimal-policy.json");
    String awsEnvPolicy = Resources.toString(url, Charsets.UTF_8);
    String encodedAwsEnvPolicy = Base64.getEncoder().encodeToString(awsEnvPolicy.getBytes());
    Map<String, Object> awsParameters = new HashMap<>();
    awsParameters.put("accessKey", "a");
    awsParameters.put("secretKey", "b");
    CloudCredential cloudCredential = new CloudCredential("id", "name", awsParameters, "acc", false);
    AmazonIdentityManagementClient amazonIdentityManagement = mock(AmazonIdentityManagementClient.class);
    when(awsClient.createAmazonIdentityManagement(any(AwsCredentialView.class))).thenReturn(amazonIdentityManagement);
    AmazonSecurityTokenServiceClient awsSecurityTokenService = mock(AmazonSecurityTokenServiceClient.class);
    GetCallerIdentityResult getCallerIdentityResult = new GetCallerIdentityResult();
    getCallerIdentityResult.setArn("arn");
    when(awsSecurityTokenService.getCallerIdentity(any(GetCallerIdentityRequest.class))).thenReturn(getCallerIdentityResult);
    when(awsClient.createSecurityTokenService(any(AwsCredentialView.class))).thenReturn(awsSecurityTokenService);
    ArgumentCaptor<SimulatePrincipalPolicyRequest> requestArgumentCaptor = ArgumentCaptor.forClass(SimulatePrincipalPolicyRequest.class);
    AtomicInteger i = new AtomicInteger();
    when(amazonIdentityManagement.simulatePrincipalPolicy(requestArgumentCaptor.capture())).thenAnswer(invocation -> {
        SimulatePrincipalPolicyResult simulatePrincipalPolicyResult = new SimulatePrincipalPolicyResult();
        ArrayList<EvaluationResult> evaluationResults = new ArrayList<>();
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("denied_action1_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(false)).withEvalActionName("denied_action2_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(false)).withEvalActionName("denied_action3_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("accept").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("accepted_action_" + i).withEvalResourceName("*"));
        simulatePrincipalPolicyResult.setEvaluationResults(evaluationResults);
        i.getAndIncrement();
        return simulatePrincipalPolicyResult;
    });
    try {
        awsCredentialVerifier.validateAws(new AwsCredentialView(cloudCredential), encodedAwsEnvPolicy);
        fail("It shoud throw verification exception");
    } catch (AwsPermissionMissingException e) {
        assertThat(e.getMessage(), CoreMatchers.containsString("denied_action1_0 : aws:ec2,"));
        assertThat(e.getMessage(), CoreMatchers.containsString("denied_action2_0 : aws:ec2 -> Denied by Organization Rule,"));
        assertThat(e.getMessage(), CoreMatchers.containsString("denied_action3_0 : aws:ec2 -> Denied by Organization Rule,"));
        assertThat(e.getMessage(), not(CoreMatchers.containsString("accepted_action")));
    }
    List<SimulatePrincipalPolicyRequest> allSimulatePrincipalPolicyRequest = requestArgumentCaptor.getAllValues();
    int simulateRequestNumber = 5;
    assertEquals("expect if " + simulateRequestNumber + " simulate request has been sent", simulateRequestNumber, allSimulatePrincipalPolicyRequest.size());
    allSimulatePrincipalPolicyRequest.forEach(simulatePrincipalPolicyRequest -> assertEquals("arn", simulatePrincipalPolicyRequest.getPolicySourceArn()));
}
Also used : AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) AmazonIdentityManagementClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonIdentityManagementClient) HashMap(java.util.HashMap) CloudCredential(com.sequenceiq.cloudbreak.cloud.model.CloudCredential) OrganizationsDecisionDetail(com.amazonaws.services.identitymanagement.model.OrganizationsDecisionDetail) ArrayList(java.util.ArrayList) URL(java.net.URL) EvaluationResult(com.amazonaws.services.identitymanagement.model.EvaluationResult) AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SimulatePrincipalPolicyRequest(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest) GetCallerIdentityRequest(com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest) AmazonSecurityTokenServiceClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonSecurityTokenServiceClient) SimulatePrincipalPolicyResult(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult) GetCallerIdentityResult(com.amazonaws.services.securitytoken.model.GetCallerIdentityResult) Test(org.junit.Test)

Example 3 with AwsPermissionMissingException

use of com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException in project cloudbreak by hortonworks.

the class AwsCredentialConnector method verifyCredentialsPermission.

private CDPServicePolicyVerificationResponses verifyCredentialsPermission(AwsCredentialView awsCredential, Map<String, String> servicesWithPolicies) {
    Set<CDPServicePolicyVerificationResponse> cdpServicePolicyVerificationResponses = new HashSet<>();
    for (Map.Entry<String, String> entry : servicesWithPolicies.entrySet()) {
        String serviceName = entry.getKey();
        String policy = entry.getValue();
        try {
            if (Strings.isNullOrEmpty(policy)) {
                CDPServicePolicyVerificationResponse cdpServicePolicyVerificationResponse = new CDPServicePolicyVerificationResponse();
                cdpServicePolicyVerificationResponse.setStatusCode(CDPServicePolicyVerificationResponse.NOT_IMPLEMENTED);
                cdpServicePolicyVerificationResponse.setServiceStatus("The policy query endpoint was not implement on experience side.");
                cdpServicePolicyVerificationResponse.setServiceName(serviceName);
                cdpServicePolicyVerificationResponses.add(cdpServicePolicyVerificationResponse);
            } else {
                verifyCredentialsPermission(awsCredential, policy);
            }
        } catch (AwsPermissionMissingException e) {
            CDPServicePolicyVerificationResponse cdpServicePolicyVerificationResponse = new CDPServicePolicyVerificationResponse();
            cdpServicePolicyVerificationResponse.setStatusCode(CDPServicePolicyVerificationResponse.NOT_FOUND);
            cdpServicePolicyVerificationResponse.setServiceName(serviceName);
            cdpServicePolicyVerificationResponse.setServiceStatus(e.getMessage());
            cdpServicePolicyVerificationResponses.add(cdpServicePolicyVerificationResponse);
        }
    }
    return new CDPServicePolicyVerificationResponses(cdpServicePolicyVerificationResponses);
}
Also used : AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) CDPServicePolicyVerificationResponses(com.sequenceiq.cloudbreak.cloud.model.CDPServicePolicyVerificationResponses) HashMap(java.util.HashMap) Map(java.util.Map) CDPServicePolicyVerificationResponse(com.sequenceiq.cloudbreak.cloud.model.CDPServicePolicyVerificationResponse) HashSet(java.util.HashSet)

Example 4 with AwsPermissionMissingException

use of com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException in project cloudbreak by hortonworks.

the class AwsCredentialConnector method verifyCredentialsPermission.

private CloudCredentialStatus verifyCredentialsPermission(CloudCredential cloudCredential, AwsCredentialView awsCredential, CloudCredentialStatus credentialStatus) {
    if (cloudCredential.isVerifyPermissions()) {
        try {
            String environmentMinimalPoliciesJson = awsPlatformParameters.getEnvironmentMinimalPoliciesJson().get(getPolicyType(new AwsCredentialView(cloudCredential).isGovernmentCloudEnabled()));
            verifyCredentialsPermission(awsCredential, environmentMinimalPoliciesJson);
        } catch (AwsPermissionMissingException e) {
            credentialStatus = new CloudCredentialStatus(cloudCredential, PERMISSIONS_MISSING, new Exception(e.getMessage()), e.getMessage());
        }
    }
    return credentialStatus;
}
Also used : AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView) AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) AwsConfusedDeputyException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsConfusedDeputyException) AmazonClientException(com.amazonaws.AmazonClientException) CloudCredentialStatus(com.sequenceiq.cloudbreak.cloud.model.CloudCredentialStatus)

Example 5 with AwsPermissionMissingException

use of com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException in project cloudbreak by hortonworks.

the class AwsCredentialVerifier method validateAws.

@Cacheable(value = AwsCredentialCachingConfig.TEMPORARY_AWS_CREDENTIAL_VERIFIER_CACHE, unless = "#awsCredential == null")
public void validateAws(AwsCredentialView awsCredential, String policyJson) throws AwsPermissionMissingException {
    String policies = new String(Base64.getDecoder().decode(policyJson));
    try {
        List<RequiredAction> resourcesWithActions = getRequiredActions(policies);
        AmazonIdentityManagementClient amazonIdentityManagement = awsClient.createAmazonIdentityManagement(awsCredential);
        AmazonSecurityTokenServiceClient awsSecurityTokenService = awsClient.createSecurityTokenService(awsCredential);
        String arn;
        if (awsCredential.getRoleArn() != null) {
            arn = awsCredential.getRoleArn();
        } else {
            GetCallerIdentityResult callerIdentity = awsSecurityTokenService.getCallerIdentity(new GetCallerIdentityRequest());
            arn = callerIdentity.getArn();
        }
        List<String> failedActionList = new ArrayList<>();
        for (RequiredAction resourceAndAction : resourcesWithActions) {
            SimulatePrincipalPolicyRequest simulatePrincipalPolicyRequest = new SimulatePrincipalPolicyRequest();
            simulatePrincipalPolicyRequest.setMaxItems(MAX_ELEMENT_SIZE);
            simulatePrincipalPolicyRequest.setPolicySourceArn(arn);
            simulatePrincipalPolicyRequest.setActionNames(resourceAndAction.getActionNames());
            simulatePrincipalPolicyRequest.setResourceArns(Collections.singleton(resourceAndAction.getResourceArn()));
            simulatePrincipalPolicyRequest.setContextEntries(resourceAndAction.getConditions());
            LOGGER.debug("Simulate policy request: {}", simulatePrincipalPolicyRequest);
            SimulatePrincipalPolicyResult simulatePrincipalPolicyResult = amazonIdentityManagement.simulatePrincipalPolicy(simulatePrincipalPolicyRequest);
            LOGGER.debug("Simulate policy result: {}", simulatePrincipalPolicyResult);
            simulatePrincipalPolicyResult.getEvaluationResults().stream().filter(evaluationResult -> evaluationResult.getEvalDecision().toLowerCase().contains("deny")).map(evaluationResult -> {
                if (evaluationResult.getOrganizationsDecisionDetail() != null && !evaluationResult.getOrganizationsDecisionDetail().getAllowedByOrganizations()) {
                    return evaluationResult.getEvalActionName() + " : " + evaluationResult.getEvalResourceName() + " -> Denied by Organization Rule";
                } else {
                    return evaluationResult.getEvalActionName() + " : " + evaluationResult.getEvalResourceName();
                }
            }).forEach(failedActionList::add);
        }
        if (!failedActionList.isEmpty()) {
            throw new AwsPermissionMissingException(String.format("CDP Credential '%s' doesn't have permission for these actions which are required: %s", awsCredential.getName(), failedActionList.stream().collect(joining(", ", "[ ", " ]"))));
        }
    } catch (IOException e) {
        throw new IllegalStateException("Can not parse aws policy json", e);
    }
}
Also used : Policy(com.amazonaws.auth.policy.Policy) AwsCredentialCachingConfig(com.sequenceiq.cloudbreak.cloud.aws.common.cache.AwsCredentialCachingConfig) Action(com.amazonaws.auth.policy.Action) Cacheable(org.springframework.cache.annotation.Cacheable) LoggerFactory(org.slf4j.LoggerFactory) SimulatePrincipalPolicyRequest(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest) ContextEntry(com.amazonaws.services.identitymanagement.model.ContextEntry) ArrayList(java.util.ArrayList) AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) Inject(javax.inject.Inject) AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView) Service(org.springframework.stereotype.Service) ContextKeyTypeEnum(com.amazonaws.services.identitymanagement.model.ContextKeyTypeEnum) AmazonIdentityManagementClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonIdentityManagementClient) Statement(com.amazonaws.auth.policy.Statement) GetCallerIdentityResult(com.amazonaws.services.securitytoken.model.GetCallerIdentityResult) Logger(org.slf4j.Logger) JsonPolicyReader(com.amazonaws.auth.policy.internal.JsonPolicyReader) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) GetCallerIdentityRequest(com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest) SimulatePrincipalPolicyResult(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult) Base64(java.util.Base64) List(java.util.List) AmazonSecurityTokenServiceClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonSecurityTokenServiceClient) Optional(java.util.Optional) Collections(java.util.Collections) Condition(com.amazonaws.auth.policy.Condition) AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) AmazonIdentityManagementClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonIdentityManagementClient) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SimulatePrincipalPolicyRequest(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest) GetCallerIdentityRequest(com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest) AmazonSecurityTokenServiceClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonSecurityTokenServiceClient) SimulatePrincipalPolicyResult(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult) GetCallerIdentityResult(com.amazonaws.services.securitytoken.model.GetCallerIdentityResult) Cacheable(org.springframework.cache.annotation.Cacheable)

Aggregations

AwsPermissionMissingException (com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException)7 AwsCredentialView (com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView)5 SimulatePrincipalPolicyRequest (com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest)4 SimulatePrincipalPolicyResult (com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult)4 GetCallerIdentityRequest (com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest)4 GetCallerIdentityResult (com.amazonaws.services.securitytoken.model.GetCallerIdentityResult)4 AmazonIdentityManagementClient (com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonIdentityManagementClient)4 AmazonSecurityTokenServiceClient (com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonSecurityTokenServiceClient)4 URL (java.net.URL)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Test (org.junit.Test)4 EvaluationResult (com.amazonaws.services.identitymanagement.model.EvaluationResult)3 CloudCredential (com.sequenceiq.cloudbreak.cloud.model.CloudCredential)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 AmazonClientException (com.amazonaws.AmazonClientException)2 OrganizationsDecisionDetail (com.amazonaws.services.identitymanagement.model.OrganizationsDecisionDetail)2 AwsConfusedDeputyException (com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsConfusedDeputyException)2 CloudCredentialStatus (com.sequenceiq.cloudbreak.cloud.model.CloudCredentialStatus)2 IOException (java.io.IOException)2