use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIProviderImpl method getAPILifeCycleData.
@Override
public /*
* This method returns the lifecycle data for an API including current state,next states.
*
* @param apiId APIIdentifier
* @return Map<String,Object> a map with lifecycle data
*/
Map<String, Object> getAPILifeCycleData(APIIdentifier apiId) throws APIManagementException {
String path = APIUtil.getAPIPath(apiId);
Map<String, Object> lcData = new HashMap<String, Object>();
String providerTenantMode = apiId.getProviderName();
boolean isTenantFlowStarted = false;
try {
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerTenantMode));
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
Resource apiSourceArtifact = registry.get(path);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when getting lifecycle data for API " + apiId;
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
GenericArtifact artifact = artifactManager.getGenericArtifact(apiSourceArtifact.getUUID());
// Get all the actions corresponding to current state of the api artifact
String[] actions = artifact.getAllLifecycleActions(APIConstants.API_LIFE_CYCLE);
// Put next states into map
lcData.put(APIConstants.LC_NEXT_STATES, actions);
String lifeCycleState = artifact.getLifecycleState();
lcData.put(APIConstants.LC_STATUS, lifeCycleState);
LifecycleBean bean;
bean = LifecycleBeanPopulator.getLifecycleBean(path, (UserRegistry) registry, configRegistry);
if (bean != null) {
ArrayList<CheckListItem> checkListItems = new ArrayList<CheckListItem>();
ArrayList<String> permissionList = new ArrayList<String>();
// Get lc properties
Property[] lifecycleProps = bean.getLifecycleProperties();
// Get roles of the current session holder
String[] roleNames = bean.getRolesOfUser();
for (Property property : lifecycleProps) {
String propName = property.getKey();
String[] propValues = property.getValues();
// Check for permission properties if any exists
if (propValues != null && propValues.length != 0) {
if (propName.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propName.endsWith(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX) && propName.contains(APIConstants.API_LIFE_CYCLE)) {
for (String role : roleNames) {
for (String propValue : propValues) {
String key = propName.replace(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX, "").replace(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX, "");
if (propValue.equals(role)) {
permissionList.add(key);
} else if (propValue.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propValue.endsWith(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX)) {
permissionList.add(key);
}
}
}
}
}
}
// Check for lifecycle checklist item properties defined
for (Property property : lifecycleProps) {
String propName = property.getKey();
String[] propValues = property.getValues();
if (propValues != null && propValues.length != 0) {
CheckListItem checkListItem = new CheckListItem();
checkListItem.setVisible("false");
if (propName.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propName.endsWith(APIConstants.LC_PROPERTY_ITEM_SUFFIX) && propName.contains(APIConstants.API_LIFE_CYCLE)) {
if (propValues.length > 2) {
for (String param : propValues) {
if (param.startsWith(APIConstants.LC_STATUS)) {
checkListItem.setLifeCycleStatus(param.substring(7));
} else if (param.startsWith(APIConstants.LC_CHECK_ITEM_NAME)) {
checkListItem.setName(param.substring(5));
} else if (param.startsWith(APIConstants.LC_CHECK_ITEM_VALUE)) {
checkListItem.setValue(param.substring(6));
} else if (param.startsWith(APIConstants.LC_CHECK_ITEM_ORDER)) {
checkListItem.setOrder(param.substring(6));
}
}
}
String key = propName.replace(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX, "").replace(APIConstants.LC_PROPERTY_ITEM_SUFFIX, "");
if (permissionList.contains(key)) {
// Set visible to true if the checklist item permits
checkListItem.setVisible("true");
}
}
if (checkListItem.matchLifeCycleStatus(lifeCycleState)) {
checkListItems.add(checkListItem);
}
}
}
lcData.put("items", checkListItems);
}
} catch (Exception e) {
handleException(e.getMessage(), e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return lcData;
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIProviderImpl method checkAccessControlPermission.
/* To check authorization of the API against current logged in user. If the user is not authorized an exception
* will be thrown.
*
* @param identifier API identifier
* @throws APIManagementException APIManagementException
*/
protected void checkAccessControlPermission(Identifier identifier) throws APIManagementException {
if (identifier == null || !isAccessControlRestrictionEnabled) {
if (!isAccessControlRestrictionEnabled && log.isDebugEnabled()) {
log.debug("Publisher access control restriction is not enabled. Hence the API " + identifier + " can be editable and viewable by all the API publishers and creators.");
}
return;
}
String resourcePath = StringUtils.EMPTY;
String identifierType = StringUtils.EMPTY;
if (identifier instanceof APIIdentifier) {
resourcePath = APIUtil.getAPIPath((APIIdentifier) identifier);
identifierType = APIConstants.API_IDENTIFIER_TYPE;
} else if (identifier instanceof APIProductIdentifier) {
resourcePath = APIUtil.getAPIProductPath((APIProductIdentifier) identifier);
identifierType = APIConstants.API_PRODUCT_IDENTIFIER_TYPE;
}
try {
Registry sysRegistry = getRegistryService().getGovernanceSystemRegistry();
// Need user name with tenant domain to get correct domain name from
// MultitenantUtils.getTenantDomain(username)
String userNameWithTenantDomain = (userNameWithoutChange != null) ? userNameWithoutChange : username;
if (!sysRegistry.resourceExists(resourcePath)) {
if (log.isDebugEnabled()) {
log.debug("Resource does not exist in the path : " + resourcePath + " this can happen if this is in the " + "middle of the new " + identifierType + " creation, hence not checking the access control");
}
return;
}
Resource resource = sysRegistry.get(resourcePath);
if (resource == null) {
return;
}
String accessControlProperty = resource.getProperty(APIConstants.ACCESS_CONTROL);
if (accessControlProperty == null || accessControlProperty.trim().isEmpty() || accessControlProperty.equalsIgnoreCase(APIConstants.NO_ACCESS_CONTROL)) {
if (log.isDebugEnabled()) {
log.debug(identifierType + " in the path " + resourcePath + " does not have any access control restriction");
}
return;
}
if (APIUtil.hasPermission(userNameWithTenantDomain, APIConstants.Permissions.APIM_ADMIN)) {
return;
}
String publisherAccessControlRoles = resource.getProperty(APIConstants.DISPLAY_PUBLISHER_ROLES);
if (publisherAccessControlRoles != null && !publisherAccessControlRoles.trim().isEmpty()) {
String[] accessControlRoleList = publisherAccessControlRoles.replaceAll("\\s+", "").split(",");
if (log.isDebugEnabled()) {
log.debug(identifierType + " has restricted access to creators and publishers with the roles : " + Arrays.toString(accessControlRoleList));
}
String[] userRoleList = APIUtil.getListOfRoles(userNameWithTenantDomain);
if (log.isDebugEnabled()) {
log.debug("User " + username + " has roles " + Arrays.toString(userRoleList));
}
for (String role : accessControlRoleList) {
if (!role.equalsIgnoreCase(APIConstants.NULL_USER_ROLE_LIST) && APIUtil.compareRoleList(userRoleList, role)) {
return;
}
}
if (log.isDebugEnabled()) {
log.debug(identifierType + " " + identifier + " cannot be accessed by user '" + username + "'. It " + "has a publisher access control restriction");
}
throw new APIManagementException(APIConstants.UN_AUTHORIZED_ERROR_MESSAGE + " view or modify the " + identifierType + " " + identifier);
}
} catch (RegistryException e) {
throw new APIManagementException("Registry Exception while trying to check the access control restriction of " + identifierType + " " + identifier.getName(), e);
}
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIThrottleHandlerTest method testMsgThrottleOutWhenApplicationLevelQuotaExceeded.
@Test
public void testMsgThrottleOutWhenApplicationLevelQuotaExceeded() throws XMLStreamException, ThrottleException {
concurrentAccessController = new ConcurrentAccessController(100);
configurationContext.setProperty(throttleKey, concurrentAccessController);
AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
authenticationContext.setApplicationTier("Silver");
((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 0, 60000, "true"), THROTTLE_POLICY_KEY, true, 0, messageContext);
TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 0, 60000, "true"), THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
messageContext.setProperty(RESPONSE, "false");
messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
apiThrottleHandler.setId(throttleID);
Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
Mockito.when(throttleConfiguration.getCallerConfiguration(Mockito.anyString())).thenReturn(callerConfiguration);
// Set application level access state to be ACCESS_DENIED
Mockito.when(callerConfiguration.getAccessState()).thenReturn(1);
Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIThrottleHandlerTest method testMsgThrottleOutWhenHardLevelQuotaExceededForProductionEndpoint.
@Test
public void testMsgThrottleOutWhenHardLevelQuotaExceededForProductionEndpoint() throws XMLStreamException, ThrottleException {
concurrentAccessController = new ConcurrentAccessController(100);
configurationContext.setProperty(throttleKey, concurrentAccessController);
AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
authenticationContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
messageContext.setProperty(APIConstants.VERB_INFO_DTO, new VerbInfoDTO());
((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000, "true"), THROTTLE_POLICY_KEY, true, 0, messageContext);
TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000, "true"), THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
messageContext.setProperty(RESPONSE, "false");
apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
apiThrottleHandler.setId(throttleID);
apiThrottleHandler.setProductionMaxCount(PRODUCTION_MAX_COUNT);
Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
Mockito.when(throttleConfiguration.getCallerConfiguration(Mockito.anyString())).thenReturn(callerConfiguration);
Mockito.when(callerConfiguration.getAccessState()).thenReturn(1);
Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.
the class APIUtil method getFilteredUserRoles.
public static String[] getFilteredUserRoles(String username) throws APIManagementException {
String[] userRoles = APIUtil.getListOfRoles(username);
String skipRolesByRegex = APIUtil.getSkipRolesByRegex();
if (StringUtils.isNotEmpty(skipRolesByRegex)) {
List<String> filteredUserRoles = new ArrayList<>(Arrays.asList(userRoles));
String[] regexList = skipRolesByRegex.split(",");
for (int i = 0; i < regexList.length; i++) {
Pattern p = Pattern.compile(regexList[i]);
Iterator<String> itr = filteredUserRoles.iterator();
while (itr.hasNext()) {
String role = itr.next();
Matcher m = p.matcher(role);
if (m.matches()) {
itr.remove();
}
}
}
userRoles = filteredUserRoles.toArray(new String[0]);
}
return userRoles;
}
Aggregations