use of org.wso2.carbon.apimgt.api.FaultGatewaysException in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateApi.
/**
* Update an API.
*
* @param originalAPI Existing API
* @param apiDtoToUpdate New API DTO to update
* @param apiProvider API Provider
* @param tokenScopes Scopes of the token
* @throws ParseException If an error occurs while parsing the endpoint configuration
* @throws CryptoException If an error occurs while encrypting the secret key of API
* @throws APIManagementException If an error occurs while updating the API
* @throws FaultGatewaysException If an error occurs while updating manage of an existing API
*/
public static API updateApi(API originalAPI, APIDTO apiDtoToUpdate, APIProvider apiProvider, String[] tokenScopes) throws ParseException, CryptoException, APIManagementException, FaultGatewaysException {
APIIdentifier apiIdentifier = originalAPI.getId();
// Validate if the USER_REST_API_SCOPES is not set in WebAppAuthenticator when scopes are validated
if (tokenScopes == null) {
throw new APIManagementException("Error occurred while updating the API " + originalAPI.getUUID() + " as the token information hasn't been correctly set internally", ExceptionCodes.TOKEN_SCOPES_NOT_SET);
}
boolean isGraphql = originalAPI.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(originalAPI.getType());
boolean isAsyncAPI = originalAPI.getType() != null && (APIConstants.APITransportType.WS.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.SSE.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.ASYNC.toString().equals(originalAPI.getType()));
Scope[] apiDtoClassAnnotatedScopes = APIDTO.class.getAnnotationsByType(Scope.class);
boolean hasClassLevelScope = checkClassScopeAnnotation(apiDtoClassAnnotatedScopes, tokenScopes);
JSONParser parser = new JSONParser();
String oldEndpointConfigString = originalAPI.getEndpointConfig();
JSONObject oldEndpointConfig = null;
if (StringUtils.isNotBlank(oldEndpointConfigString)) {
oldEndpointConfig = (JSONObject) parser.parse(oldEndpointConfigString);
}
String oldProductionApiSecret = null;
String oldSandboxApiSecret = null;
if (oldEndpointConfig != null) {
if ((oldEndpointConfig.containsKey(APIConstants.ENDPOINT_SECURITY))) {
JSONObject oldEndpointSecurity = (JSONObject) oldEndpointConfig.get(APIConstants.ENDPOINT_SECURITY);
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION)) {
JSONObject oldEndpointSecurityProduction = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
if (oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldProductionApiSecret = oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX)) {
JSONObject oldEndpointSecuritySandbox = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
if (oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldSandboxApiSecret = oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
}
}
Map endpointConfig = (Map) apiDtoToUpdate.getEndpointConfig();
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
// OAuth 2.0 backend protection: API Key and API Secret encryption
encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, oldProductionApiSecret, oldSandboxApiSecret, apiDtoToUpdate);
// AWS Lambda: secret key encryption while updating the API
if (apiDtoToUpdate.getEndpointConfig() != null) {
if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
if (!StringUtils.isEmpty(secretKey)) {
if (!APIConstants.AWS_SECRET_KEY.equals(secretKey)) {
String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
} else {
JSONParser jsonParser = new JSONParser();
JSONObject originalEndpointConfig = (JSONObject) jsonParser.parse(originalAPI.getEndpointConfig());
String encryptedSecretKey = (String) originalEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
}
}
}
}
if (!hasClassLevelScope) {
// Validate per-field scopes
apiDtoToUpdate = getFieldOverriddenAPIDTO(apiDtoToUpdate, originalAPI, tokenScopes);
}
// API Name change not allowed if OnPrem
if (APIUtil.isOnPremResolver()) {
apiDtoToUpdate.setName(apiIdentifier.getApiName());
}
apiDtoToUpdate.setVersion(apiIdentifier.getVersion());
apiDtoToUpdate.setProvider(apiIdentifier.getProviderName());
apiDtoToUpdate.setContext(originalAPI.getContextTemplate());
apiDtoToUpdate.setLifeCycleStatus(originalAPI.getStatus());
apiDtoToUpdate.setType(APIDTO.TypeEnum.fromValue(originalAPI.getType()));
List<APIResource> removedProductResources = getRemovedProductResources(apiDtoToUpdate, originalAPI);
if (!removedProductResources.isEmpty()) {
throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, originalAPI.getId().getApiName(), originalAPI.getId().getVersion()));
}
// Validate API Security
List<String> apiSecurity = apiDtoToUpdate.getSecurityScheme();
// validation for tiers
List<String> tiersFromDTO = apiDtoToUpdate.getPolicies();
String originalStatus = originalAPI.getStatus();
if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
if ((tiersFromDTO == null || tiersFromDTO.isEmpty() && !(APIConstants.CREATED.equals(originalStatus) || APIConstants.PROTOTYPED.equals(originalStatus))) && !apiDtoToUpdate.getAdvertiseInfo().isAdvertised()) {
throw new APIManagementException("A tier should be defined if the API is not in CREATED or PROTOTYPED state", ExceptionCodes.TIER_CANNOT_BE_NULL);
}
}
if (tiersFromDTO != null && !tiersFromDTO.isEmpty()) {
// check whether the added API's tiers are all valid
Set<Tier> definedTiers = apiProvider.getTiers();
List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
if (invalidTiers.size() > 0) {
throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
}
}
if (apiDtoToUpdate.getAccessControlRoles() != null) {
String errorMessage = validateUserRoles(apiDtoToUpdate.getAccessControlRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getVisibleRoles() != null) {
String errorMessage = validateRoles(apiDtoToUpdate.getVisibleRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getAdditionalProperties() != null) {
String errorMessage = validateAdditionalProperties(apiDtoToUpdate.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiDtoToUpdate.getName(), apiDtoToUpdate.getVersion()));
}
}
// Validate if resources are empty
if (apiDtoToUpdate.getOperations() == null || apiDtoToUpdate.getOperations().isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
API apiToUpdate = APIMappingUtil.fromDTOtoAPI(apiDtoToUpdate, apiIdentifier.getProviderName());
if (APIConstants.PUBLIC_STORE_VISIBILITY.equals(apiToUpdate.getVisibility())) {
apiToUpdate.setVisibleRoles(StringUtils.EMPTY);
}
apiToUpdate.setUUID(originalAPI.getUUID());
apiToUpdate.setOrganization(originalAPI.getOrganization());
validateScopes(apiToUpdate);
apiToUpdate.setThumbnailUrl(originalAPI.getThumbnailUrl());
if (apiDtoToUpdate.getKeyManagers() instanceof List) {
apiToUpdate.setKeyManagers((List<String>) apiDtoToUpdate.getKeyManagers());
} else {
apiToUpdate.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
}
if (!isAsyncAPI) {
String oldDefinition = apiProvider.getOpenAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
APIDefinition apiDefinition = OASParserUtil.getOASParser(oldDefinition);
SwaggerData swaggerData = new SwaggerData(apiToUpdate);
String newDefinition = apiDefinition.generateAPIDefinition(swaggerData, oldDefinition);
apiProvider.saveSwaggerDefinition(apiToUpdate, newDefinition, originalAPI.getOrganization());
if (!isGraphql) {
Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(newDefinition);
// set operation policies from the original API Payload
Set<URITemplate> uriTemplatesFromPayload = apiToUpdate.getUriTemplates();
Map<String, List<OperationPolicy>> operationPoliciesPerURITemplate = new HashMap<>();
for (URITemplate uriTemplate : uriTemplatesFromPayload) {
if (!uriTemplate.getOperationPolicies().isEmpty()) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
operationPoliciesPerURITemplate.put(key, uriTemplate.getOperationPolicies());
}
}
for (URITemplate uriTemplate : uriTemplates) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
if (operationPoliciesPerURITemplate.containsKey(key)) {
uriTemplate.setOperationPolicies(operationPoliciesPerURITemplate.get(key));
}
}
apiToUpdate.setUriTemplates(uriTemplates);
}
} else {
String oldDefinition = apiProvider.getAsyncAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
AsyncApiParser asyncApiParser = new AsyncApiParser();
String updateAsyncAPIDefinition = asyncApiParser.updateAsyncAPIDefinition(oldDefinition, apiToUpdate);
apiProvider.saveAsyncApiDefinition(originalAPI, updateAsyncAPIDefinition);
}
apiToUpdate.setWsdlUrl(apiDtoToUpdate.getWsdlUrl());
// validate API categories
List<APICategory> apiCategories = apiToUpdate.getApiCategories();
List<APICategory> apiCategoriesList = new ArrayList<>();
for (APICategory category : apiCategories) {
category.setOrganization(originalAPI.getOrganization());
apiCategoriesList.add(category);
}
apiToUpdate.setApiCategories(apiCategoriesList);
if (apiCategoriesList.size() > 0) {
if (!APIUtil.validateAPICategories(apiCategoriesList, originalAPI.getOrganization())) {
throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
}
}
apiToUpdate.setOrganization(originalAPI.getOrganization());
apiProvider.updateAPI(apiToUpdate, originalAPI);
return apiProvider.getAPIbyUUID(originalAPI.getUuid(), originalAPI.getOrganization());
// TODO use returend api
}
use of org.wso2.carbon.apimgt.api.FaultGatewaysException in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addAPIProductWithGeneratedSwaggerDefinition.
/**
* Add API Product with the generated swagger from the DTO.
*
* @param apiProductDTO API Product DTO
* @param username Username
* @param organization Identifier of the organization
* @return Created API Product object
* @throws APIManagementException Error while creating the API Product
* @throws FaultGatewaysException Error while adding the API Product to gateway
*/
public static APIProduct addAPIProductWithGeneratedSwaggerDefinition(APIProductDTO apiProductDTO, String username, String organization) throws APIManagementException, FaultGatewaysException {
username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
// if not add product
String provider = apiProductDTO.getProvider();
String context = apiProductDTO.getContext();
if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
if (log.isDebugEnabled()) {
log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
}
provider = username;
}
} else {
// Set username in case provider is null or empty
provider = username;
}
List<String> tiersFromDTO = apiProductDTO.getPolicies();
Set<Tier> definedTiers = apiProvider.getTiers();
List<String> invalidTiers = PublisherCommonUtils.getInvalidTierNames(definedTiers, tiersFromDTO);
if (!invalidTiers.isEmpty()) {
throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
}
if (apiProductDTO.getAdditionalProperties() != null) {
String errorMessage = PublisherCommonUtils.validateAdditionalProperties(apiProductDTO.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiProductDTO.getName()));
}
}
if (apiProductDTO.getVisibility() == null) {
// set the default visibility to PUBLIC
apiProductDTO.setVisibility(APIProductDTO.VisibilityEnum.PUBLIC);
}
if (apiProductDTO.getAuthorizationHeader() == null) {
apiProductDTO.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
}
if (apiProductDTO.getAuthorizationHeader() == null) {
apiProductDTO.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
}
// Remove the /{version} from the context.
if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
}
// Make sure context starts with "/". ex: /pizzaProduct
context = context.startsWith("/") ? context : ("/" + context);
// Check whether the context already exists
if (apiProvider.isContextExist(context)) {
throw new APIManagementException("Error occurred while adding API Product. API Product with the context " + context + " already " + "exists.", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_CONTEXT_ALREADY_EXISTS, context));
}
// Set default gatewayVendor
if (apiProductDTO.getGatewayVendor() == null) {
apiProductDTO.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
}
APIProduct productToBeAdded = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, provider);
productToBeAdded.setOrganization(organization);
if (!APIConstants.PROTOTYPED.equals(productToBeAdded.getState())) {
productToBeAdded.setState(APIConstants.CREATED);
}
APIProductIdentifier createdAPIProductIdentifier = productToBeAdded.getId();
Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.addAPIProductWithoutPublishingToGateway(productToBeAdded);
APIProduct createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
apiProvider.addAPIProductSwagger(createdProduct.getUuid(), apiToProductResourceMapping, createdProduct, organization);
createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
return createdProduct;
}
use of org.wso2.carbon.apimgt.api.FaultGatewaysException in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateAsyncAPIDefinition.
/**
* update AsyncPI definition of the given api.
*
* @param apiId API Id
* @param response response of the AsyncAPI definition validation call
* @param organization identifier of the organization
* @return updated AsyncAPI definition
* @throws APIManagementException when error occurred updating AsyncAPI definition
* @throws FaultGatewaysException when error occurred publishing API to the gateway
*/
public static String updateAsyncAPIDefinition(String apiId, APIDefinitionValidationResponse response, String organization) throws APIManagementException, FaultGatewaysException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// this will fall if user does not have access to the API or the API does not exist
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
existingAPI.setOrganization(organization);
String apiDefinition = response.getJsonContent();
AsyncApiParser asyncApiParser = new AsyncApiParser();
// Set uri templates
Set<URITemplate> uriTemplates = asyncApiParser.getURITemplates(apiDefinition, APIConstants.API_TYPE_WS.equals(existingAPI.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(existingAPI.getGatewayVendor()));
if (uriTemplates == null || uriTemplates.isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
existingAPI.setUriTemplates(uriTemplates);
// Update ws uri mapping
existingAPI.setWsUriMapping(asyncApiParser.buildWSUriMapping(apiDefinition));
// updating APi with the new AsyncAPI definition
existingAPI.setAsyncApiDefinition(apiDefinition);
apiProvider.saveAsyncApiDefinition(existingAPI, apiDefinition);
apiProvider.updateAPI(existingAPI);
// retrieves the updated AsyncAPI definition
return apiProvider.getAsyncAPIDefinition(existingAPI.getId().getUUID(), organization);
}
use of org.wso2.carbon.apimgt.api.FaultGatewaysException in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateSwagger.
/**
* update swagger definition of the given api.
*
* @param apiId API Id
* @param response response of a swagger definition validation call
* @param organization Organization Identifier
* @return updated swagger definition
* @throws APIManagementException when error occurred updating swagger
* @throws FaultGatewaysException when error occurred publishing API to the gateway
*/
public static String updateSwagger(String apiId, APIDefinitionValidationResponse response, boolean isServiceAPI, String organization) throws APIManagementException, FaultGatewaysException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// this will fail if user does not have access to the API or the API does not exist
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
APIDefinition oasParser = response.getParser();
String apiDefinition = response.getJsonContent();
if (isServiceAPI) {
apiDefinition = oasParser.copyVendorExtensions(existingAPI.getSwaggerDefinition(), apiDefinition);
} else {
apiDefinition = OASParserUtil.preProcess(apiDefinition);
}
if (APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType())) {
List<SOAPToRestSequence> sequenceList = SequenceGenerator.generateSequencesFromSwagger(apiDefinition);
existingAPI.setSoapToRestSequences(sequenceList);
}
Set<URITemplate> uriTemplates = null;
uriTemplates = oasParser.getURITemplates(apiDefinition);
if (uriTemplates == null || uriTemplates.isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
Set<org.wso2.carbon.apimgt.api.model.Scope> scopes = oasParser.getScopes(apiDefinition);
// validating scope roles
for (org.wso2.carbon.apimgt.api.model.Scope scope : scopes) {
String roles = scope.getRoles();
if (roles != null) {
for (String aRole : roles.split(",")) {
boolean isValidRole = APIUtil.isRoleNameExist(RestApiCommonUtil.getLoggedInUsername(), aRole);
if (!isValidRole) {
throw new APIManagementException("Role '" + aRole + "' Does not exist.");
}
}
}
}
List<APIResource> removedProductResources = apiProvider.getRemovedProductResources(uriTemplates, existingAPI);
if (!removedProductResources.isEmpty()) {
throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, existingAPI.getId().getApiName(), existingAPI.getId().getVersion()));
}
// set existing operation policies to URI templates
apiProvider.setOperationPoliciesToURITemplates(apiId, uriTemplates);
existingAPI.setUriTemplates(uriTemplates);
existingAPI.setScopes(scopes);
PublisherCommonUtils.validateScopes(existingAPI);
// Update API is called to update URITemplates and scopes of the API
SwaggerData swaggerData = new SwaggerData(existingAPI);
String updatedApiDefinition = oasParser.populateCustomManagementInfo(apiDefinition, swaggerData);
apiProvider.saveSwaggerDefinition(existingAPI, updatedApiDefinition, organization);
existingAPI.setSwaggerDefinition(updatedApiDefinition);
API unModifiedAPI = apiProvider.getAPIbyUUID(apiId, organization);
existingAPI.setStatus(unModifiedAPI.getStatus());
apiProvider.updateAPI(existingAPI, unModifiedAPI);
// retrieves the updated swagger definition
// TODO see why we need to get it
String apiSwagger = apiProvider.getOpenAPIDefinition(apiId, organization);
// instead of passing same
return oasParser.getOASDefinitionForPublisher(existingAPI, apiSwagger);
}
use of org.wso2.carbon.apimgt.api.FaultGatewaysException in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateAPIBySettingGenerateSequencesFromSwagger.
/**
* Set the generated SOAP to REST sequences from the swagger file to the API and update it.
*
* @param swaggerContent Swagger content
* @param api API to update
* @param apiProvider API Provider
* @param organization Organization Identifier
* @return Updated API Object
* @throws APIManagementException If an error occurs while generating the sequences or updating the API
* @throws FaultGatewaysException If an error occurs while updating the API
*/
public static API updateAPIBySettingGenerateSequencesFromSwagger(String swaggerContent, API api, APIProvider apiProvider, String organization) throws APIManagementException, FaultGatewaysException {
List<SOAPToRestSequence> list = SequenceGenerator.generateSequencesFromSwagger(swaggerContent);
API updatedAPI = apiProvider.getAPIbyUUID(api.getUuid(), organization);
updatedAPI.setSoapToRestSequences(list);
return apiProvider.updateAPI(updatedAPI, api);
}
Aggregations