Search in sources :

Example 1 with CertificateMgtUtils

use of org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils in project carbon-apimgt by wso2.

the class TemplateBuilderUtil method getAPITemplateBuilder.

public static APITemplateBuilderImpl getAPITemplateBuilder(APIProduct apiProduct, String tenantDomain, List<ClientCertificateDTO> clientCertificateDTOS, Map<String, APIDTO> associatedAPIMap) throws APIManagementException {
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    APITemplateBuilderImpl vtb = new APITemplateBuilderImpl(apiProduct, associatedAPIMap);
    Map<String, String> latencyStatsProperties = new HashMap<String, String>();
    latencyStatsProperties.put(APIConstants.API_UUID, apiProduct.getUuid());
    if (!APIUtil.isStreamingApi(apiProduct)) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIMgtLatencyStatsHandler", latencyStatsProperties);
    }
    Map<String, String> corsProperties = new HashMap<>();
    corsProperties.put(APIConstants.CORSHeaders.IMPLEMENTATION_TYPE_HANDLER_VALUE, APIConstants.IMPLEMENTATION_TYPE_ENDPOINT);
    // Get authorization header from the API object or from the tenant registry
    String authorizationHeader;
    if (!StringUtils.isBlank(apiProduct.getAuthorizationHeader())) {
        authorizationHeader = apiProduct.getAuthorizationHeader();
    } else {
        // Retrieves the auth configuration from tenant registry or api-manager.xml if not available
        // in tenant registry
        authorizationHeader = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.AUTHORIZATION_HEADER);
    }
    if (!StringUtils.isBlank(authorizationHeader)) {
        corsProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    if (apiProduct.getCorsConfiguration() != null && apiProduct.getCorsConfiguration().isCorsConfigurationEnabled()) {
        CORSConfiguration corsConfiguration = apiProduct.getCorsConfiguration();
        if (corsConfiguration.getAccessControlAllowHeaders() != null) {
            StringBuilder allowHeaders = new StringBuilder();
            for (String header : corsConfiguration.getAccessControlAllowHeaders()) {
                allowHeaders.append(header).append(',');
            }
            if (allowHeaders.length() != 0) {
                allowHeaders.deleteCharAt(allowHeaders.length() - 1);
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_HEADERS_HANDLER_VALUE, allowHeaders.toString());
            }
        }
        if (corsConfiguration.getAccessControlAllowOrigins() != null) {
            StringBuilder allowOrigins = new StringBuilder();
            for (String origin : corsConfiguration.getAccessControlAllowOrigins()) {
                allowOrigins.append(origin).append(',');
            }
            if (allowOrigins.length() != 0) {
                allowOrigins.deleteCharAt(allowOrigins.length() - 1);
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_ORIGIN_HANDLER_VALUE, allowOrigins.toString());
            }
        }
        if (corsConfiguration.getAccessControlAllowMethods() != null) {
            StringBuilder allowedMethods = new StringBuilder();
            for (String methods : corsConfiguration.getAccessControlAllowMethods()) {
                allowedMethods.append(methods).append(',');
            }
            if (allowedMethods.length() != 0) {
                allowedMethods.deleteCharAt(allowedMethods.length() - 1);
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_METHODS_HANDLER_VALUE, allowedMethods.toString());
            }
        }
        if (corsConfiguration.isAccessControlAllowCredentials()) {
            corsProperties.put(APIConstants.CORSHeaders.ALLOW_CREDENTIALS_HANDLER_VALUE, String.valueOf(corsConfiguration.isAccessControlAllowCredentials()));
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
    } else if (APIUtil.isCORSEnabled()) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
    }
    vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIStatusHandler", Collections.emptyMap());
    Map<String, String> clientCertificateObject = null;
    CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
    if (clientCertificateDTOS != null) {
        clientCertificateObject = new HashMap<>();
        for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
            clientCertificateObject.put(certificateMgtUtils.getUniqueIdentifierOfCertificate(clientCertificateDTO.getCertificate()), clientCertificateDTO.getTierName());
        }
    }
    Map<String, String> authProperties = new HashMap<String, String>();
    if (!StringUtils.isBlank(authorizationHeader)) {
        authProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    String apiSecurity = apiProduct.getApiSecurity();
    String apiLevelPolicy = apiProduct.getProductLevelPolicy();
    authProperties.put(APIConstants.API_SECURITY, apiSecurity);
    authProperties.put(APIConstants.API_LEVEL_POLICY, apiLevelPolicy);
    if (clientCertificateObject != null) {
        authProperties.put(APIConstants.CERTIFICATE_INFORMATION, clientCertificateObject.toString());
    }
    // Get RemoveHeaderFromOutMessage from tenant registry or api-manager.xml
    String removeHeaderFromOutMessage = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE);
    if (!StringUtils.isBlank(removeHeaderFromOutMessage)) {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, removeHeaderFromOutMessage);
    } else {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE_DEFAULT);
    }
    authProperties.put("apiType", APIConstants.ApiTypes.PRODUCT_API.name());
    vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler", authProperties);
    Map<String, String> properties = new HashMap<String, String>();
    if (apiProduct.getProductionMaxTps() != null) {
        properties.put("productionMaxCount", apiProduct.getProductionMaxTps());
    }
    if (apiProduct.getSandboxMaxTps() != null) {
        properties.put("sandboxMaxCount", apiProduct.getSandboxMaxTps());
    }
    if (!APIUtil.isStreamingApi(apiProduct)) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler", properties);
        properties = new HashMap<String, String>();
        properties.put("configKey", APIConstants.GA_CONF_KEY);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtGoogleAnalyticsTrackingHandler", properties);
        String extensionHandlerPosition = getExtensionHandlerPosition(tenantDomain);
        if ("top".equalsIgnoreCase(extensionHandlerPosition)) {
            vtb.addHandlerPriority("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap(), 2);
        } else {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap());
        }
    }
    return vtb;
}
Also used : CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) HashMap(java.util.HashMap) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) CertificateMgtUtils(org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils) APITemplateBuilderImpl(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl)

