Search in sources :

Example 21 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testUpdateApplication.

@Test
public void testUpdateApplication() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    final String consumerKey = "xxx-xxx-xxx-xxx";
    // happy path - 200
    // //request object to key manager
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientName("app1");
    List<String> grantTypesList = new ArrayList<>();
    grantTypesList.add("password");
    grantTypesList.add("client-credentials");
    oAuthApplicationInfo.setGrantTypes(grantTypesList);
    oAuthApplicationInfo.setCallBackURL("https://sample.callback/url");
    oAuthApplicationInfo.setClientId(consumerKey);
    oAuthApplicationInfo.setClientSecret("yyy-yyy-yyy-yyy");
    // //request object to dcr api
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(oAuthApplicationInfo.getClientName());
    dcrClientInfo.setGrantTypes(oAuthApplicationInfo.getGrantTypes());
    dcrClientInfo.addCallbackUrl(oAuthApplicationInfo.getCallBackURL());
    /*
        dcrClientInfo.setUserinfoSignedResponseAlg(ServiceReferenceHolder.getInstance().getAPIMConfiguration()
                .getKeyManagerConfigs().getOidcUserinfoJWTSigningAlgo());
*/
    dcrClientInfo.setClientId(oAuthApplicationInfo.getClientId());
    dcrClientInfo.setClientSecret(oAuthApplicationInfo.getClientSecret());
    // //mocked response object from dcr api
    DCRClientInfo dcrClientInfoResponse = new DCRClientInfo();
    dcrClientInfoResponse.setClientName(oAuthApplicationInfo.getClientName());
    dcrClientInfoResponse.setGrantTypes(oAuthApplicationInfo.getGrantTypes());
    dcrClientInfoResponse.addCallbackUrl(oAuthApplicationInfo.getCallBackURL());
    dcrClientInfoResponse.setClientId(consumerKey);
    dcrClientInfoResponse.setClientSecret("yyy-yyy-yyy-yyy");
    dcrClientInfoResponse.setClientIdIssuedAt("now");
    dcrClientInfoResponse.setClientSecretExpiresAt("future");
    dcrClientInfoResponse.setRegistrationClientUri("https://localhost:9443/oauth/xxx-xxx-xxx-xxx");
    // //expected response object from key manager
    OAuthApplicationInfo oAuthApplicationInfoResponse = new OAuthApplicationInfo();
    oAuthApplicationInfoResponse.setClientName(dcrClientInfoResponse.getClientName());
    oAuthApplicationInfoResponse.setGrantTypes(dcrClientInfoResponse.getGrantTypes());
    oAuthApplicationInfoResponse.setCallBackURL(dcrClientInfoResponse.getRedirectURIs().get(0));
    oAuthApplicationInfoResponse.setClientId(dcrClientInfoResponse.getClientId());
    oAuthApplicationInfoResponse.setClientSecret(dcrClientInfoResponse.getClientSecret());
    Response dcrResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(dcrClientInfoResponse), feign.Util.UTF_8).build();
    Mockito.when(dcrmServiceStub.updateApplication(dcrClientInfo, consumerKey)).thenReturn(dcrResponse);
    try {
        OAuthApplicationInfo app = kmImpl.updateApplication(oAuthApplicationInfo);
        Assert.assertEquals(app, oAuthApplicationInfoResponse);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - 400
    int errorSc = 400;
    String errorMsg = "{\"error\": \"invalid_redirect_uri\", \"error_description\": \"One or more " + "redirect_uri values are invalid\"}";
    Response errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.updateApplication(dcrClientInfo, consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.updateApplication(oAuthApplicationInfo);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while updating DCR application."));
    }
    // error case - non-400
    errorSc = 500;
    errorMsg = "unknown error occurred";
    errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.updateApplication(dcrClientInfo, consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.updateApplication(oAuthApplicationInfo);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while updating DCR application."));
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) Test(org.testng.annotations.Test)

Example 22 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testRetrieveApplication.

@Test
public void testRetrieveApplication() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200
    // //mocked response object from dcr api
    DCRClientInfo dcrClientInfoResponse = new DCRClientInfo();
    dcrClientInfoResponse.setClientName("appx");
    List<String> grantTypesList = new ArrayList<>();
    grantTypesList.add("password");
    grantTypesList.add("client-credentials");
    dcrClientInfoResponse.setGrantTypes(grantTypesList);
    dcrClientInfoResponse.addCallbackUrl("https://sample.callback/url");
    dcrClientInfoResponse.setClientId(consumerKey);
    dcrClientInfoResponse.setClientSecret(consumerSecret);
    dcrClientInfoResponse.setClientIdIssuedAt("now");
    dcrClientInfoResponse.setClientSecretExpiresAt("future");
    dcrClientInfoResponse.setRegistrationClientUri("https://localhost:9443/oauth/xxx-xxx-xxx-xxx");
    // //expected response object from key manager
    OAuthApplicationInfo oAuthApplicationInfoResponse = new OAuthApplicationInfo();
    oAuthApplicationInfoResponse.setClientName(dcrClientInfoResponse.getClientName());
    oAuthApplicationInfoResponse.setGrantTypes(dcrClientInfoResponse.getGrantTypes());
    oAuthApplicationInfoResponse.setCallBackURL(dcrClientInfoResponse.getRedirectURIs().get(0));
    oAuthApplicationInfoResponse.setClientId(dcrClientInfoResponse.getClientId());
    oAuthApplicationInfoResponse.setClientSecret(dcrClientInfoResponse.getClientSecret());
    Response appGetResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(dcrClientInfoResponse), feign.Util.UTF_8).build();
    Mockito.when(dcrmServiceStub.getApplication(consumerKey)).thenReturn(appGetResponse);
    try {
        OAuthApplicationInfo app = kmImpl.retrieveApplication(consumerKey);
        Assert.assertEquals(app, oAuthApplicationInfoResponse);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - empty consumer key
    try {
        kmImpl.retrieveApplication("");
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to retrieve OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - empty consumer null
    try {
        kmImpl.retrieveApplication(null);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to retrieve OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - backend error
    String errorMsg = "unknown error occurred";
    Response errorResponse = Response.builder().status(500).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.getApplication(consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.retrieveApplication(consumerKey);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while retrieving DCR application."));
    }
}
Also used : ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) Test(org.testng.annotations.Test)

Example 23 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project product-iots by wso2.

the class UserManagement method testChangePassword.

@Test(description = "Test whether the API that is used to change the password works as expected.", dependsOnMethods = { "testRemoveUser" })
public void testChangePassword() throws Exception {
    String url = Constants.UserManagement.USER_ENDPOINT + "/credentials";
    HttpResponse response = client.put(url, PayloadGenerator.getJsonPayload(Constants.UserManagement.USER_PAYLOAD_FILE_NAME, Constants.UserManagement.RESET_PASSWORD_PAYLOAD).toString());
    Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode());
    Assert.assertEquals("Password of the user cannot be changed", "\"UserImpl password by " + "username: admin was successfully changed.\"", response.getData());
}
Also used : HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) Test(org.testng.annotations.Test)

