Search in sources :

Example 1 with ErrorResponse

use of org.wso2.carbon.identity.api.server.common.error.ErrorResponse in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetIdOfUser.

@Test
public void testGetIdOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("invalid_user")).thenReturn("invalid_user");
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("John")).thenReturn("John");
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("invalid_user_giving_null_response")).thenReturn("invalid_user_giving_null_response");
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserName = "John";
    final String validUserSearchQuery = "userName Eq " + validUserName;
    final String expectedUserId = "cfbde56e-8422-498e-b6dc-85a6f1f8b058";
    String invalidUserName = "invalid_user";
    final String invalidUserSearchQuery = "userName Eq " + invalidUserName;
    String userReturningNullResponse = "invalid_user_giving_null_response";
    final String userReturningNullResponseSearchQuery = "userName Eq " + userReturningNullResponse;
    // happy path
    String responseBody = "{\"totalResults\":1,\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"Resources\":" + "[{\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/cfbde56e-8422-498e-b6dc-85a6f1f8b058\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"id\":\"cfbde56e-8422-498e-b6dc-85a6f1f8b058\",\"userName\":\"John\"}]}";
    Response createdResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(responseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchUsers(validUserSearchQuery)).thenReturn(createdResponse);
    try {
        String userId = idpImpl.getIdOfUser(validUserName);
        Assert.assertEquals(userId, expectedUserId);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    // Assuming the user cannot be found - When the request did not return a 200 OK response
    String errorResponse = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response createdResponseNoSuchUser = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponse.getBytes()).build();
    Mockito.when(scimServiceStub.searchUsers(invalidUserSearchQuery)).thenReturn(createdResponseNoSuchUser);
    try {
        idpImpl.getIdOfUser(invalidUserName);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of user " + invalidUserName + ". Error : User not found in the user store.");
    }
    // error path
    // Assuming the response is null
    Mockito.when(scimServiceStub.searchUsers(userReturningNullResponseSearchQuery)).thenReturn(null);
    try {
        idpImpl.getIdOfUser(userReturningNullResponse);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of user " + userReturningNullResponse + ". Error : Response is null.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 2 with ErrorResponse

use of org.wso2.carbon.identity.api.server.common.error.ErrorResponse in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleIdsOfUser.

@Test
public void testGetRoleIdsOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserId = "a42b4760-120d-432e-8042-4a7f12e3346c";
    String roleName1 = "subscriber";
    String roleId1 = "fb5aaf9c-1fdf-4b2d-86bc-6e3203b99618";
    String roleName2 = "manager";
    String roleId2 = "097435bc-c460-402b-9137-8ab65fd28c3e";
    String roleName3 = "engineer";
    String roleId3 = "ac093278-9343-466c-8a71-af47921a575b";
    List<String> roleIds = new ArrayList<>();
    roleIds.add(roleId1);
    roleIds.add(roleId2);
    roleIds.add(roleId3);
    String successResponseBody = "{\"emails\":[{\"type\":\"home\",\"value\":\"john_home.com\"},{\"type\":\"work\"" + ",\"value\":\"john_work.com\"}],\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/" + validUserId + "\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"name\":{\"familyName\":" + "\"Smith\",\"givenName\":\"John\"},\"groups\":[{\"display\":\"" + roleName1 + "\",\"value\":\"" + roleId1 + "\"},{\"display\":\"" + roleName2 + "\",\"value\":\"" + roleId2 + "\"},{\"display\":\"" + roleName3 + "\",\"value\":\"" + roleId3 + "\"}],\"id\":\"" + validUserId + "\",\"userName\":" + "\"John\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(validUserId)).thenReturn(successfulResponse);
    List<String> roles = idpImpl.getRoleIdsOfUser(validUserId);
    Assert.assertEquals(roleIds.size(), roles.size());
    roles.forEach(roleId -> Assert.assertTrue(roleIds.contains(roleId)));
    // Error case - When response is null
    String invalidUserIdResponseNull = "invalidUserId_Response_Null";
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with Id " + invalidUserIdResponseNull + ". Error : Response is null.");
    }
    // Error case - When the request did not return a 200 OK response
    String invalidUserIdNot200OK = "invalidUserId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response errorResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role Ids of user with Id " + invalidUserIdNot200OK + ". Error : User not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidUserIdResponseEmpty = "invalidUserId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with user Id " + invalidUserIdResponseEmpty + " from SCIM endpoint. Response body is null or empty.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) ArrayList(java.util.ArrayList) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 3 with ErrorResponse

use of org.wso2.carbon.identity.api.server.common.error.ErrorResponse in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testRevokeToken.

