Search in sources :

Example 1 with Util

use of org.wso2.carbon.identity.api.server.common.Util in project carbon-apimgt by wso2.

the class APIUtil method executeQueryOnStreamProcessor.

/**
 * Util method to call SP rest api to invoke queries.
 *
 * @param appName SP app name that the query should run against
 * @param query   query
 * @return jsonObj JSONObject of the response
 * @throws APIManagementException
 */
public static JSONObject executeQueryOnStreamProcessor(String appName, String query) throws APIManagementException {
    String spEndpoint = APIManagerAnalyticsConfiguration.getInstance().getDasServerUrl() + "/stores/query";
    String spUserName = APIManagerAnalyticsConfiguration.getInstance().getDasServerUser();
    String spPassword = APIManagerAnalyticsConfiguration.getInstance().getDasServerPassword();
    byte[] encodedAuth = Base64.encodeBase64((spUserName + ":" + spPassword).getBytes(Charset.forName("ISO-8859-1")));
    String authHeader = "Basic " + new String(encodedAuth);
    URL spURL;
    try {
        spURL = new URL(spEndpoint);
        HttpClient httpClient = APIUtil.getHttpClient(spURL.getPort(), spURL.getProtocol());
        HttpPost httpPost = new HttpPost(spEndpoint);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        JSONObject obj = new JSONObject();
        obj.put("appName", appName);
        obj.put("query", query);
        if (log.isDebugEnabled()) {
            log.debug("Request from SP: " + obj.toJSONString());
        }
        StringEntity requestEntity = new StringEntity(obj.toJSONString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        HttpResponse response;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String error = "Error while invoking SP rest api :  " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
                log.error(error);
                throw new APIManagementException(error);
            }
            String responseStr = EntityUtils.toString(entity);
            if (log.isDebugEnabled()) {
                log.debug("Response from SP: " + responseStr);
            }
            JSONParser parser = new JSONParser();
            return (JSONObject) parser.parse(responseStr);
        } catch (ClientProtocolException e) {
            handleException("Error while connecting to the server ", e);
        } catch (IOException e) {
            handleException("Error while connecting to the server ", e);
        } catch (ParseException e) {
            handleException("Error while parsing the response ", e);
        } finally {
            httpPost.reset();
        }
    } catch (MalformedURLException e) {
        handleException("Error while parsing the stream processor url", e);
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MalformedURLException(java.net.MalformedURLException) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) URL(java.net.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) ApacheFeignHttpClient(org.wso2.carbon.apimgt.impl.kmclient.ApacheFeignHttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 2 with Util

use of org.wso2.carbon.identity.api.server.common.Util in project carbon-apimgt by wso2.

the class APIUtil method getAPIArtifact.

/**
 * Util method to return the artifact from a registry resource path
 *
 * @param apiIdentifier
 * @param registry
 * @return
 * @throws APIManagementException
 */
public static GenericArtifact getAPIArtifact(APIIdentifier apiIdentifier, Registry registry) throws APIManagementException {
    String apiPath = APIUtil.getAPIPath(apiIdentifier);
    GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
    if (artifactManager == null) {
        String errorMessage = "Artifact manager is null when getting generic artifact for API " + apiIdentifier.getApiName();
        log.error(errorMessage);
        throw new APIManagementException(errorMessage);
    }
    try {
        Resource apiResource = registry.get(apiPath);
        String artifactId = apiResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + apiPath);
        }
        return artifactManager.getGenericArtifact(artifactId);
    } catch (RegistryException e) {
        handleException("Failed to get API artifact from : " + apiPath, e);
        return null;
    }
}
Also used : GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 3 with Util

use of org.wso2.carbon.identity.api.server.common.Util 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 Util

use of org.wso2.carbon.identity.api.server.common.Util 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 5 with Util

use of org.wso2.carbon.identity.api.server.common.Util in project ballerina by ballerina-lang.

the class ParserUtils method getAllPackages.

/**
 * Get All Native Packages.
 *
 * @return {@link Map} Package name, package functions and connectors
 */
public static Map<String, ModelPackage> getAllPackages() {
    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    // TODO: remove once the packerina api for package listing is available
    final String[] packageNames = { "net.http", "net.http.authadaptor", "net.http.endpoints", "net.http.mock", "net.http.swagger", "net.uri", "mime", "net.websub", "net.websub.hub", "net.grpc", "auth", "auth.authz", "auth.authz.permissionstore", "auth.basic", "auth.jwtAuth", "auth.userstore", "auth.utils", "caching", "collections", "config", "data.sql", "file", "internal", "io", "jwt", "jwt.signature", "log", "math", "os", "reflect", "runtime", "security.crypto", "task", "time", "transactions.coordinator", "user", "util" };
    try {
        List<BLangPackage> builtInPackages = LSPackageLoader.getBuiltinPackages();
        for (BLangPackage bLangPackage : builtInPackages) {
            loadPackageMap(bLangPackage.packageID.getName().getValue(), bLangPackage, modelPackage);
        }
        CompilerContext context = CommonUtil.prepareTempCompilerContext();
        for (String packageName : packageNames) {
            PackageID packageID = new PackageID(new Name("ballerina"), new Name(packageName), new Name("0.0.0"));
            BLangPackage bLangPackage = LSPackageLoader.getPackageById(context, packageID);
            loadPackageMap(bLangPackage.packageID.getName().getValue(), bLangPackage, modelPackage);
        }
    } catch (Exception e) {
        // Above catch is to fail safe composer front end due to core errors.
        logger.warn("Error while loading packages");
    }
    return modelPackage;
}
Also used : BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) HashMap(java.util.HashMap) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) PackageID(org.ballerinalang.model.elements.PackageID) IOException(java.io.IOException) Name(org.wso2.ballerinalang.compiler.util.Name)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)5 IOException (java.io.IOException)4 KeyStoreManager (org.wso2.carbon.core.util.KeyStoreManager)4 Resource (org.wso2.carbon.registry.core.Resource)4 KeyStore (java.security.KeyStore)3 ArrayList (java.util.ArrayList)3 KeyStoreException (java.security.KeyStoreException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 PrivateKey (java.security.PrivateKey)2 CertificateEncodingException (java.security.cert.CertificateEncodingException)2 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 Format (java.text.Format)2 SimpleDateFormat (java.text.SimpleDateFormat)2 HashMap (java.util.HashMap)2 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)2 ServerConfiguration (org.wso2.carbon.base.ServerConfiguration)2 CryptoUtil (org.wso2.carbon.core.util.CryptoUtil)2 IdentitySCIMException (org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException)2