Example 2 with CertificateMgtUtils

use of org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils in project carbon-apimgt by wso2.

the class CertificateManagerImplTest method testEmptyCertAddToGateway.

@Test
public void testEmptyCertAddToGateway() throws NoSuchFieldException, IllegalAccessException {
    CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
    ResponseCode responseCode = certificateMgtUtils.addCertificateToTrustStore("", "testalias");
    Assert.assertEquals(ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode(), responseCode.getResponseCode());
}
Also used : CertificateMgtUtils(org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with CertificateMgtUtils

use of org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils in project carbon-apimgt by wso2.

the class CertificateMgtUtilTest method testAddCertificateWithFileNotFoundException.

@Test
public void testAddCertificateWithFileNotFoundException() throws NoSuchFieldException, IllegalAccessException {
    Field field = CertificateMgtUtils.class.getDeclaredField(TRUST_STORE_FIELD);
    field.setAccessible(true);
    field.set(certificateMgtUtils, INVALID_TRUST_STORE_FILE);
    ResponseCode responseCode = certificateMgtUtils.addCertificateToTrustStore(ALIAS, BASE64_ENCODED_ERROR_CERT);
    field.set(certificateMgtUtils, CERT_PATH.getPath());
    Assert.assertEquals(responseCode, ResponseCode.INTERNAL_SERVER_ERROR);
}
Also used : Field(java.lang.reflect.Field) ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) Test(org.junit.Test)

Example 4 with CertificateMgtUtils

use of org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAPIClientCertificateByAlias.

@Override
public Response getAPIClientCertificateByAlias(String alias, String apiId, MessageContext messageContext) {
    String organization = null;
    CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
    try {
        organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
        CertificateInformationDTO certificateInformationDTO = certificateMgtUtils.getCertificateInfo(clientCertificateDTO.getCertificate());
        if (certificateInformationDTO != null) {
            CertificateInfoDTO certificateInfoDTO = CertificateMappingUtil.fromCertificateInformationToDTO(certificateInformationDTO);
            return Response.ok().entity(certificateInfoDTO).build();
        } else {
            RestApiUtil.handleResourceNotFoundError("Certificate is empty for alias " + alias, log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving the client certificate with alias " + alias + " for the tenant " + organization, e, log);
    }
    return null;
}
Also used : 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) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) CertificateInformationDTO(org.wso2.carbon.apimgt.api.dto.CertificateInformationDTO) CertificateMgtUtils(org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) CertificateInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CertificateInfoDTO)