// TODO:Enable after revoke endpoint implementation done in key manager.
@Test(enabled = false)
public void testRevokeToken() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.RevokeServiceStub revokeStub = Mockito.mock(OAuth2ServiceStubs.RevokeServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200
    Response revokeTokenResponse = Response.builder().status(200).headers(new HashMap<>()).build();
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    final String revokeToken = "xxx-revoke-token-xxx";
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(revokeTokenResponse);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - response is null
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(null);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Error occurred while revoking current access token. " + "Response is null"));
    }
    // error case - token response non-200
    final int errorCode = 500;
    Response errorResponse = Response.builder().status(errorCode).headers(new HashMap<>()).body("backend error occurred", Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(errorResponse);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Token revocation failed. HTTP error code: " + errorCode));
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) HashMap(java.util.HashMap) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) 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) Test(org.testng.annotations.Test)

Example 4 with ErrorResponse

use of org.wso2.carbon.identity.api.server.common.error.ErrorResponse in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testDeleteApplication.

@Test
public void testDeleteApplication() 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 - 204
    Response okResponse = Response.builder().status(204).headers(new HashMap<>()).build();
    Mockito.when(dcrmServiceStub.deleteApplication(consumerKey)).thenReturn(okResponse);
    try {
        kmImpl.deleteApplication(consumerKey);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - empty consumer key
    try {
        kmImpl.deleteApplication("");
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to delete OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - empty consumer null
    try {
        kmImpl.deleteApplication(null);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to delete OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - non-204
    String errorMsg = "unknown error occurred";
    Response errorResponse = Response.builder().status(500).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.deleteApplication(consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.deleteApplication(consumerKey);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while deleting DCR application."));
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) HashMap(java.util.HashMap) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) 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) Test(org.testng.annotations.Test)

Example 5 with ErrorResponse

use of org.wso2.carbon.identity.api.server.common.error.ErrorResponse in project identity-test-integration by wso2-incubator.

the class ProxyUtils method handleResponse.

/**
 * creates the response to be sent to the calling application, by the API.
 *
 * @param responseStatus
 * @param code
 * @param name
 * @param detail
 * @return
 */
public static Response handleResponse(ProxyUtils.OperationStatus responseStatus, String code, String name, String detail) {
    Response response;
    String message = name;
    ErrorResponse resp = new ErrorResponse(code, name, detail);
    switch(responseStatus) {
        case CREATED:
            response = Response.created(URI.create(message)).build();
            break;
        case SUCCESS:
            response = Response.ok().entity(resp).build();
            break;
        case BAD_REQUEST:
            response = Response.status(HttpStatus.SC_BAD_REQUEST).entity(resp).build();
            break;
        case NOT_FOUND:
            response = Response.status(HttpStatus.SC_NOT_FOUND).entity(resp).build();
            break;
        case FORBIDDEN:
            response = Response.status(HttpStatus.SC_UNAUTHORIZED).entity(resp).build();
            break;
        case INTERNAL_SERVER_ERROR:
            response = Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(resp).build();
            break;
        default:
            response = Response.noContent().build();
    }
    if (log.isDebugEnabled()) {
        log.debug(resp.toString());
    }
    return response;
}
Also used : ErrorResponse(org.wso2.carbon.identity.oauth.proxy.bean.ErrorResponse) Response(javax.ws.rs.core.Response) ErrorResponse(org.wso2.carbon.identity.oauth.proxy.bean.ErrorResponse)

Aggregations

APIError (org.wso2.carbon.identity.api.server.common.error.APIError)47 ErrorResponse (org.wso2.carbon.identity.api.server.common.error.ErrorResponse)47 Response (javax.ws.rs.core.Response)44 Test (org.testng.annotations.Test)12 Response (feign.Response)11 ArrayList (java.util.ArrayList)6 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)6 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)6 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)6 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)6 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)6 HashMap (java.util.HashMap)5 UserNameMapper (org.wso2.carbon.apimgt.core.api.UserNameMapper)5 SCIMServiceStub (org.wso2.carbon.apimgt.core.auth.SCIMServiceStub)5 IdentityProviderException (org.wso2.carbon.apimgt.core.exception.IdentityProviderException)5 ConnectionEstablishedResponse (org.wso2.carbon.identity.api.server.userstore.v1.model.ConnectionEstablishedResponse)4 UserStoreAttributeMappingResponse (org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreAttributeMappingResponse)4 UserStoreListResponse (org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreListResponse)4 UserStoreResponse (org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreResponse)4 Gson (com.google.gson.Gson)3