Search in sources :

Example 6 with CryptoUtil

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

the class PublisherCommonUtils method addAPIWithGeneratedSwaggerDefinition.

/**
 * Add API with the generated swagger from the DTO.
 *
 * @param apiDto     API DTO of the API
 * @param oasVersion Open API Definition version
 * @param username   Username
 * @param organization  Organization Identifier
 * @return Created API object
 * @throws APIManagementException Error while creating the API
 * @throws CryptoException        Error while encrypting
 */
public static API addAPIWithGeneratedSwaggerDefinition(APIDTO apiDto, String oasVersion, String username, String organization) throws APIManagementException, CryptoException {
    if (APIUtil.isOnPremResolver()) {
        String name = apiDto.getName();
        // replace all white spaces in the API Name
        apiDto.setName(name.replaceAll("\\s+", ""));
    }
    if (APIDTO.TypeEnum.ASYNC.equals(apiDto.getType())) {
        throw new APIManagementException("ASYNC API type does not support API creation from scratch", ExceptionCodes.API_CREATION_NOT_SUPPORTED_FOR_ASYNC_TYPE_APIS);
    }
    boolean isWSAPI = APIDTO.TypeEnum.WS.equals(apiDto.getType());
    boolean isAsyncAPI = isWSAPI || APIDTO.TypeEnum.WEBSUB.equals(apiDto.getType()) || APIDTO.TypeEnum.SSE.equals(apiDto.getType()) || APIDTO.TypeEnum.ASYNC.equals(apiDto.getType());
    username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
    APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
    // validate web socket api endpoint configurations
    if (isWSAPI && !PublisherCommonUtils.isValidWSAPI(apiDto)) {
        throw new APIManagementException("Endpoint URLs should be valid web socket URLs", ExceptionCodes.INVALID_ENDPOINT_URL);
    }
    // validate sandbox and production endpoints
    if (!PublisherCommonUtils.validateEndpoints(apiDto)) {
        throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
    }
    Map endpointConfig = (Map) apiDto.getEndpointConfig();
    CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, StringUtils.EMPTY, StringUtils.EMPTY, apiDto);
    // AWS Lambda: secret key encryption while creating the API
    if (apiDto.getEndpointConfig() != null) {
        if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
            String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            if (!StringUtils.isEmpty(secretKey)) {
                String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
                endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
                apiDto.setEndpointConfig(endpointConfig);
            }
        }
    }
    /* if (isWSAPI) {
            ArrayList<String> websocketTransports = new ArrayList<>();
            websocketTransports.add(APIConstants.WS_PROTOCOL);
            websocketTransports.add(APIConstants.WSS_PROTOCOL);
            apiDto.setTransport(websocketTransports);
        }*/
    API apiToAdd = prepareToCreateAPIByDTO(apiDto, apiProvider, username, organization);
    validateScopes(apiToAdd);
    // validate API categories
    List<APICategory> apiCategories = apiToAdd.getApiCategories();
    List<APICategory> apiCategoriesList = new ArrayList<>();
    for (APICategory category : apiCategories) {
        category.setOrganization(organization);
        apiCategoriesList.add(category);
    }
    apiToAdd.setApiCategories(apiCategoriesList);
    if (apiCategoriesList.size() > 0) {
        if (!APIUtil.validateAPICategories(apiCategoriesList, organization)) {
            throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
        }
    }
    if (!isAsyncAPI) {
        APIDefinition oasParser;
        if (RestApiConstants.OAS_VERSION_2.equalsIgnoreCase(oasVersion)) {
            oasParser = new OAS2Parser();
        } else {
            oasParser = new OAS3Parser();
        }
        SwaggerData swaggerData = new SwaggerData(apiToAdd);
        String apiDefinition = oasParser.generateAPIDefinition(swaggerData);
        apiToAdd.setSwaggerDefinition(apiDefinition);
    } else {
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String asyncApiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
        apiToAdd.setAsyncApiDefinition(asyncApiDefinition);
    }
    apiToAdd.setOrganization(organization);
    if (isAsyncAPI) {
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String apiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
        apiToAdd.setAsyncApiDefinition(apiDefinition);
    }
    // adding the api
    apiProvider.addAPI(apiToAdd);
    return apiToAdd;
}
Also used : OAS2Parser(org.wso2.carbon.apimgt.impl.definitions.OAS2Parser) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ArrayList(java.util.ArrayList) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) 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)

