use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.
the class DefaultIdentityProviderImplTestCase method testGetRoleNamesOfUser.
@Test
public void testGetRoleNamesOfUser() 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> roleNames = new ArrayList<>();
roleNames.add(roleName1);
roleNames.add(roleName2);
roleNames.add(roleName3);
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.getRoleNamesOfUser(validUserId);
Assert.assertEquals(roleNames.size(), roles.size());
roles.forEach(roleName -> Assert.assertTrue(roleNames.contains(roleName)));
// Error case - When response is null
String invalidUserIdResponseNull = "invalidUserId_Response_Null";
Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
try {
idpImpl.getRoleNamesOfUser(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.getRoleNamesOfUser(invalidUserIdNot200OK);
} catch (IdentityProviderException ex) {
Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role names 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.getRoleNamesOfUser(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.");
}
}
use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.
the class APIPublisherImpl method getAPIPermissionsOfLoggedInUser.
/**
* This method retrieves the set of overall permissions for a given api for the logged in user
*
* @param loggedInUserName - Logged in user
* @param api - The API whose permissions for the logged in user is retrieved
* @return The overall list of permissions for the given API for the logged in user
*/
private List<String> getAPIPermissionsOfLoggedInUser(String loggedInUserName, API api) throws APIManagementException {
Set<String> permissionArrayForUser = new HashSet<>();
Map<String, Integer> permissionMap = api.getPermissionMap();
String provider = api.getProvider();
// TODO: Remove the check for admin after IS adds an ID to admin user
if (loggedInUserName.equals(provider) || permissionMap == null || permissionMap.isEmpty() || "admin".equals(loggedInUserName)) {
permissionArrayForUser.add(APIMgtConstants.Permission.READ);
permissionArrayForUser.add(APIMgtConstants.Permission.UPDATE);
permissionArrayForUser.add(APIMgtConstants.Permission.DELETE);
permissionArrayForUser.add(APIMgtConstants.Permission.MANAGE_SUBSCRIPTION);
} else {
try {
String userId = getIdentityProvider().getIdOfUser(loggedInUserName);
List<String> loggedInUserRoles = getIdentityProvider().getRoleIdsOfUser(userId);
List<String> permissionRoleList = getRolesFromPermissionMap(permissionMap);
List<String> rolesOfUserWithAPIPermissions = null;
// To prevent a possible null pointer exception
if (loggedInUserRoles == null) {
loggedInUserRoles = new ArrayList<>();
}
// get the intersection - retainAll() transforms first set to the result of intersection
loggedInUserRoles.retainAll(permissionRoleList);
if (!loggedInUserRoles.isEmpty()) {
rolesOfUserWithAPIPermissions = loggedInUserRoles;
}
if (rolesOfUserWithAPIPermissions != null) {
Integer aggregatePermissions = 0;
// Calculating aggregate permissions using Bitwise OR operation
for (String role : rolesOfUserWithAPIPermissions) {
aggregatePermissions |= permissionMap.get(role);
}
permissionArrayForUser = new HashSet<>(APIUtils.constructApiPermissionsListForValue(aggregatePermissions));
}
} catch (IdentityProviderException e) {
String errorMsg = "Error occurred while calling SCIM endpoint to retrieve user " + loggedInUserName + "'s information";
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
}
}
List<String> finalAggregatedPermissionList = new ArrayList<>();
finalAggregatedPermissionList.addAll(permissionArrayForUser);
if (log.isDebugEnabled()) {
String message = "Aggregate permissions of user " + loggedInUserName + " for the API " + api.getName() + " are " + StringUtils.join(finalAggregatedPermissionList, ", ") + ".";
log.debug(message);
}
return finalAggregatedPermissionList;
}
use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testReplaceGroupNamesWithIdWithInvalidRoles.
@Test(description = "Update API when there is a list of invalid roles specified for permission")
public void testReplaceGroupNamesWithIdWithInvalidRoles() throws APIManagementException {
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
String permissionString = "[{\"groupId\" : \"developer\", \"permission\" : [\"READ\",\"UPDATE\"]}," + "{\"groupId\" : \"invalid_role\", \"permission\" : [\"READ\",\"UPDATE\",\"DELETE\"]}]";
String errorMessage = "There are invalid roles in the permission string";
API.APIBuilder api = SampleTestObjectCreator.createDefaultAPI().apiPermission(permissionString);
String uuid = api.getId();
GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
APIGateway gateway = Mockito.mock(APIGateway.class);
APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, apiLifecycleManager, gatewaySourceGenerator, gateway);
Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.lifeCycleStatus(APIStatus.CREATED.getStatus()).build());
Mockito.when(identityProvider.getRoleId("invalid_role")).thenThrow(new IdentityProviderException(errorMessage, ExceptionCodes.ROLE_DOES_NOT_EXIST));
Mockito.when(identityProvider.getRoleId(DEVELOPER_ROLE)).thenReturn(DEVELOPER_ROLE_ID);
Mockito.when(apiDAO.isAPIContextExists(api.getContext())).thenReturn(true);
String configString = SampleTestObjectCreator.createSampleGatewayConfig();
Mockito.when(apiDAO.getGatewayConfigOfAPI(uuid)).thenReturn(configString);
Mockito.when(apiDAO.getApiSwaggerDefinition(api.getId())).thenReturn(SampleTestObjectCreator.apiDefinition);
try {
apiPublisher.updateAPI(api.lifeCycleStatus(APIStatus.CREATED.getStatus()).id(uuid));
} catch (APIManagementException e) {
Assert.assertEquals(e.getMessage(), "There are invalid roles in the permission string");
}
}
Aggregations