use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class APIUtil method setResourcePermissions.
/**
* This function is to set resource permissions based on its visibility
*
* @param visibility API/Product visibility
* @param roles Authorized roles
* @param artifactPath API/Product resource path
* @param registry Registry
* @throws APIManagementException Throwing exception
*/
public static void setResourcePermissions(String username, String visibility, String[] roles, String artifactPath, Registry registry) throws APIManagementException {
try {
String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
Resource registryResource = null;
if (registry != null && registry.resourceExists(artifactPath)) {
registryResource = registry.get(artifactPath);
}
StringBuilder publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
if (registryResource != null) {
String publisherRole = registryResource.getProperty(APIConstants.PUBLISHER_ROLES);
if (publisherRole != null) {
publisherAccessRoles = new StringBuilder(publisherRole);
}
if (StringUtils.isEmpty(publisherAccessRoles.toString())) {
publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
}
if (APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(visibility) || APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
// set publisher
publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
// access roles null since store visibility is global. We do not need to add any roles to
// store_view_role property.
} else {
registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
}
}
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
// calculate resource path
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
resourcePath = authorizationManager.computePathOnMount(resourcePath);
org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
boolean isRoleEveryOne = false;
/*If no roles have defined, authorize for everyone role */
if (roles != null) {
if (roles.length == 1 && "".equals(roles[0])) {
authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
isRoleEveryOne = true;
} else {
for (String role : roles) {
if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
isRoleEveryOne = true;
}
authManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
publisherAccessRoles.append(",").append(role.trim().toLowerCase());
}
}
}
if (!isRoleEveryOne) {
authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
}
authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
/*If no roles have defined, deny access for everyone & anonymous role */
if (roles == null) {
authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} else {
for (String role : roles) {
authManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
}
}
} else {
authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
}
} else {
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
boolean isRoleEveryOne = false;
if (roles != null) {
for (String role : roles) {
if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
isRoleEveryOne = true;
}
authorizationManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
publisherAccessRoles.append(",").append(role.toLowerCase());
}
}
if (!isRoleEveryOne) {
authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
}
authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
/*If no roles have defined, deny access for everyone & anonymous role */
if (roles == null) {
authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} else {
for (String role : roles) {
authorizationManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Store view roles for " + artifactPath + " : " + publisherAccessRoles.toString());
}
authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
}
}
if (registryResource != null) {
registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
registry.put(artifactPath, registryResource);
}
} catch (UserStoreException e) {
throw new APIManagementException("Error while adding role permissions to API", e);
} catch (RegistryException e) {
throw new APIManagementException("Registry exception while adding role permissions to API", e);
}
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class APIConsumerImpl method isCandidateAPI.
private boolean isCandidateAPI(String apiPath, String loggedUsername, GenericArtifactManager artifactManager, int tenantId, boolean showAllAPIs, boolean allowMultipleVersions, String apiOwner, String providerId, Registry registry, Map<String, API> apiCollection) throws UserStoreException, RegistryException, APIManagementException {
AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
Comparator<API> versionComparator = new APIVersionComparator();
Resource resource;
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
boolean checkAuthorized;
String userNameWithoutDomain = loggedUsername;
if (!loggedUsername.isEmpty() && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(super.tenantDomain)) {
String[] nameParts = loggedUsername.split("@");
userNameWithoutDomain = nameParts[0];
}
int loggedInUserTenantDomain = -1;
if (!StringUtils.isEmpty(loggedUsername)) {
loggedInUserTenantDomain = APIUtil.getTenantId(loggedUsername);
}
if (loggedUsername.isEmpty()) {
// Anonymous user is viewing.
checkAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} else if (tenantId != loggedInUserTenantDomain) {
// Cross tenant scenario
providerId = APIUtil.replaceEmailDomainBack(providerId);
String[] nameParts = providerId.split("@");
String provideNameWithoutDomain = nameParts[0];
checkAuthorized = manager.isUserAuthorized(provideNameWithoutDomain, path, ActionConstants.GET);
} else {
// Some user is logged in also user and api provider tenant domain are same.
checkAuthorized = manager.isUserAuthorized(userNameWithoutDomain, path, ActionConstants.GET);
}
String apiArtifactId = null;
if (checkAuthorized) {
resource = registry.get(apiPath);
apiArtifactId = resource.getUUID();
}
if (apiArtifactId != null) {
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
// check the API status
String status = APIUtil.getLcStateFromArtifact(artifact);
API api = null;
// Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
if (!showAllAPIs) {
// then we are only interested in published APIs here...
if (APIConstants.PUBLISHED.equals(status)) {
api = APIUtil.getAPI(artifact);
}
} else {
// else we are interested in both deprecated/published APIs here...
if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
api = APIUtil.getAPI(artifact);
}
}
if (api != null) {
String apiVisibility = api.getVisibility();
if (!StringUtils.isEmpty(apiVisibility) && !APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(apiVisibility)) {
String providerDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerId));
String loginUserDomain = MultitenantUtils.getTenantDomain(loggedUsername);
if (!StringUtils.isEmpty(providerDomain) && !StringUtils.isEmpty(loginUserDomain) && !providerDomain.equals(loginUserDomain)) {
return false;
}
}
// apiOwner is the value coming from front end and compared against the API instance
if (apiOwner != null && !apiOwner.isEmpty()) {
if (APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && api.getApiOwner() != null && !api.getApiOwner().isEmpty() && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
// reject remote APIs when local admin user's API selected
return false;
} else if (!APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
// reject local admin's APIs when remote API selected
return false;
}
}
String key;
// Check the configuration to allow showing multiple versions of an API true/false
if (!allowMultipleVersions) {
// If allow only showing the latest version of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = apiCollection.get(key);
if (existingAPI != null) {
// this one has a higher version number
if (versionComparator.compare(api, existingAPI) > 0) {
apiCollection.put(key, api);
return true;
}
} else {
// We haven't seen this API before
apiCollection.put(key, api);
return true;
}
} else {
// If allow showing multiple versions of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName() + COLON_CHAR + api.getId().getVersion();
// we're not really interested in the key, so generate one for the sake of adding this element to
// the map.
key = key + '_' + apiCollection.size();
apiCollection.put(key, api);
return true;
}
}
}
return false;
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class APIManagerComponentTest method testShouldActivateWhenAllPrerequisitesMet.
@Test
public void testShouldActivateWhenAllPrerequisitesMet() throws Exception {
PowerMockito.mockStatic(APIMgtDBUtil.class);
PowerMockito.mockStatic(APIUtil.class);
PowerMockito.mockStatic(AuthorizationUtils.class);
PowerMockito.mockStatic(RegistryUtils.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
PowerMockito.mockStatic(SQLConstantManagerFactory.class);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
ComponentContext componentContext = Mockito.mock(ComponentContext.class);
BundleContext bundleContext = Mockito.mock(BundleContext.class);
APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);
APIManagerConfigurationService configurationService = Mockito.mock(APIManagerConfigurationService.class);
AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
Registry registry = Mockito.mock(Registry.class);
RealmService realmService = Mockito.mock(RealmService.class);
UserRealm userRealm = Mockito.mock(UserRealm.class);
OutputEventAdapterService adapterService = Mockito.mock(OutputEventAdapterService.class);
ThrottleProperties throttleProperties = new ThrottleProperties();
Mockito.doNothing().when(configuration).load(Mockito.anyString());
Mockito.doNothing().when(authManager).authorizeRole(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
Mockito.doNothing().when(adapterService).create(null);
Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("").thenReturn(null);
Mockito.when(bundleContext.registerService("", CommonConfigDeployer.class, null)).thenReturn(null);
Mockito.when(authManager.isRoleAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(configurationService);
Mockito.when(serviceReferenceHolder.getOutputEventAdapterService()).thenReturn(adapterService);
Mockito.when(configurationService.getAPIManagerConfiguration()).thenReturn(configuration);
Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
Mockito.when(configuration.getThrottleProperties()).thenReturn(throttleProperties);
PowerMockito.doNothing().when(APIMgtDBUtil.class, "initialize");
PowerMockito.doNothing().when(APIUtil.class, "loadTenantExternalStoreConfig", Mockito.anyString());
PowerMockito.doNothing().when(AuthorizationUtils.class, "addAuthorizeRoleListener", Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
PowerMockito.doNothing().when(SQLConstantManagerFactory.class, "initializeSQLConstantManager");
PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);
PowerMockito.mockStatic(ApiMgtDAO.class);
ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
APIManagerComponent apiManagerComponent = new APIManagerComponentWrapper(registry);
GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
eventHubConfigurationDto.setEnabled(true);
eventHubConfigurationDto.setInitDelay(0);
eventHubConfigurationDto.setUsername("a");
eventHubConfigurationDto.setPassword("sss".toCharArray());
eventHubConfigurationDto.setServiceUrl("https://localhost");
EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration = new EventHubConfigurationDto.EventHubPublisherConfiguration();
eventHubConfigurationDto.setEventHubPublisherConfiguration(eventHubPublisherConfiguration);
Mockito.when(config.getEventHubConfigurationDto()).thenReturn(eventHubConfigurationDto);
try {
apiManagerComponent.activate(componentContext);
} catch (FileNotFoundException f) {
// Exception thrown here means that method was continued without the configuration file
Assert.fail("Should not throw an exception");
}
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class TestUtils method mockRegistryAndUserRealm.
public static ServiceReferenceHolder mockRegistryAndUserRealm(int tenantId) throws UserStoreException, RegistryException, XMLStreamException {
ServiceReferenceHolder sh = getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tm = Mockito.mock(TenantManager.class);
PowerMockito.when(sh.getRealmService()).thenReturn(realmService);
PowerMockito.when(realmService.getTenantManager()).thenReturn(tm);
RegistryService registryService = Mockito.mock(RegistryService.class);
PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
UserRegistry userReg = Mockito.mock(UserRegistry.class);
PowerMockito.when(registryService.getGovernanceUserRegistry()).thenReturn(userReg);
UserRegistry systemReg = Mockito.mock(UserRegistry.class);
PowerMockito.when(registryService.getConfigSystemRegistry()).thenReturn(systemReg);
UserRealm userRealm = Mockito.mock(UserRealm.class);
UserRealm bootstrapRealm = Mockito.mock(UserRealm.class);
PowerMockito.when(systemReg.getUserRealm()).thenReturn(userRealm);
PowerMockito.doNothing().when(ServiceReferenceHolder.class);
ServiceReferenceHolder.setUserRealm(userRealm);
org.wso2.carbon.user.api.UserRealm userR = Mockito.mock(org.wso2.carbon.user.api.UserRealm.class);
PowerMockito.when(realmService.getTenantUserRealm(-1234)).thenReturn(userR);
AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
PowerMockito.when(userR.getAuthorizationManager()).thenReturn(authManager);
PowerMockito.when(realmService.getBootstrapRealm()).thenReturn(bootstrapRealm);
ServiceReferenceHolder.setUserRealm(bootstrapRealm);
PowerMockito.when(tm.getTenantId(Matchers.anyString())).thenReturn(tenantId);
return sh;
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class APIManagerComponent method setupImagePermissions.
private void setupImagePermissions() throws APIManagementException {
try {
AuthorizationManager accessControlAdmin = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getAuthorizationManager();
String imageLocation = APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_IMAGE_LOCATION;
if (!accessControlAdmin.isRoleAuthorized(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME, imageLocation, ActionConstants.GET)) {
// Can we get rid of this?
accessControlAdmin.authorizeRole(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME, imageLocation, ActionConstants.GET);
}
} catch (UserStoreException e) {
throw new APIManagementException("Error while setting up permissions for image collection", e);
}
}
Aggregations