Search in sources :

Example 1 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class APIStoreImpl method addCompositeApiFromDefinition.

/**
 * {@inheritDoc}
 */
@Override
public String addCompositeApiFromDefinition(String swaggerResourceUrl) throws APIManagementException {
    try {
        URL url = new URL(swaggerResourceUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod(APIMgtConstants.HTTP_GET);
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), StandardCharsets.UTF_8);
            CompositeAPI.Builder apiBuilder = apiDefinitionFromSwagger20.generateCompositeApiFromSwaggerResource(getUsername(), responseStr);
            apiBuilder.apiDefinition(responseStr);
            addCompositeApi(apiBuilder);
            return apiBuilder.getId();
        } else {
            throw new APIManagementException("Error while getting swagger resource from url : " + url, ExceptionCodes.API_DEFINITION_MALFORMED);
        }
    } catch (UnsupportedEncodingException e) {
        String msg = "Unsupported encoding exception while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (ProtocolException e) {
        String msg = "Protocol exception while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (MalformedURLException e) {
        String msg = "Malformed url while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (IOException e) {
        String msg = "Error while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    }
}
Also used : ProtocolException(java.net.ProtocolException) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL)

Example 2 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateMgtUtils method validateCertificate.

/**
 * To validate the current certificate and alias.
 *
 * @param alias       Alias of the certificate.
 * @param certificate Bas64 endcoded certificated.
 * @return response code based on the validation
 */
