use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testDeleteApiWhenUserHasNoDeletePermission.
@Test(description = "Delete API when the logged in user has no delete permission for the API")
public void testDeleteApiWhenUserHasNoDeletePermission() throws APIManagementException, LifecycleException, SQLException {
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
APISubscriptionDAO apiSubscriptionDAO = Mockito.mock(APISubscriptionDAO.class);
APIBuilder builder = SampleTestObjectCreator.createDefaultAPI();
API api = builder.build();
String uuid = api.getId();
Mockito.when(apiSubscriptionDAO.getSubscriptionCountByAPI(uuid)).thenReturn(0L);
APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
APIGateway gateway = Mockito.mock(APIGateway.class);
IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
LabelDAO labelDao = Mockito.mock(LabelDAO.class);
APIPublisherImpl apiPublisher = getApiPublisherImpl(ALTERNATIVE_USER, identityProvider, apiDAO, apiSubscriptionDAO, apiLifecycleManager, gateway, labelDao);
Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api);
// Assuming the user role list retrieved from IS is null
Mockito.when(identityProvider.getIdOfUser(ALTERNATIVE_USER)).thenReturn(USER_ID);
Mockito.when(identityProvider.getRoleIdsOfUser(USER_ID)).thenReturn(null);
Mockito.when(apiDAO.getApiSwaggerDefinition(api.getId())).thenReturn(SampleTestObjectCreator.apiDefinition);
try {
apiPublisher.deleteAPI(uuid);
} catch (APIManagementException ex) {
Assert.assertEquals(ex.getMessage(), "The user " + ALTERNATIVE_USER + " does not have permission to delete the api " + api.getName());
}
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class ApisApiServiceImplTestCase method testApisApiIdScopesNamePutException.
@Test
public void testApisApiIdScopesNamePutException() throws Exception {
printTestMethodName();
ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
APIPublisher apiPublisher = Mockito.mock(APIPublisherImpl.class);
PowerMockito.mockStatic(RestAPIPublisherUtil.class);
PowerMockito.when(RestAPIPublisherUtil.getApiPublisher(USER)).thenReturn(apiPublisher);
String apiId = UUID.randomUUID().toString();
Scope scope = new Scope("apim:api_view", "api view");
Mockito.doThrow(new APIManagementException("Scope couldn't found by name: apim:api_view", ExceptionCodes.SCOPE_NOT_FOUND)).when(apiPublisher).updateScopeOfTheApi(apiId, scope);
Response response = apisApiService.apisApiIdScopesNamePut(apiId, "apim:api_view", MappingUtil.scopeDto(scope, "role"), null, null, getRequest());
assertEquals(response.getStatus(), 404);
assertTrue(response.getEntity().toString().contains("Scope not found"));
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class ApisApiServiceImplTestCase method testApisApiIdScopesPost.
@Test
public void testApisApiIdScopesPost() throws Exception {
printTestMethodName();
ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
APIPublisher apiPublisher = Mockito.mock(APIPublisherImpl.class);
PowerMockito.mockStatic(RestAPIPublisherUtil.class);
PowerMockito.when(RestAPIPublisherUtil.getApiPublisher(USER)).thenReturn(apiPublisher);
String apiId = UUID.randomUUID().toString();
Scope scope = new Scope("api_view", "api view");
Mockito.doNothing().when(apiPublisher).addScopeToTheApi(apiId, scope);
Response response = apisApiService.apisApiIdScopesPost(apiId, MappingUtil.scopeDto(scope, "role"), null, null, getRequest());
assertEquals(response.getStatus(), 201);
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIPublisherImpl method replaceGroupNamesWithId.
/**
* This method replaces the groupId field's value to the role id instead of the name passed by the user
*
* @param permissionString - the permission json string which contains role names in groupId field
* @return permission string with replaced groupId
* @throws ParseException - if there is an error parsing the json string
* @throws APIManagementException - if there is an error getting the IdentityProvider instance
*/
private String replaceGroupNamesWithId(String permissionString) throws ParseException, APIManagementException {
JSONArray updatedPermissionArray = new JSONArray();
JSONParser jsonParser = new JSONParser();
JSONArray originalPermissionArray = (JSONArray) jsonParser.parse(permissionString);
try {
for (Object permissionObj : originalPermissionArray) {
JSONObject jsonObject = (JSONObject) permissionObj;
String groupName = (String) jsonObject.get(APIMgtConstants.Permission.GROUP_ID);
String groupId = getIdentityProvider().getRoleId(groupName);
JSONObject updatedPermissionJsonObj = new JSONObject();
updatedPermissionJsonObj.put(APIMgtConstants.Permission.GROUP_ID, groupId);
updatedPermissionJsonObj.put(APIMgtConstants.Permission.PERMISSION, jsonObject.get(APIMgtConstants.Permission.PERMISSION));
updatedPermissionArray.add(updatedPermissionJsonObj);
}
} catch (IdentityProviderException e) {
String errorMessage = "There are invalid roles in the permission string";
log.error(errorMessage, e);
throw new APIManagementException(errorMessage, e, ExceptionCodes.UNSUPPORTED_ROLE);
}
return updatedPermissionArray.toJSONString();
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIPublisherImpl method updateAPI.
/**
* Updates design and implementation of an existing API. This method must not be used to change API status.
* Implementations should throw an exceptions when such attempts are made. All life cycle state changes
* should be carried out using the changeAPIStatus method of this interface.
*
* @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
* @throws APIManagementException if failed to update API
*/
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
APIGateway gateway = getApiGateway();
apiBuilder.provider(getUsername());
apiBuilder.updatedBy(getUsername());
try {
API originalAPI = getAPIbyUUID(apiBuilder.getId());
if (originalAPI != null) {
// Checks whether the logged in user has the "UPDATE" permission for the API
verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
apiBuilder.createdTime(originalAPI.getCreatedTime());
// workflow status is an internal property and shouldn't be allowed to update externally
apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
Map<String, Integer> roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
apiBuilder.permissionMap(roleNamePermissionList);
}
Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
validateEndpoints(apiEndpointMap, true);
validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
createUriTemplateList(apiBuilder, true);
validateApiPolicy(apiBuilder.getApiPolicy());
validateSubscriptionPolicies(apiBuilder);
String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
API api = apiBuilder.build();
// Add API to gateway
gateway.updateAPI(api);
if (log.isDebugEnabled()) {
log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
}
if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
if (!checkIfAPIContextExists(api.getContext())) {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> availableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
} else {
throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
}
} else {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
}
if (log.isDebugEnabled()) {
log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
// 'API_M Functions' related code
// Create a payload with event specific details
Map<String, String> eventPayload = new HashMap<>();
eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
// This will notify all the EventObservers(Asynchronous)
ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
}
} else {
APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
}
} else {
log.error("Couldn't found API with ID " + apiBuilder.getId());
throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
}
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (ParseException e) {
String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
} catch (GatewayException e) {
String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
}
}
Aggregations