use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class AbstractAPIManager method registerCustomQueries.
/**
* method to register custom registry queries
*
* @param registry Registry instance to use
* @throws RegistryException n error
*/
protected void registerCustomQueries(UserRegistry registry, String username) throws RegistryException, APIManagementException {
String tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
String latestAPIsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/latest-apis";
String resourcesByTag = RegistryConstants.QUERIES_COLLECTION_PATH + "/resource-by-tag";
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION);
if (username == null) {
try {
UserRealm realm = ServiceReferenceHolder.getUserRealm();
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(realm);
authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (UserStoreException e) {
String msg = "Error while setting the permissions";
throw new APIManagementException(msg, e);
}
} else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int tenantId;
try {
tenantId = getTenantManager().getTenantId(tenantDomain);
AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Error while setting the permissions";
throw new APIManagementException(msg, e);
}
}
if (!registry.resourceExists(tagsQueryPath)) {
Resource resource = registry.newResource();
// Tag Search Query
// 'MOCK_PATH' used to bypass ChrootWrapper -> filterSearchResult. A valid registry path is
// a must for executeQuery results to be passed to client side
String sql1 = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + " RT.REG_TAG_NAME AS TAG_NAME, " + " COUNT(RT.REG_TAG_NAME) AS USED_COUNT " + "FROM " + " REG_RESOURCE_TAG RRT, " + " REG_TAG RT, " + " REG_RESOURCE R, " + " REG_RESOURCE_PROPERTY RRP, " + " REG_PROPERTY RP " + "WHERE " + " RT.REG_ID = RRT.REG_TAG_ID " + " AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + " AND RRT.REG_VERSION = R.REG_VERSION " + " AND RRP.REG_VERSION = R.REG_VERSION " + " AND RP.REG_NAME = 'STATUS' " + " AND RRP.REG_PROPERTY_ID = RP.REG_ID " + " AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED' AND RP.REG_VALUE !='BLOCKED' AND RP.REG_VALUE !='RETIRED') " + "GROUP BY " + " RT.REG_TAG_NAME";
resource.setContent(sql1);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
registry.put(tagsQueryPath, resource);
}
if (!registry.resourceExists(latestAPIsQueryPath)) {
// Recently added APIs
Resource resource = registry.newResource();
String sql = "SELECT " + " RR.REG_PATH_ID AS REG_PATH_ID, " + " RR.REG_NAME AS REG_NAME " + "FROM " + " REG_RESOURCE RR, " + " REG_RESOURCE_PROPERTY RRP, " + " REG_PROPERTY RP " + "WHERE " + " RR.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + " AND RRP.REG_VERSION = RR.REG_VERSION " + " AND RP.REG_NAME = 'STATUS' " + " AND RRP.REG_PROPERTY_ID = RP.REG_ID " + " AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED') " + "ORDER BY " + " RR.REG_LAST_UPDATED_TIME " + "DESC ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
registry.put(latestAPIsQueryPath, resource);
}
if (!registry.resourceExists(resourcesByTag)) {
Resource resource = registry.newResource();
String sql = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + " R.REG_UUID AS REG_UUID " + "FROM " + " REG_RESOURCE_TAG RRT, " + " REG_TAG RT, " + " REG_RESOURCE R, " + " REG_PATH RP " + "WHERE " + " RT.REG_TAG_NAME = ? " + " AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + " AND RP.REG_PATH_ID = R.REG_PATH_ID " + " AND RT.REG_ID = RRT.REG_TAG_ID " + " AND RRT.REG_VERSION = R.REG_VERSION ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCE_UUID_RESULT_TYPE);
registry.put(resourcesByTag, resource);
}
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method loadloadTenantAPIRXT.
public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
UserRegistry registry = null;
try {
registry = registryService.getGovernanceSystemRegistry(tenantID);
} catch (RegistryException e) {
throw new APIManagementException("Error when create registry instance ", e);
}
String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
File file = new File(rxtDir);
FilenameFilter filenameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// if the file extension is .rxt return true, else false
return name.endsWith(".rxt");
}
};
String[] rxtFilePaths = file.list(filenameFilter);
if (rxtFilePaths == null) {
throw new APIManagementException("rxt files not found in directory " + rxtDir);
}
for (String rxtPath : rxtFilePaths) {
String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
// This is "registry" is a governance registry instance, therefore calculate the relative path to governance.
String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
try {
// 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 (registry.resourceExists(govRelativePath)) {
// set anonymous user permission to RXTs
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
continue;
}
String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
Resource resource = registry.newResource();
resource.setContent(rxt.getBytes(Charset.defaultCharset()));
resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
registry.put(govRelativePath, resource);
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} catch (UserStoreException e) {
throw new APIManagementException("Error while adding role permissions to API", e);
} catch (IOException e) {
String msg = "Failed to read rxt files";
throw new APIManagementException(msg, e);
} catch (RegistryException e) {
String msg = "Failed to add rxt to registry ";
throw new APIManagementException(msg, e);
}
}
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class APIProviderImplTest method testCreateNewAPIVersion.
@Test
public void testCreateNewAPIVersion() throws Exception {
// Create Original API
APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
API api = new API(apiId);
api.setContext("/test");
api.setVisibility("Public");
api.setStatus(APIConstants.CREATED);
api.setWsdlUrl("https://localhost:9443/services/echo?wsdl");
api.setOrganization("carbon.super");
long time = System.currentTimeMillis();
String newVersion = "1.0.1";
// Create new API object
APIIdentifier newApiId = new APIIdentifier("admin", "API1", "1.0.1");
final API newApi = new API(newApiId);
newApi.setStatus(APIConstants.CREATED);
newApi.setContext("/test");
newApi.setWsdlUrl("/registry/resource/_system/governance/apimgt/applicationdata/wsdls/admin--API11.0.0.wsdl");
// Create Documentation List
List<Documentation> documentationList = getDocumentationList();
final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
GenericArtifact artifactNew = Mockito.mock(GenericArtifact.class);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, newApi)).thenReturn(artifactNew);
PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
Mockito.when(publisherAPI.getVersionTimestamp()).thenReturn(String.valueOf(time));
PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
API returnedAPI = apiProvider.addAPI(api);
Assert.assertTrue(StringUtils.isNotEmpty(returnedAPI.getVersionTimestamp()));
String targetPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + newVersion + APIConstants.API_RESOURCE_NAME;
String apiSourcePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + APIConstants.API_RESOURCE_NAME;
PowerMockito.when(APIUtil.getAPIPath(apiId)).thenReturn(apiSourcePath);
String apiSourceUUID = "87ty543-899hyt";
Mockito.when(apiProvider.registry.resourceExists(targetPath)).thenReturn(false);
Mockito.doNothing().when(apiProvider.registry).beginTransaction();
Mockito.doNothing().when(apiProvider.registry).commitTransaction();
Resource apiSourceArtifact = Mockito.mock(Resource.class);
Mockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
// Mocking Old API retrieval
Mockito.when(apiSourceArtifact.getUUID()).thenReturn(apiSourceUUID);
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("PUBLISHED");
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT)).thenReturn("test");
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE)).thenReturn("test/{version}");
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_WEBSOCKET)).thenReturn("false");
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES)).thenReturn("admin, subscriber");
Mockito.when(artifactManager.getGenericArtifact(apiSourceUUID)).thenReturn(artifact);
// Mocking thumbnail
String thumbUrl = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
Resource image = Mockito.mock(Resource.class);
Mockito.when(apiProvider.registry.get(thumbUrl)).thenReturn(image);
Mockito.when(apiProvider.registry.resourceExists(thumbUrl)).thenReturn(true);
// Mocking In sequence retrieval
String inSeqFilePath = "API1/1.0.0/in";
PowerMockito.when(APIUtil.getSequencePath(api.getId(), "in")).thenReturn(inSeqFilePath);
Mockito.when(apiProvider.registry.resourceExists(inSeqFilePath)).thenReturn(true);
Collection inSeqCollection = Mockito.mock(Collection.class);
Mockito.when(apiProvider.registry.get(inSeqFilePath)).thenReturn(inSeqCollection);
String[] inSeqChildPaths = { "path1" };
Mockito.when(inSeqCollection.getChildren()).thenReturn(inSeqChildPaths);
Mockito.when(apiProvider.registry.get(inSeqChildPaths[0])).thenReturn(apiSourceArtifact);
InputStream responseStream = IOUtils.toInputStream("<sequence name=\"in-seq\"></sequence>", "UTF-8");
OMElement seqElment = buildOMElement(responseStream);
PowerMockito.when(APIUtil.buildOMElement(responseStream)).thenReturn(seqElment);
Mockito.when(apiSourceArtifact.getContentStream()).thenReturn(responseStream);
// Mocking Out sequence retrieval
Resource apiSourceArtifact1 = Mockito.mock(Resource.class);
String outSeqFilePath = "API1/1.0.0/out";
PowerMockito.when(APIUtil.getSequencePath(api.getId(), "out")).thenReturn(outSeqFilePath);
Mockito.when(apiProvider.registry.resourceExists(outSeqFilePath)).thenReturn(true);
Collection outSeqCollection = Mockito.mock(Collection.class);
Mockito.when(apiProvider.registry.get(outSeqFilePath)).thenReturn(outSeqCollection);
String[] outSeqChildPaths = { "path2" };
Mockito.when(outSeqCollection.getChildren()).thenReturn(outSeqChildPaths);
Mockito.when(apiProvider.registry.get(outSeqChildPaths[0])).thenReturn(apiSourceArtifact1);
InputStream responseStream2 = IOUtils.toInputStream("<sequence name=\"in-seq\"></sequence>", "UTF-8");
OMElement seqElment2 = buildOMElement(responseStream2);
PowerMockito.when(APIUtil.buildOMElement(responseStream2)).thenReturn(seqElment2);
Mockito.when(apiSourceArtifact1.getContentStream()).thenReturn(responseStream2);
// Mock Adding new API artifact with new version
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
apiProvider.createAPI(newApi);
return null;
}
}).when(artifactManager).addGenericArtifact(artifact);
Mockito.doNothing().when(artifact).attachLifecycle(APIConstants.API_LIFE_CYCLE);
PowerMockito.when(APIUtil.getAPIProviderPath(api.getId())).thenReturn("/dummy/provider/path");
Mockito.doNothing().when(apiProvider.registry).addAssociation("/dummy/provider/path", targetPath, APIConstants.PROVIDER_ASSOCIATION);
PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, artifact.getId())).thenReturn(artifactPath);
PowerMockito.doNothing().when(APIUtil.class);
String[] roles = { "admin", "subscriber" };
APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
// Mock no tags case
Mockito.when(apiProvider.registry.getTags(apiSourcePath)).thenReturn(null);
// Mock WSDL retrieval
String wsdlUrl = APIUtil.getWSDLDefinitionFilePath(api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName());
PowerMockito.when(apiProvider.registry.resourceExists(wsdlUrl)).thenReturn(true);
// Mock new API retrieval
String newApiPath = "API1/1.0.1/";
PowerMockito.when(APIUtil.getAPIPath(newApi.getId())).thenReturn(newApiPath);
String newApiUUID = "87ty543-899hy23";
GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
Resource newApiResource = Mockito.mock(Resource.class);
Mockito.when(newApiResource.getUUID()).thenReturn(newApiUUID);
Mockito.when(apiProvider.registry.get(newApiPath)).thenReturn(newApiResource);
Mockito.when(artifactManager.getGenericArtifact(newApiUUID)).thenReturn(newArtifact);
PowerMockito.when(APIUtil.getAPI(newArtifact, apiProvider.registry, api.getId(), "test")).thenReturn(newApi);
// Swagger resource
String resourcePath = APIUtil.getOpenAPIDefinitionFilePath(api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName());
Mockito.when(apiProvider.registry.resourceExists(resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME)).thenReturn(true);
PowerMockito.mockStatic(OASParserUtil.class);
Mockito.when(OASParserUtil.getAPIDefinition(apiId, apiProvider.registry)).thenReturn("{\"info\": {\"swagger\":\"data\"}}");
Mockito.doNothing().when(artifactManager).updateGenericArtifact(artifact);
// WSDL
String newWsdlResourcePath = APIUtil.getWSDLDefinitionFilePath(newApi.getId().getApiName(), newApi.getId().getVersion(), newApi.getId().getProviderName());
PowerMockito.when(apiProvider.registry.copy(resourcePath, newWsdlResourcePath)).thenReturn(newWsdlResourcePath);
// Mock Config system registry
PowerMockito.when(tenantManager.getTenantId(Matchers.anyString())).thenReturn(-1234);
AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
UserRealm userRealm = Mockito.mock(UserRealm.class);
PowerMockito.when(realmService.getTenantUserRealm(-1234)).thenReturn(userRealm);
PowerMockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class APIProviderImpl method getAuthorizedRoles.
private String[] getAuthorizedRoles(String artifactPath) throws UserStoreException {
String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
return authManager.getAllowedRolesForResource(resourcePath, ActionConstants.GET);
} else {
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
return authorizationManager.getAllowedRolesForResource(resourcePath, ActionConstants.GET);
}
}
use of org.wso2.carbon.user.core.AuthorizationManager in project carbon-apimgt by wso2.
the class APIUtil method clearResourcePermissions.
/**
* This function is to set resource permissions based on its visibility
*
* @param artifactPath API/Product resource path
* @throws APIManagementException Throwing exception
*/
public static void clearResourcePermissions(String artifactPath, Identifier id, int tenantId) throws APIManagementException {
try {
String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(id.getProviderName()));
if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
authManager.clearResourceAuthorizations(resourcePath);
} else {
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
authorizationManager.clearResourceAuthorizations(resourcePath);
}
} catch (UserStoreException e) {
handleException("Error while adding role permissions to API", e);
}
}
Aggregations