Example 7 with CryptoUtil

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

the class ApisApiServiceImpl method getAmazonResourceNamesOfAPI.

// AWS Lambda: rest api operation to get ARNs
@Override
public Response getAmazonResourceNamesOfAPI(String apiId, MessageContext messageContext) {
    JSONObject arns = new JSONObject();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        String endpointConfigString = api.getEndpointConfig();
        if (!StringUtils.isEmpty(endpointConfigString)) {
            JSONParser jsonParser = new JSONParser();
            JSONObject endpointConfig = (JSONObject) jsonParser.parse(endpointConfigString);
            if (endpointConfig != null) {
                if (endpointConfig.containsKey(APIConstants.AMZN_ACCESS_KEY) && endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY) && endpointConfig.containsKey(APIConstants.AMZN_REGION)) {
                    String accessKey = (String) endpointConfig.get(APIConstants.AMZN_ACCESS_KEY);
                    String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
                    String region = (String) endpointConfig.get(APIConstants.AMZN_REGION);
                    AWSCredentialsProvider credentialsProvider;
                    AWSLambda awsLambda;
                    if (StringUtils.isEmpty(accessKey) && StringUtils.isEmpty(secretKey) && StringUtils.isEmpty(region)) {
                        credentialsProvider = DefaultAWSCredentialsProviderChain.getInstance();
                        awsLambda = AWSLambdaClientBuilder.standard().withCredentials(credentialsProvider).build();
                    } else if (!StringUtils.isEmpty(accessKey) && !StringUtils.isEmpty(secretKey) && !StringUtils.isEmpty(region)) {
                        if (secretKey.length() == APIConstants.AWS_ENCRYPTED_SECRET_KEY_LENGTH) {
                            CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                            secretKey = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
                        }
                        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
                        credentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
                        awsLambda = AWSLambdaClientBuilder.standard().withCredentials(credentialsProvider).withRegion(region).build();
                    } else {
                        log.error("Missing AWS Credentials");
                        return null;
                    }
                    ListFunctionsResult listFunctionsResult = awsLambda.listFunctions();
                    List<FunctionConfiguration> functionConfigurations = listFunctionsResult.getFunctions();
                    arns.put("count", functionConfigurations.size());
                    JSONArray list = new JSONArray();
                    for (FunctionConfiguration functionConfiguration : functionConfigurations) {
                        list.put(functionConfiguration.getFunctionArn());
                    }
                    arns.put("list", list);
                    return Response.ok().entity(arns.toString()).build();
                }
            }
        }
    } catch (SdkClientException e) {
        if (e.getCause() instanceof UnknownHostException) {
            arns.put("error", "No internet connection to connect the given access method.");
            log.error("No internet connection to connect the given access method of API : " + apiId, e);
            return Response.serverError().entity(arns.toString()).build();
        } else {
            arns.put("error", "Unable to access Lambda functions under the given access method.");
            log.error("Unable to access Lambda functions under the given access method of API : " + apiId, e);
            return Response.serverError().entity(arns.toString()).build();
        }
    } catch (ParseException e) {
        String errorMessage = "Error while parsing endpoint config of the API: " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (CryptoException | UnsupportedEncodingException e) {
        String errorMessage = "Error while decrypting the secret key of the API: " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving the API: " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : AWSLambda(com.amazonaws.services.lambda.AWSLambda) ListFunctionsResult(com.amazonaws.services.lambda.model.ListFunctionsResult) UnknownHostException(java.net.UnknownHostException) FunctionConfiguration(com.amazonaws.services.lambda.model.FunctionConfiguration) JSONArray(org.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) JSONObject(org.json.simple.JSONObject) SdkClientException(com.amazonaws.SdkClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) CryptoException(org.wso2.carbon.core.util.CryptoException) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider)

Example 8 with CryptoUtil

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

the class APIMappingUtil method fromAPItoDTO.

public static APIDTO fromAPItoDTO(API model, boolean preserveCredentials, APIProvider apiProviderParam) throws APIManagementException {
    APIProvider apiProvider;
    if (apiProviderParam != null) {
        apiProvider = apiProviderParam;
    } else {
        apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    }
    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getApiName());
    dto.setVersion(model.getId().getVersion());
    String providerName = model.getId().getProviderName();
    dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    dto.setId(model.getUUID());
    String context = model.getContextTemplate();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    dto.setContext(context);
    dto.setCreatedTime(model.getCreatedTime());
    if (model.getLastUpdated() != null) {
        dto.setLastUpdatedTime(Long.toString(model.getLastUpdated().getTime()));
    }
    dto.setDescription(model.getDescription());
    dto.setIsDefaultVersion(model.isDefaultVersion());
    dto.setIsRevision(model.isRevision());
    dto.setRevisionedApiId(model.getRevisionedApiId());
    dto.setRevisionId(model.getRevisionId());
    dto.setEnableSchemaValidation(model.isEnabledSchemaValidation());
    AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
    advertiseInfoDTO.setAdvertised(model.isAdvertiseOnly());
    advertiseInfoDTO.setApiExternalProductionEndpoint(model.getApiExternalProductionEndpoint());
    advertiseInfoDTO.setApiExternalSandboxEndpoint(model.getApiExternalSandboxEndpoint());
    advertiseInfoDTO.setOriginalDevPortalUrl(model.getRedirectURL());
    advertiseInfoDTO.setApiOwner(model.getApiOwner());
    if (model.getAdvertiseOnlyAPIVendor() != null) {
        advertiseInfoDTO.setVendor(AdvertiseInfoDTO.VendorEnum.valueOf(model.getAdvertiseOnlyAPIVendor()));
    }
    dto.setAdvertiseInfo(advertiseInfoDTO);
    if (APIConstants.ENABLED.equals(model.getResponseCache())) {
        dto.setResponseCachingEnabled(Boolean.TRUE);
    } else {
        dto.setResponseCachingEnabled(Boolean.FALSE);
    }
    String serviceKey = model.getServiceInfo("key");
    if (StringUtils.isNotEmpty(serviceKey)) {
        APIServiceInfoDTO apiServiceInfoDTO = new APIServiceInfoDTO();
        apiServiceInfoDTO.setKey(serviceKey);
        apiServiceInfoDTO.setOutdated(Boolean.parseBoolean(model.getServiceInfo("outdated")));
        apiServiceInfoDTO.setName(model.getServiceInfo("name"));
        apiServiceInfoDTO.setVersion(model.getServiceInfo("version"));
        dto.setServiceInfo(apiServiceInfoDTO);
    }
    dto.setCacheTimeout(model.getCacheTimeout());
    String endpointConfig = model.getEndpointConfig();
    if (!StringUtils.isBlank(endpointConfig)) {
        try {
            JSONParser parser = new JSONParser();
            JSONObject endpointConfigJson = (JSONObject) parser.parse(endpointConfig);
            // AWS Lambda: set secret key based on preserveCredentials
            if (APIConstants.ENDPOINT_TYPE_AWSLAMBDA.equals(endpointConfigJson.get(APIConstants.API_ENDPOINT_CONFIG_PROTOCOL_TYPE))) {
                handleAWSCredentials(endpointConfigJson, preserveCredentials);
            }
            CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
            if (endpointConfigJson.get(APIConstants.ENDPOINT_SECURITY) != null) {
                JSONObject endpointSecurity = (JSONObject) endpointConfigJson.get(APIConstants.ENDPOINT_SECURITY);
                if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION) != null) {
                    JSONObject productionEndpointSecurity = (JSONObject) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
                    String productionEndpointType = (String) productionEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                    if (productionEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                        String customParametersString = (String) productionEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                        JSONObject customParameters = (JSONObject) parser.parse(customParametersString);
                        productionEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParameters);
                    }
                    if (APIConstants.OAuthConstants.OAUTH.equals(productionEndpointType)) {
                        String clientSecret = (String) productionEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET);
                        if (StringUtils.isNotEmpty(clientSecret)) {
                            productionEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, new String(cryptoUtil.base64DecodeAndDecrypt(clientSecret)));
                        }
                    }
                    endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION, productionEndpointSecurity);
                    endpointConfigJson.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                }
                if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX) != null) {
                    JSONObject sandboxEndpointSecurity = (JSONObject) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
                    String sandboxEndpointType = (String) sandboxEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                    if (sandboxEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                        String customParametersString = (String) sandboxEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                        JSONObject customParameters = (JSONObject) parser.parse(customParametersString);
                        sandboxEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParameters);
                    }
                    if (APIConstants.OAuthConstants.OAUTH.equals(sandboxEndpointType)) {
                        String clientSecret = (String) sandboxEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET);
                        if (StringUtils.isNotEmpty(clientSecret)) {
                            sandboxEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, new String(cryptoUtil.base64DecodeAndDecrypt(clientSecret)));
                        }
                    }
                    endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX, sandboxEndpointSecurity);
                    endpointConfigJson.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                }
                JSONObject jsonObject = handleEndpointSecurity(model, (JSONObject) endpointConfigJson.get(APIConstants.ENDPOINT_SECURITY), preserveCredentials);
                endpointConfigJson.put(APIConstants.ENDPOINT_SECURITY, jsonObject);
            }
            dto.setEndpointConfig(endpointConfigJson);
        } catch (ParseException e) {
            // logs the error and continues as this is not a blocker
            log.error("Cannot convert endpoint configurations when setting endpoint for API. " + "API ID = " + model.getId(), e);
        } catch (CryptoException e) {
            log.error("Error while decrypting client credentials for API: " + model.getId(), e);
        }
    }
    dto.setHasThumbnail(!StringUtils.isBlank(model.getThumbnailUrl()));
    List<MediationPolicyDTO> mediationPolicies = new ArrayList<>();
    String inMedPolicyName = model.getInSequence();
    if (inMedPolicyName != null && !inMedPolicyName.isEmpty()) {
        String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN;
        Mediation mediation = model.getInSequenceMediation();
        String mediationPolicyUUID = (mediation != null) ? mediation.getUuid() : null;
        boolean sharedStatus = (mediation != null) ? mediation.isGlobal() : false;
        MediationPolicyDTO inMedPolicy = new MediationPolicyDTO();
        inMedPolicy.setName(inMedPolicyName);
        inMedPolicy.setType(type.toUpperCase());
        inMedPolicy.setShared(sharedStatus);
        inMedPolicy.setId(mediationPolicyUUID);
        mediationPolicies.add(inMedPolicy);
    }
    String outMedPolicyName = model.getOutSequence();
    if (outMedPolicyName != null && !outMedPolicyName.isEmpty()) {
        String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT;
        Mediation mediation = model.getOutSequenceMediation();
        String mediationPolicyUUID = (mediation != null) ? mediation.getUuid() : null;
        boolean sharedStatus = (mediation != null) ? mediation.isGlobal() : false;
        MediationPolicyDTO outMedPolicy = new MediationPolicyDTO();
        outMedPolicy.setName(outMedPolicyName);
        outMedPolicy.setType(type.toUpperCase());
        outMedPolicy.setShared(sharedStatus);
        outMedPolicy.setId(mediationPolicyUUID);
        mediationPolicies.add(outMedPolicy);
    }
    String faultSequenceName = model.getFaultSequence();
    if (faultSequenceName != null && !faultSequenceName.isEmpty()) {
        String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT;
        Mediation mediation = model.getFaultSequenceMediation();
        String mediationPolicyUUID = (mediation != null) ? mediation.getUuid() : null;
        boolean sharedStatus = (mediation != null) ? mediation.isGlobal() : false;
        MediationPolicyDTO faultMedPolicy = new MediationPolicyDTO();
        faultMedPolicy.setName(faultSequenceName);
        faultMedPolicy.setType(type.toUpperCase());
        faultMedPolicy.setShared(sharedStatus);
        faultMedPolicy.setId(mediationPolicyUUID);
        mediationPolicies.add(faultMedPolicy);
    }
    dto.setMediationPolicies(mediationPolicies);
    dto.setLifeCycleStatus(model.getStatus());
    String subscriptionAvailability = model.getSubscriptionAvailability();
    if (subscriptionAvailability != null) {
        dto.setSubscriptionAvailability(mapSubscriptionAvailabilityFromAPItoDTO(subscriptionAvailability));
    }
    if (model.getSubscriptionAvailableTenants() != null) {
        dto.setSubscriptionAvailableTenants(Arrays.asList(model.getSubscriptionAvailableTenants().split(",")));
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
    boolean isAsyncAPI = APIDTO.TypeEnum.WS.toString().equals(model.getType()) || APIDTO.TypeEnum.WEBSUB.toString().equals(model.getType()) || APIDTO.TypeEnum.SSE.toString().equals(model.getType()) || APIDTO.TypeEnum.ASYNC.toString().equals(model.getType());
    // Get Swagger definition which has URL templates, scopes and resource details
    model.getId().setUuid(model.getUuid());
    if (!isAsyncAPI) {
        // Get from swagger definition
        List<APIOperationsDTO> apiOperationsDTO;
        String apiSwaggerDefinition;
        if (model.getSwaggerDefinition() != null) {
            apiSwaggerDefinition = model.getSwaggerDefinition();
        } else {
            apiSwaggerDefinition = apiProvider.getOpenAPIDefinition(model.getId(), tenantDomain);
        }
        // We will fetch operations from the swagger definition and not from the AM_API_URL_MAPPING table: table
        // entries may have API level throttling tiers listed in case API level throttling is selected for the API.
        // This will lead the x-throttling-tiers of API definition to get overwritten. (wso2/product-apim#11240)
        apiOperationsDTO = getOperationsFromSwaggerDef(model, apiSwaggerDefinition);
        // since the operation details goes missing after fetching operations list from the swagger definition, we
        // have to set them back from the original API model.
        setOperationPoliciesToOperationsDTO(model, apiOperationsDTO);
        dto.setOperations(apiOperationsDTO);
        List<ScopeDTO> scopeDTOS = getScopesFromSwagger(apiSwaggerDefinition);
        dto.setScopes(getAPIScopesFromScopeDTOs(scopeDTOS, apiProvider));
    } else {
        // Get from asyncapi definition
        List<APIOperationsDTO> apiOperationsDTO = getOperationsFromAPI(model);
        dto.setOperations(apiOperationsDTO);
        String asyncAPIDefinition;
        if (model.getAsyncApiDefinition() != null) {
            asyncAPIDefinition = model.getAsyncApiDefinition();
        } else {
            asyncAPIDefinition = apiProvider.getAsyncAPIDefinition(model.getId().getUUID(), tenantDomain);
        }
        if (asyncAPIDefinition != null) {
            List<ScopeDTO> scopeDTOS = getScopesFromAsyncAPI(asyncAPIDefinition);
            dto.setScopes(getAPIScopesFromScopeDTOs(scopeDTOS, apiProvider));
        }
    }
    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);
    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<String> tiersToReturn = new ArrayList<>();
    for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
        tiersToReturn.add(tier.getName());
    }
    dto.setPolicies(tiersToReturn);
    dto.setApiThrottlingPolicy(model.getApiLevelPolicy());
    // APIs created with type set to "NULL" will be considered as "HTTP"
    if (model.getType() == null || model.getType().toLowerCase().equals("null")) {
        dto.setType(APIDTO.TypeEnum.HTTP);
    } else {
        dto.setType(APIDTO.TypeEnum.fromValue(model.getType()));
    }
    if (!APIConstants.APITransportType.WS.toString().equals(model.getType())) {
        if (StringUtils.isEmpty(model.getTransports())) {
            List<String> transports = new ArrayList<>();
            transports.add(APIConstants.HTTPS_PROTOCOL);
            dto.setTransport(transports);
        }
        dto.setTransport(Arrays.asList(model.getTransports().split(",")));
    }
    if (StringUtils.isEmpty(model.getTransports())) {
        dto.setVisibility(APIDTO.VisibilityEnum.PUBLIC);
    }
    dto.setVisibility(mapVisibilityFromAPItoDTO(model.getVisibility()));
    if (model.getVisibleRoles() != null) {
        dto.setVisibleRoles(Arrays.asList(model.getVisibleRoles().split(",")));
    }
    if (model.getVisibleTenants() != null) {
        dto.setVisibleRoles(Arrays.asList(model.getVisibleTenants().split(",")));
    }
    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        List<APIInfoAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
        Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = new HashMap<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            APIInfoAdditionalPropertiesDTO additionalPropertiesDTO = new APIInfoAdditionalPropertiesDTO();
            APIInfoAdditionalPropertiesMapDTO apiInfoAdditionalPropertiesMapDTO = new APIInfoAdditionalPropertiesMapDTO();
            String key = (String) propertyKey;
            int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
            additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
            apiInfoAdditionalPropertiesMapDTO.setValue((String) additionalProperties.get(key));
            if (index > 0) {
                additionalPropertiesDTO.setName(key.substring(0, index));
                apiInfoAdditionalPropertiesMapDTO.setName(key.substring(0, index));
                additionalPropertiesDTO.setDisplay(true);
            } else {
                additionalPropertiesDTO.setName(key);
                apiInfoAdditionalPropertiesMapDTO.setName(key);
                additionalPropertiesDTO.setDisplay(false);
            }
            apiInfoAdditionalPropertiesMapDTO.setDisplay(false);
            additionalPropertiesMap.put(key, apiInfoAdditionalPropertiesMapDTO);
            additionalPropertiesList.add(additionalPropertiesDTO);
        }
        dto.setAdditionalProperties(additionalPropertiesList);
        dto.setAdditionalPropertiesMap(additionalPropertiesMap);
    }
    if (model.getImplementation() != null) {
        dto.setEndpointImplementationType(APIDTO.EndpointImplementationTypeEnum.valueOf(model.getImplementation()));
    }
    dto.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY.equals(model.getAccessControl()) ? APIDTO.AccessControlEnum.RESTRICTED : APIDTO.AccessControlEnum.NONE);
    if (model.getAccessControlRoles() != null) {
        dto.setAccessControlRoles(Arrays.asList(model.getAccessControlRoles().split(",")));
    }
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);
    APICorsConfigurationDTO apiCorsConfigurationDTO = new APICorsConfigurationDTO();
    CORSConfiguration corsConfiguration = model.getCorsConfiguration();
    if (corsConfiguration == null) {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAccessControlAllowOrigins());
    apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAccessControlAllowHeaders());
    apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAccessControlAllowMethods());
    apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isCorsConfigurationEnabled());
    apiCorsConfigurationDTO.setAccessControlAllowCredentials(corsConfiguration.isAccessControlAllowCredentials());
    dto.setCorsConfiguration(apiCorsConfigurationDTO);
    WebsubSubscriptionConfigurationDTO websubSubscriptionConfigurationDTO = new WebsubSubscriptionConfigurationDTO();
    WebsubSubscriptionConfiguration websubSubscriptionConfiguration = model.getWebsubSubscriptionConfiguration();
    if (websubSubscriptionConfiguration == null) {
        websubSubscriptionConfiguration = APIUtil.getDefaultWebsubSubscriptionConfiguration();
    }
    websubSubscriptionConfigurationDTO.setEnable(websubSubscriptionConfiguration.isEnable());
    websubSubscriptionConfigurationDTO.setSecret(websubSubscriptionConfiguration.getSecret());
    websubSubscriptionConfigurationDTO.setSigningAlgorithm(websubSubscriptionConfiguration.getSigningAlgorithm());
    websubSubscriptionConfigurationDTO.setSignatureHeader(websubSubscriptionConfiguration.getSignatureHeader());
    dto.setWebsubSubscriptionConfiguration(websubSubscriptionConfigurationDTO);
    if (model.getWsdlUrl() != null) {
        WSDLInfoDTO wsdlInfoDTO = getWsdlInfoDTO(model);
        dto.setWsdlInfo(wsdlInfoDTO);
    }
    dto.setWsdlUrl(model.getWsdlUrl());
    setEndpointSecurityFromModelToApiDTO(model, dto, preserveCredentials);
    setMaxTpsFromModelToApiDTO(model, dto);
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    if (null != model.getLastUpdated()) {
        Date lastUpdateDate = model.getLastUpdated();
        Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
        dto.setLastUpdatedTime(String.valueOf(timeStamp));
    }
    if (null != model.getCreatedTime()) {
        Date created = new Date(Long.parseLong(model.getCreatedTime()));
        Timestamp timeStamp = new Timestamp(created.getTime());
        dto.setCreatedTime(String.valueOf(timeStamp.getTime()));
    }
    dto.setWorkflowStatus(model.getWorkflowStatus());
    List<APICategory> apiCategories = model.getApiCategories();
    List<String> categoryNameList = new ArrayList<>();
    if (apiCategories != null && !apiCategories.isEmpty()) {
        for (APICategory category : apiCategories) {
            categoryNameList.add(category.getName());
        }
    }
    dto.setCategories(categoryNameList);
    dto.setKeyManagers(model.getKeyManagers());
    if (model.getAudience() != null) {
        dto.setAudience(AudienceEnum.valueOf(model.getAudience()));
    }
    dto.setGatewayVendor(StringUtils.toRootLowerCase(model.getGatewayVendor()));
    if (model.getAsyncTransportProtocols() != null) {
        dto.setAsyncTransportProtocols(Arrays.asList(model.getAsyncTransportProtocols().split(",")));
    }
    return dto;
}
Also used : APIInfoAdditionalPropertiesMapDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO) AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AdvertiseInfoDTO) WebsubSubscriptionConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WebsubSubscriptionConfigurationDTO) HashMap(java.util.HashMap) ScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ScopeDTO) APIScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIScopeDTO) ArrayList(java.util.ArrayList) APIUtil.getDefaultWebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.impl.utils.APIUtil.getDefaultWebsubSubscriptionConfiguration) WebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) Timestamp(java.sql.Timestamp) MediationPolicyDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MediationPolicyDTO) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIBusinessInformationDTO) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) Tier(org.wso2.carbon.apimgt.api.model.Tier) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) Date(java.util.Date) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) WSDLInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WSDLInfoDTO) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) JSONObject(org.json.simple.JSONObject) APIServiceInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIServiceInfoDTO) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) CryptoException(org.wso2.carbon.core.util.CryptoException) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 9 with CryptoUtil

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