public ResponseCode validateCertificate(String alias, int tenantId, String certificate) {
    File trustStoreFile = new File(trustStoreLocation);
    ResponseCode responseCode = ResponseCode.SUCCESS;
    ByteArrayInputStream serverCert = null;
    try {
        synchronized (this) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            try (InputStream localTrustStoreStream = new FileInputStream(trustStoreFile)) {
                trustStore.load(localTrustStoreStream, trustStorePassword);
            }
            if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) {
                responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE;
            }
        }
        if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) {
            byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
            serverCert = new ByteArrayInputStream(cert);
            if (serverCert.available() == 0) {
                responseCode = ResponseCode.CERTIFICATE_NOT_FOUND;
            } else {
                CertificateFactory cf = CertificateFactory.getInstance(certificateType);
                while (serverCert.available() > 0) {
                    Certificate generatedCertificate = cf.generateCertificate(serverCert);
                    X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
                    if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
                        responseCode = ResponseCode.CERTIFICATE_EXPIRED;
                    }
                }
            }
        }
    } catch (IOException e) {
        log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (CertificateException e) {
        log.error("Certificate Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (NoSuchAlgorithmException e) {
        log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether " + "alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (KeyStoreException e) {
        log.error("KeyStore Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } finally {
        closeStreams(serverCert);
    }
    return responseCode;
}
Also used : ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 3 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateMgtUtils method updateCertificate.

/**
 * Method to update the certificate which matches the given alias.
 *
 * @param certificate: The base64 encoded certificate string.
 * @param alias        : Alias of the certificate that should be retrieved.
 * @return :
 */
public synchronized ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException {
    try {
        File trustStoreFile = new File(trustStoreLocation);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream localTrustStoreStream = new FileInputStream(trustStoreFile)) {
            trustStore.load(localTrustStoreStream, trustStorePassword);
        }
        if (trustStore.getCertificate(alias) == null) {
            log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found" + " in the trust store.");
            return ResponseCode.CERTIFICATE_NOT_FOUND;
        }
        // Generate the certificate from the input string.
        byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
        Certificate newCertificate;
        try (InputStream certificateStream = new ByteArrayInputStream(cert)) {
            if (certificateStream.available() == 0) {
                log.error("Certificate is empty for the provided alias " + alias);
                return ResponseCode.INTERNAL_SERVER_ERROR;
            }
            CertificateFactory certificateFactory = CertificateFactory.getInstance(certificateType);
            newCertificate = certificateFactory.generateCertificate(certificateStream);
        }
        X509Certificate x509Certificate = (X509Certificate) newCertificate;
        if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
            log.error("Could not update the certificate. The certificate expired.");
            return ResponseCode.CERTIFICATE_EXPIRED;
        }
        // If the certificate is not expired, delete the existing certificate and add the new cert.
        trustStore.deleteEntry(alias);
        // Store the certificate in the trust store.
        trustStore.setCertificateEntry(alias, newCertificate);
        try (OutputStream fileOutputStream = new FileOutputStream(trustStoreFile)) {
            trustStore.store(fileOutputStream, trustStorePassword);
        }
    } catch (IOException e) {
        throw new CertificateManagementException("Error updating certificate.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error generating the certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Error loading the keystore.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error updating the certificate in the keystore.", e);
    }
    return ResponseCode.SUCCESS;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 4 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class OAS3Parser method generateExample.

/**
 * This method  generates Sample/Mock payloads for Open API Specification (3.0) definitions
 *
 * @param apiDefinition API Definition
 * @return swagger Json
 */
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    OpenAPI swagger = parseAttemptForV3.getOpenAPI();
    // return map
    Map<String, Object> returnMap = new HashMap<>();
    // List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
        int minResponseCode = 0;
        int responseCode = 0;
        String path = entry.getKey();
        Map<String, Schema> definitions = swagger.getComponents().getSchemas();
        // operation map to get verb
        Map<PathItem.HttpMethod, Operation> operationMap = entry.getValue().readOperationsMap();
        List<Operation> operations = swagger.getPaths().get(path).readOperations();
        for (int i = 0, operationsSize = operations.size(); i < operationsSize; i++) {
            Operation op = operations.get(i);
            // initializing apiResourceMediationPolicyObject
            APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
            // setting path for apiResourceMediationPolicyObject
            apiResourceMediationPolicyObject.setPath(path);
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            // for each HTTP method get the verb
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            // for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            Object[] operationsArray = operationMap.entrySet().toArray();
            if (operationsArray.length > i) {
                Map.Entry<PathItem.HttpMethod, Operation> operationEntry = (Map.Entry<PathItem.HttpMethod, Operation>) operationsArray[i];
                apiResourceMediationPolicyObject.setVerb(String.valueOf(operationEntry.getKey()));
            } else {
                throw new APIManagementException("Cannot find the HTTP method for the API Resource Mediation Policy");
            }
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                Content content = op.getResponses().get(responseEntry).getContent();
                if (content != null) {
                    MediaType applicationJson = content.get(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
                    MediaType applicationXml = content.get(APIConstants.APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        Schema jsonSchema = applicationJson.getSchema();
                        if (jsonSchema != null) {
                            String jsonExample = getJsonExample(jsonSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                            respCodeInitialized = true;
                            hasJsonPayload = true;
                        }
                    }
                    if (applicationXml != null) {
                        Schema xmlSchema = applicationXml.getSchema();
                        if (xmlSchema != null) {
                            String xmlExample = getXmlExample(xmlSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                            hasXmlPayload = true;
                        }
                    }
                } else {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            // inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            // gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            // sets script to each resource in the swagger
            op.addExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
        }
        checkAndSetEmptyScope(swagger);
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathItem(io.swagger.v3.oas.models.PathItem) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MediaType(io.swagger.v3.oas.models.media.MediaType) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Content(io.swagger.v3.oas.models.media.Content) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 5 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class APIProviderImpl method updateCertificate.

@Override
public int updateCertificate(String certificateString, String alias) throws APIManagementException {
    ResponseCode responseCode = certificateManager.updateCertificate(certificateString, alias);
    if (responseCode != null && responseCode.getResponseCode() == ResponseCode.SUCCESS.getResponseCode()) {
        CertificateEvent certificateEvent = new CertificateEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.ENDPOINT_CERTIFICATE_UPDATE.toString(), tenantDomain, alias);
        APIUtil.sendNotification(certificateEvent, APIConstants.NotifierType.CERTIFICATE.name());
    }
    return responseCode != null ? responseCode.getResponseCode() : ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode();
}
Also used : ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) CertificateEvent(org.wso2.carbon.apimgt.impl.notifier.events.CertificateEvent)

Aggregations

ResponseCode (org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode)18 Test (org.junit.Test)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 IOException (java.io.IOException)8 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 ArrayList (java.util.ArrayList)5 CertificateMetadataDTO (org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 UserStoreException (org.wso2.carbon.user.api.UserStoreException)4 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)3 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)3 API (org.wso2.carbon.apimgt.api.model.API)3 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)3 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)3 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)3 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)3 CertificateAliasExistsException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateAliasExistsException)3 CertificateManagementException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException)3