Search in sources :

Example 1 with CryptoUtil

use of org.wso2.carbon.core.util.CryptoUtil in project wso2-synapse by wso2.

the class CryptoUtil method init.

/**
 * Method to initialise crypto util. which will generate the required chiper etc.
 *
 * @param secureVaultProperties
 * @throws org.apache.axis2.AxisFault
 */
public void init(Properties secureVaultProperties) throws AxisFault {
    // Create a KeyStore Information  for private key entry KeyStore
    IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory.createIdentityKeyStoreInformation(secureVaultProperties);
    String identityKeyPass = null;
    String identityStorePass = null;
    if (identityInformation != null) {
        identityKeyPass = identityInformation.getKeyPasswordProvider().getResolvedSecret();
        identityStorePass = identityInformation.getKeyStorePasswordProvider().getResolvedSecret();
    }
    if (!Util.validatePasswords(identityStorePass, identityKeyPass)) {
        if (log.isDebugEnabled()) {
            log.info("Either Identity or Trust keystore password is mandatory" + " in order to initialized secret manager.");
        }
        throw new AxisFault("Error inititialising cryptoutil, required parameters not provided");
    }
    IdentityKeyStoreWrapper identityKeyStoreWrapper = new IdentityKeyStoreWrapper();
    identityKeyStoreWrapper.init(identityInformation, identityKeyPass);
    algorithm = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.CIPHER_ALGORITHM, CryptoConstants.CIPHER_ALGORITHM_DEFAULT);
    String provider = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.SECURITY_PROVIDER, null);
    String cipherType = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.CIPHER_TYPE, null);
    String inTypeString = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.INPUT_ENCODE_TYPE, null);
    inType = Util.getEncodeDecodeType(inTypeString, EncodeDecodeTypes.BASE64);
    String outTypeString = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.OUTPUT_ENCODE_TYPE, null);
    outType = Util.getEncodeDecodeType(outTypeString, null);
    CipherInformation cipherInformation = new CipherInformation();
    cipherInformation.setAlgorithm(algorithm);
    cipherInformation.setCipherOperationMode(CipherOperationMode.DECRYPT);
    cipherInformation.setType(cipherType);
    // skipping decoding encoding in securevault
    cipherInformation.setInType(null);
    // skipping decoding encoding in securevault
    cipherInformation.setOutType(null);
    if (provider != null && !provider.isEmpty()) {
        if (CryptoConstants.BOUNCY_CASTLE_PROVIDER.equals(provider)) {
            Security.addProvider(new BouncyCastleProvider());
            cipherInformation.setProvider(provider);
        }
    // todo need to add other providers if there are any.
    }
    baseCipher = CipherFactory.createCipher(cipherInformation, identityKeyStoreWrapper);
    isInitialized = true;
}
Also used : AxisFault(org.apache.axis2.AxisFault) IdentityKeyStoreWrapper(org.wso2.securevault.keystore.IdentityKeyStoreWrapper) IdentityKeyStoreInformation(org.wso2.securevault.definition.IdentityKeyStoreInformation) CipherInformation(org.wso2.securevault.definition.CipherInformation) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 2 with CryptoUtil

use of org.wso2.carbon.core.util.CryptoUtil in project carbon-apimgt by wso2.

the class APIAdminImpl method encryptValues.