Example 24 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project product-iots by wso2.

the class UserOperations method changePassword.

public static boolean changePassword(String username, String pwd) {
    HashMap<String, String> headers = new HashMap<String, String>();
    String pwdEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/admin/users/" + username + "/credentials";
    // Set the password payload
    JSONObject pwdData = new JSONObject();
    pwdData.put("newPassword", pwd);
    // Set the headers
    headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
    HTTPResponse httpResponse = HTTPInvoker.sendHTTPPostWithOAuthSecurity(pwdEndpoint, pwdData.toJSONString(), headers);
    if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
        return true;
    }
    return false;
}
Also used : JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) HTTPResponse(org.wso2.mdm.qsg.dto.HTTPResponse)

Example 25 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAmazonResourceNamesOfAPI.

// AWS Lambda: rest api operation to get ARNs
@Override
public Response getAmazonResourceNamesOfAPI(String apiId, MessageContext messageContext) {
    JSONObject arns = new JSONObject();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        String endpointConfigString = api.getEndpointConfig();
        if (!StringUtils.isEmpty(endpointConfigString)) {
            JSONParser jsonParser = new JSONParser();
            JSONObject endpointConfig = (JSONObject) jsonParser.parse(endpointConfigString);
            if (endpointConfig != null) {
                if (endpointConfig.containsKey(APIConstants.AMZN_ACCESS_KEY) && endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY) && endpointConfig.containsKey(APIConstants.AMZN_REGION)) {
                    String accessKey = (String) endpointConfig.get(APIConstants.AMZN_ACCESS_KEY);
                    String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
                    String region = (String) endpointConfig.get(APIConstants.AMZN_REGION);
                    AWSCredentialsProvider credentialsProvider;
                    AWSLambda awsLambda;
                    if (StringUtils.isEmpty(accessKey) && StringUtils.isEmpty(secretKey) && StringUtils.isEmpty(region)) {
                        credentialsProvider = DefaultAWSCredentialsProviderChain.getInstance();
                        awsLambda = AWSLambdaClientBuilder.standard().withCredentials(credentialsProvider).build();
                    } else if (!StringUtils.isEmpty(accessKey) && !StringUtils.isEmpty(secretKey) && !StringUtils.isEmpty(region)) {
                        if (secretKey.length() == APIConstants.AWS_ENCRYPTED_SECRET_KEY_LENGTH) {
                            CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                            secretKey = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
                        }
                        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
                        credentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
                        awsLambda = AWSLambdaClientBuilder.standard().withCredentials(credentialsProvider).withRegion(region).build();
                    } else {
                        log.error("Missing AWS Credentials");
                        return null;
                    }
                    ListFunctionsResult listFunctionsResult = awsLambda.listFunctions();
                    List<FunctionConfiguration> functionConfigurations = listFunctionsResult.getFunctions();
                    arns.put("count", functionConfigurations.size());
                    JSONArray list = new JSONArray();
                    for (FunctionConfiguration functionConfiguration : functionConfigurations) {
                        list.put(functionConfiguration.getFunctionArn());
                    }
                    arns.put("list", list);
                    return Response.ok().entity(arns.toString()).build();
                }
            }
        }
    } catch (SdkClientException e) {
        if (e.getCause() instanceof UnknownHostException) {
            arns.put("error", "No internet connection to connect the given access method.");
            log.error("No internet connection to connect the given access method of API : " + apiId, e);
            return Response.serverError().entity(arns.toString()).build();
        } else {
            arns.put("error", "Unable to access Lambda functions under the given access method.");
            log.error("Unable to access Lambda functions under the given access method of API : " + apiId, e);
            return Response.serverError().entity(arns.toString()).build();
        }
    } catch (ParseException e) {
        String errorMessage = "Error while parsing endpoint config of the API: " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (CryptoException | UnsupportedEncodingException e) {
        String errorMessage = "Error while decrypting the secret key of the API: " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving the API: " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : AWSLambda(com.amazonaws.services.lambda.AWSLambda) ListFunctionsResult(com.amazonaws.services.lambda.model.ListFunctionsResult) UnknownHostException(java.net.UnknownHostException) FunctionConfiguration(com.amazonaws.services.lambda.model.FunctionConfiguration) JSONArray(org.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) JSONObject(org.json.simple.JSONObject) SdkClientException(com.amazonaws.SdkClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) CryptoException(org.wso2.carbon.core.util.CryptoException) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 HttpClient (org.apache.http.client.HttpClient)12 URL (java.net.URL)10 ArrayList (java.util.ArrayList)9 HttpGet (org.apache.http.client.methods.HttpGet)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 HttpResponse (org.apache.http.HttpResponse)8 Gson (com.google.gson.Gson)6 JSONObject (org.json.simple.JSONObject)6 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Test (org.testng.annotations.Test)6 Response (feign.Response)4 WorkflowProperties (org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)4 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)3 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)3 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)3