the class APIAdminImpl method getDecryptedValue.

private String getDecryptedValue(String value) throws APIManagementException {
    try {
        JsonElement encryptedJsonValue = new JsonParser().parse(value);
        if (encryptedJsonValue instanceof JsonObject) {
            JsonObject jsonObject = (JsonObject) encryptedJsonValue;
            JsonPrimitive encryptedValue = jsonObject.getAsJsonPrimitive(APIConstants.ENCRYPTED_VALUE);
            if (encryptedValue.isBoolean()) {
                JsonPrimitive valueElement = jsonObject.getAsJsonPrimitive(APIConstants.VALUE);
                if (encryptedValue.getAsBoolean()) {
                    if (valueElement.isString()) {
                        CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                        return new String(cryptoUtil.decrypt(valueElement.getAsString().getBytes()));
                    }
                }
            }
        }
    } catch (CryptoException e) {
        throw new APIManagementException("Error while Decrypting value", e);
    } catch (JsonParseException e) {
        // check Element is a json element
        if (log.isDebugEnabled()) {
            log.debug("Error while parsing element " + value, e);
        }
    }
    return value;
}
Also used : CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) CryptoException(org.wso2.carbon.core.util.CryptoException) JsonParseException(com.google.gson.JsonParseException) JsonParser(com.google.gson.JsonParser)

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