Example 5 with CertificateMgtUtils

use of org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils in project carbon-apimgt by wso2.

the class TemplateBuilderUtil method getAPITemplateBuilder.

public static APITemplateBuilderImpl getAPITemplateBuilder(API api, String tenantDomain, List<ClientCertificateDTO> clientCertificateDTOS, List<SoapToRestMediationDto> soapToRestInMediationDtos, List<SoapToRestMediationDto> soapToRestMediationDtos) throws APIManagementException {
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    APITemplateBuilderImpl vtb = new APITemplateBuilderImpl(api, soapToRestInMediationDtos, soapToRestMediationDtos);
    Map<String, String> latencyStatsProperties = new HashMap<String, String>();
    latencyStatsProperties.put(APIConstants.API_UUID, api.getUUID());
    if (!APIUtil.isStreamingApi(api)) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIMgtLatencyStatsHandler", latencyStatsProperties);
    }
    Map<String, String> corsProperties = new HashMap<String, String>();
    corsProperties.put(APIConstants.CORSHeaders.IMPLEMENTATION_TYPE_HANDLER_VALUE, api.getImplementation());
    // Get authorization header from the API object or from the tenant registry
    String authorizationHeader;
    if (!StringUtils.isBlank(api.getAuthorizationHeader())) {
        authorizationHeader = api.getAuthorizationHeader();
    } else {
        // Retrieves the auth configuration from tenant registry or api-manager.xml if not available
        // in tenant registry
        authorizationHeader = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.AUTHORIZATION_HEADER);
    }
    if (!StringUtils.isBlank(authorizationHeader)) {
        corsProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    if (!(APIConstants.APITransportType.WS.toString().equals(api.getType()))) {
        if (api.getCorsConfiguration() != null && api.getCorsConfiguration().isCorsConfigurationEnabled()) {
            CORSConfiguration corsConfiguration = api.getCorsConfiguration();
            if (corsConfiguration.getAccessControlAllowHeaders() != null) {
                StringBuilder allowHeaders = new StringBuilder();
                for (String header : corsConfiguration.getAccessControlAllowHeaders()) {
                    allowHeaders.append(header).append(',');
                }
                if (allowHeaders.length() != 0) {
                    allowHeaders.deleteCharAt(allowHeaders.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_HEADERS_HANDLER_VALUE, allowHeaders.toString());
                }
            }
            if (corsConfiguration.getAccessControlAllowOrigins() != null) {
                StringBuilder allowOrigins = new StringBuilder();
                for (String origin : corsConfiguration.getAccessControlAllowOrigins()) {
                    allowOrigins.append(origin).append(',');
                }
                if (allowOrigins.length() != 0) {
                    allowOrigins.deleteCharAt(allowOrigins.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_ORIGIN_HANDLER_VALUE, allowOrigins.toString());
                }
            }
            if (corsConfiguration.getAccessControlAllowMethods() != null) {
                StringBuilder allowedMethods = new StringBuilder();
                for (String methods : corsConfiguration.getAccessControlAllowMethods()) {
                    allowedMethods.append(methods).append(',');
                }
                if (allowedMethods.length() != 0) {
                    allowedMethods.deleteCharAt(allowedMethods.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_METHODS_HANDLER_VALUE, allowedMethods.toString());
                }
            }
            if (corsConfiguration.isAccessControlAllowCredentials()) {
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_CREDENTIALS_HANDLER_VALUE, String.valueOf(corsConfiguration.isAccessControlAllowCredentials()));
            }
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
        } else if (APIUtil.isCORSEnabled()) {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIStatusHandler", Collections.emptyMap());
    }
    Map<String, String> clientCertificateObject = null;
    CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
    if (clientCertificateDTOS != null) {
        clientCertificateObject = new HashMap<>();
        for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
            clientCertificateObject.put(certificateMgtUtils.getUniqueIdentifierOfCertificate(clientCertificateDTO.getCertificate()), clientCertificateDTO.getTierName());
        }
    }
    Map<String, String> authProperties = new HashMap<>();
    if (!StringUtils.isBlank(authorizationHeader)) {
        authProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    String apiSecurity = api.getApiSecurity();
    String apiLevelPolicy = api.getApiLevelPolicy();
    authProperties.put(APIConstants.API_SECURITY, apiSecurity);
    authProperties.put(APIConstants.API_LEVEL_POLICY, apiLevelPolicy);
    if (clientCertificateObject != null) {
        authProperties.put(APIConstants.CERTIFICATE_INFORMATION, clientCertificateObject.toString());
    }
    // Get RemoveHeaderFromOutMessage from tenant registry or api-manager.xml
    String removeHeaderFromOutMessage = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE);
    if (!StringUtils.isBlank(removeHeaderFromOutMessage)) {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, removeHeaderFromOutMessage);
    } else {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE_DEFAULT);
    }
    authProperties.put(APIConstants.API_UUID, api.getUUID());
    authProperties.put("keyManagers", String.join(",", api.getKeyManagers()));
    if (APIConstants.GRAPHQL_API.equals(api.getType())) {
        Map<String, String> apiUUIDProperty = new HashMap<String, String>();
        apiUUIDProperty.put(APIConstants.API_UUID, api.getUUID());
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.graphQL.GraphQLAPIHandler", apiUUIDProperty);
    }
    if (APIConstants.APITransportType.WEBSUB.toString().equals(api.getType())) {
        authProperties.put(APIConstants.WebHookProperties.EVENT_RECEIVING_RESOURCE_PATH, APIConstants.WebHookProperties.DEFAULT_SUBSCRIPTION_RESOURCE_PATH);
        authProperties.put(APIConstants.WebHookProperties.TOPIC_QUERY_PARAM_NAME, APIConstants.WebHookProperties.DEFAULT_TOPIC_QUERY_PARAM_NAME);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.webhook.WebhookApiHandler", authProperties);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.webhook." + "WebhooksExtensionHandler", Collections.emptyMap());
    } else if (APIConstants.APITransportType.SSE.toString().equals(api.getType())) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.SseApiHandler", authProperties);
    } else if (!(APIConstants.APITransportType.WS.toString().equals(api.getType()))) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler", authProperties);
    }
    if (APIConstants.GRAPHQL_API.equals(api.getType())) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.graphQL.GraphQLQueryAnalysisHandler", Collections.emptyMap());
    }
    if (!APIUtil.isStreamingApi(api)) {
        Map<String, String> properties = new HashMap<String, String>();
        if (api.getProductionMaxTps() != null) {
            properties.put("productionMaxCount", api.getProductionMaxTps());
        }
        if (api.getSandboxMaxTps() != null) {
            properties.put("sandboxMaxCount", api.getSandboxMaxTps());
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler", properties);
        properties = new HashMap<String, String>();
        properties.put("configKey", APIConstants.GA_CONF_KEY);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtGoogleAnalyticsTrackingHandler", properties);
        String extensionHandlerPosition = getExtensionHandlerPosition(tenantDomain);
        if ("top".equalsIgnoreCase(extensionHandlerPosition)) {
            vtb.addHandlerPriority("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap(), 2);
        } else {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap());
        }
    }
    return vtb;
}
Also used : CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) HashMap(java.util.HashMap) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) CertificateMgtUtils(org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils) APITemplateBuilderImpl(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl)

Aggregations

CertificateMgtUtils (org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils)4 ClientCertificateDTO (org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)3 HashMap (java.util.HashMap)2 Test (org.junit.Test)2 CORSConfiguration (org.wso2.carbon.apimgt.api.model.CORSConfiguration)2 APITemplateBuilderImpl (org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl)2 Field (java.lang.reflect.Field)1 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)1 CertificateInformationDTO (org.wso2.carbon.apimgt.api.dto.CertificateInformationDTO)1 API (org.wso2.carbon.apimgt.api.model.API)1 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)1 ResponseCode (org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode)1 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)1 CertificateInfoDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CertificateInfoDTO)1