use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.
the class APIProviderImpl method updateApiArtifact.
private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
// Validate Transports
validateAndSetTransports(api);
validateAndSetAPISecurity(api);
boolean transactionCommitted = false;
String apiUUID = null;
try {
registry.beginTransaction();
String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
Resource apiResource = registry.get(artifact.getPath());
String oldAccessControlRoles = api.getAccessControlRoles();
if (apiResource != null) {
oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
}
GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
if (oldTags != null) {
for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
registry.removeTag(artifactPath, tag.getTagName());
}
}
Set<String> tagSet = api.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
// If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
// will skip registry update. Only if this API created with WSDL end point type we need to update
// wsdls for each update.
// check for wsdl endpoint
org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
String wsdlURL;
if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
String path = APIUtil.createWSDL(registry, api);
if (path != null) {
// reset the wsdl path to permlink
updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
}
}
}
}
artifactManager.updateGenericArtifact(updateApiArtifact);
// write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
// to gain performance
String apiStatus = api.getStatus().toUpperCase();
saveAPIStatus(artifactPath, apiStatus);
String[] visibleRoles = new String[0];
String publisherAccessControlRoles = api.getAccessControlRoles();
updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
// propagate api status change and access control roles change to document artifact
String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
}
if (updatePermissions) {
APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
String visibleRolesList = api.getVisibleRoles();
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
}
// attaching api categories to the API
List<APICategory> attachedApiCategories = api.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
registry.commitTransaction();
transactionCommitted = true;
apiUUID = updateApiArtifact.getId();
if (updatePermissions) {
APIManagerConfiguration config = getAPIManagerConfiguration();
boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
String docRootPath = APIUtil.getAPIDocPath(api.getId());
if (isSetDocLevelPermissions) {
// Retain the docs
List<Documentation> docs = getAllDocumentation(api.getId());
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
} else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
}
}
}
} else {
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
}
} else {
// In order to support content search feature - we need to update resource permissions of document resources
// if their visibility is set to API level.
List<Documentation> docs = getAllDocumentation(api.getId());
if (docs != null) {
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
}
}
}
}
} catch (Exception e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error from this level will mask the original exception
log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
}
handleException("Error while performing registry transaction operation", e);
} finally {
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
handleException("Error occurred while rolling back the transaction.", ex);
}
}
return apiUUID;
}
use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPIResources.
/**
* Update resources of the API including local scopes and resource to scope attachments.
*
* @param api API
* @param tenantId Tenant Id
* @throws APIManagementException If fails to update local scopes of the API.
*/
private void updateAPIResources(API api, int tenantId) throws APIManagementException {
String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
APIIdentifier apiIdentifier = api.getId();
// Get the new URI templates for the API
Set<URITemplate> uriTemplates = api.getUriTemplates();
// Get the existing local scope keys attached for the API
Set<String> oldLocalScopeKeys = apiMgtDAO.getAllLocalScopeKeysForAPI(api.getUuid(), tenantId);
// Get the existing URI templates for the API
Set<URITemplate> oldURITemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
// Get the new local scope keys from URI templates
Set<Scope> newLocalScopes = getScopesToRegisterFromURITemplates(api.getId().getApiName(), api.getOrganization(), uriTemplates);
Set<String> newLocalScopeKeys = newLocalScopes.stream().map(Scope::getKey).collect(Collectors.toSet());
// Get the existing versioned local scope keys attached for the API
Set<String> oldVersionedLocalScopeKeys = apiMgtDAO.getVersionedLocalScopeKeysForAPI(api.getUuid(), tenantId);
// Get the existing versioned local scope keys which needs to be removed (not updated) from the current updating
// API and remove them from the oldLocalScopeKeys set before sending to KM, so that they will not be removed
// from KM and can be still used by other versioned APIs.
Iterator oldLocalScopesItr = oldLocalScopeKeys.iterator();
while (oldLocalScopesItr.hasNext()) {
String oldLocalScopeKey = (String) oldLocalScopesItr.next();
// if the scope is used in versioned APIs and it is not in new local scope key set
if (oldVersionedLocalScopeKeys.contains(oldLocalScopeKey) && !newLocalScopeKeys.contains(oldLocalScopeKey)) {
// remove from old local scope key set which will be send to KM
oldLocalScopesItr.remove();
}
}
apiMgtDAO.updateURITemplates(api, tenantId);
if (log.isDebugEnabled()) {
log.debug("Successfully updated the URI templates of API: " + apiIdentifier + " in the database");
}
// Update the resource scopes of the API in KM.
// Need to remove the old local scopes and register new local scopes and, update the resource scope mappings
// using the updated URI templates of the API.
deleteScopes(oldLocalScopeKeys, tenantId);
addScopes(newLocalScopes, tenantId);
Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
if (keyManager != null) {
try {
keyManager.updateResourceScopes(api, oldLocalScopeKeys, newLocalScopes, oldURITemplates, uriTemplates);
if (log.isDebugEnabled()) {
log.debug("Successfully updated the resource scopes of API: " + apiIdentifier + " in Key Manager " + keyManagerDtoEntry.getKey() + " .");
}
} catch (APIManagementException e) {
log.error("Error while updating resource to scope attachment in Key Manager " + keyManagerDtoEntry.getKey(), e);
}
}
}
}
use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.
the class APIProviderImpl method getRemovedProductResources.
@Override
public List<APIResource> getRemovedProductResources(Set<URITemplate> updatedUriTemplates, API existingAPI) {
Set<URITemplate> existingUriTemplates = existingAPI.getUriTemplates();
List<APIResource> removedReusedResources = new ArrayList<>();
for (URITemplate existingUriTemplate : existingUriTemplates) {
// If existing URITemplate is used by any API Products
if (!existingUriTemplate.retrieveUsedByProducts().isEmpty()) {
String existingVerb = existingUriTemplate.getHTTPVerb();
String existingPath = existingUriTemplate.getUriTemplate();
boolean isReusedResourceRemoved = true;
for (URITemplate updatedUriTemplate : updatedUriTemplates) {
String updatedVerb = updatedUriTemplate.getHTTPVerb();
String updatedPath = updatedUriTemplate.getUriTemplate();
// Check if existing reused resource is among updated resources
if (existingVerb.equalsIgnoreCase(updatedVerb) && existingPath.equalsIgnoreCase(updatedPath)) {
isReusedResourceRemoved = false;
break;
}
}
// Existing reused resource is not among updated resources
if (isReusedResourceRemoved) {
APIResource removedResource = new APIResource(existingVerb, existingPath);
removedReusedResources.add(removedResource);
}
}
}
return removedReusedResources;
}
use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.
the class DefaultKeyValidationHandler method validateScopes.
@Override
public boolean validateScopes(TokenValidationContext validationContext) throws APIKeyMgtException {
if (validationContext.isCacheHit()) {
return true;
}
APIKeyValidationInfoDTO apiKeyValidationInfoDTO = validationContext.getValidationInfoDTO();
if (apiKeyValidationInfoDTO == null) {
throw new APIKeyMgtException("Key Validation information not set");
}
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String httpVerb = validationContext.getHttpVerb();
String[] scopes;
Set<String> scopesSet = apiKeyValidationInfoDTO.getScopes();
StringBuilder scopeList = new StringBuilder();
if (scopesSet != null && !scopesSet.isEmpty()) {
scopes = scopesSet.toArray(new String[scopesSet.size()]);
if (log.isDebugEnabled() && scopes != null) {
for (String scope : scopes) {
scopeList.append(scope);
scopeList.append(",");
}
scopeList.deleteCharAt(scopeList.length() - 1);
log.debug("Scopes allowed for token : " + validationContext.getAccessToken() + " : " + scopeList.toString());
}
}
String resourceList = validationContext.getMatchingResource();
List<String> resourceArray;
if ((APIConstants.GRAPHQL_QUERY.equalsIgnoreCase(validationContext.getHttpVerb())) || (APIConstants.GRAPHQL_MUTATION.equalsIgnoreCase(validationContext.getHttpVerb())) || (APIConstants.GRAPHQL_SUBSCRIPTION.equalsIgnoreCase(validationContext.getHttpVerb()))) {
resourceArray = new ArrayList<>(Arrays.asList(resourceList.split(",")));
} else {
resourceArray = new ArrayList<>(Arrays.asList(resourceList));
}
String actualVersion = validationContext.getVersion();
// Check if the api version has been prefixed with _default_
if (actualVersion != null && actualVersion.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
// Remove the prefix from the version.
actualVersion = actualVersion.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
}
SubscriptionDataStore tenantSubscriptionStore = SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(tenantDomain);
API api = tenantSubscriptionStore.getApiByContextAndVersion(validationContext.getContext(), actualVersion);
boolean scopesValidated = false;
if (api != null) {
for (String resource : resourceArray) {
List<URLMapping> resources = api.getResources();
URLMapping urlMapping = null;
for (URLMapping mapping : resources) {
if (Objects.equals(mapping.getHttpMethod(), httpVerb) || "WS".equalsIgnoreCase(api.getApiType())) {
if (isResourcePathMatching(resource, mapping)) {
urlMapping = mapping;
break;
}
}
}
if (urlMapping != null) {
if (urlMapping.getScopes().size() == 0) {
scopesValidated = true;
continue;
}
List<String> mappingScopes = urlMapping.getScopes();
boolean validate = false;
for (String scope : mappingScopes) {
if (scopesSet.contains(scope)) {
scopesValidated = true;
validate = true;
break;
}
}
if (!validate && urlMapping.getScopes().size() > 0) {
scopesValidated = false;
break;
}
}
}
}
if (!scopesValidated) {
apiKeyValidationInfoDTO.setAuthorized(false);
apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.INVALID_SCOPE);
}
return scopesValidated;
}
use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.
the class APIUtil method writeDefinedSequencesToTenantRegistry.
/**
* Adds the sequences defined in repository/resources/customsequences folder to tenant registry
*
* @param tenantID tenant Id
* @throws APIManagementException
*/
public static void writeDefinedSequencesToTenantRegistry(int tenantID) throws APIManagementException {
try {
RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantID);
// Add all custom in,out and fault sequences to tenant registry
APIUtil.addDefinedAllSequencesToRegistry(govRegistry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
APIUtil.addDefinedAllSequencesToRegistry(govRegistry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
APIUtil.addDefinedAllSequencesToRegistry(govRegistry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
} catch (RegistryException e) {
throw new APIManagementException("Error while saving defined sequences to the registry of tenant with id " + tenantID, e);
}
}
Aggregations