private Object encryptValues(Object value) throws APIManagementException {
    try {
        CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
        if (value instanceof String) {
            String encryptedValue = new String(cryptoUtil.encrypt(((String) value).getBytes()));
            return getEncryptedValue(encryptedValue);
        } else if (value instanceof List) {
            List valueList = (List) value;
            List encrpytedList = new ArrayList<>();
            for (Object s : valueList) {
                encrpytedList.add(encryptValues(s));
            }
            return encrpytedList;
        } else if (value instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) value;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object entryValue = entry.getValue();
                map.replace(key, encryptValues(entryValue));
            }
            return map;
        }
    } catch (CryptoException e) {
        throw new APIManagementException("Error while encrypting values", e);
    }
    return null;
}
Also used : CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) List(java.util.List) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) CryptoException(org.wso2.carbon.core.util.CryptoException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with CryptoUtil

use of org.wso2.carbon.core.util.CryptoUtil in project carbon-apimgt by wso2.

the class PublisherCommonUtils method encryptEndpointSecurityOAuthCredentials.

/**
 * This method will encrypt the OAuth 2.0 API Key and API Secret
 *
 * @param endpointConfig         endpoint configuration of API
 * @param cryptoUtil             cryptography util
 * @param oldProductionApiSecret existing production API secret
 * @param oldSandboxApiSecret    existing sandbox API secret
 * @param apidto                 API DTO
 * @throws CryptoException        if an error occurs while encrypting and base64 encode
 * @throws APIManagementException if an error occurs due to a problem in the endpointConfig payload
 */
public static void encryptEndpointSecurityOAuthCredentials(Map endpointConfig, CryptoUtil cryptoUtil, String oldProductionApiSecret, String oldSandboxApiSecret, APIDTO apidto) throws CryptoException, APIManagementException {
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    String customParametersString;
    if (endpointConfig != null) {
        if ((endpointConfig.get(APIConstants.ENDPOINT_SECURITY) != null)) {
            Map endpointSecurity = (Map) endpointConfig.get(APIConstants.ENDPOINT_SECURITY);
            if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION) != null) {
                Map endpointSecurityProduction = (Map) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
                String productionEndpointType = (String) endpointSecurityProduction.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                // Change default value of customParameters JSONObject to String
                if (!(endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) instanceof String)) {
                    LinkedHashMap<String, String> customParametersHashMap = (LinkedHashMap<String, String>) endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                    customParametersString = JSONObject.toJSONString(customParametersHashMap);
                } else if (endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                    customParametersString = (String) endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                } else {
                    customParametersString = "{}";
                }
                endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParametersString);
                if (APIConstants.OAuthConstants.OAUTH.equals(productionEndpointType)) {
                    if (endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null && StringUtils.isNotBlank(endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString())) {
                        String apiSecret = endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                        String encryptedApiSecret = cryptoUtil.encryptAndBase64Encode(apiSecret.getBytes());
                        endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, encryptedApiSecret);
                    } else if (StringUtils.isNotBlank(oldProductionApiSecret)) {
                        endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, oldProductionApiSecret);
                    } else {
                        String errorMessage = "Client secret is not provided for production endpoint security";
                        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.INVALID_ENDPOINT_CREDENTIALS, errorMessage));
                    }
                }
                endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION, endpointSecurityProduction);
                endpointConfig.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                apidto.setEndpointConfig(endpointConfig);
            }
            if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX) != null) {
                Map endpointSecuritySandbox = (Map) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
                String sandboxEndpointType = (String) endpointSecuritySandbox.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                // Change default value of customParameters JSONObject to String
                if (!(endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) instanceof String)) {
                    Map<String, String> customParametersHashMap = (Map<String, String>) endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                    customParametersString = JSONObject.toJSONString(customParametersHashMap);
                } else if (endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                    customParametersString = (String) endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                } else {
                    customParametersString = "{}";
                }
                endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParametersString);
                if (APIConstants.OAuthConstants.OAUTH.equals(sandboxEndpointType)) {
                    if (endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null && StringUtils.isNotBlank(endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString())) {
                        String apiSecret = endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                        String encryptedApiSecret = cryptoUtil.encryptAndBase64Encode(apiSecret.getBytes());
                        endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, encryptedApiSecret);
                    } else if (StringUtils.isNotBlank(oldSandboxApiSecret)) {
                        endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, oldSandboxApiSecret);
                    } else {
                        String errorMessage = "Client secret is not provided for sandbox endpoint security";
                        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.INVALID_ENDPOINT_CREDENTIALS, errorMessage));
                    }
                }
                endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX, endpointSecuritySandbox);
                endpointConfig.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                apidto.setEndpointConfig(endpointConfig);
            }
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with CryptoUtil

use of org.wso2.carbon.core.util.CryptoUtil in project carbon-apimgt by wso2.

the class APIMappingUtil method handleAWSCredentials.

/**
 * Set AWS Secret Key based on preserveCredentials state
 *
 * @param awsEndpointConfig   Endpoint configuration of the API
 * @param preserveCredentials Condition to preserve credentials
 * @return Updated endpoint config
 */
private static JSONObject handleAWSCredentials(JSONObject awsEndpointConfig, boolean preserveCredentials) {
    if (StringUtils.isNotEmpty((String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY))) {
        if (!preserveCredentials) {
            awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, APIConstants.AWS_SECRET_KEY);
            return awsEndpointConfig;
        } else {
            String secretKey = (String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            // Decrypting the key since CTL project goes between environments which have different encryption keys.
            try {
                CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                String decryptedSecret = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
                awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, decryptedSecret);
                return awsEndpointConfig;
            } catch (CryptoException | UnsupportedEncodingException e) {
                log.error("Error while decrypting the Amazon key", e);
            }
        }
    }
    return awsEndpointConfig;
}
Also used : CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CryptoException(org.wso2.carbon.core.util.CryptoException)

Example 5 with CryptoUtil

use of org.wso2.carbon.core.util.CryptoUtil 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
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ArrayList(java.util.ArrayList) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) List(java.util.List) ArrayList(java.util.ArrayList) Tier(org.wso2.carbon.apimgt.api.model.Tier) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) Scope(org.wso2.carbon.apimgt.rest.api.common.annotations.Scope) JSONObject(org.json.simple.JSONObject) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) JSONParser(org.json.simple.parser.JSONParser) API(org.wso2.carbon.apimgt.api.model.API) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Aggregations

CryptoUtil (org.wso2.carbon.core.util.CryptoUtil)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 HashMap (java.util.HashMap)5 CryptoException (org.wso2.carbon.core.util.CryptoException)5 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 JSONObject (org.json.simple.JSONObject)4 LinkedHashMap (java.util.LinkedHashMap)3 JSONParser (org.json.simple.parser.JSONParser)3 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)3 API (org.wso2.carbon.apimgt.api.model.API)3 APICategory (org.wso2.carbon.apimgt.api.model.APICategory)3 JsonObject (com.google.gson.JsonObject)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 List (java.util.List)2 ParseException (org.json.simple.parser.ParseException)2 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)2 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)2 Tier (org.wso2.carbon.apimgt.api.model.Tier)2 AsyncApiParser (org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser)2