org.apache.synapse.MessageContext Java Examples

The following examples show how to use org.apache.synapse.MessageContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataServiceResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private void populateDataServiceList(MessageContext msgCtx) throws Exception {
    SynapseConfiguration configuration = msgCtx.getConfiguration();
    AxisConfiguration axisConfiguration = configuration.getAxisConfiguration();
    String[] dataServicesNames = DBUtils.getAvailableDS(axisConfiguration);

    // initiate list model
    DataServicesList dataServicesList = new DataServicesList(dataServicesNames.length);

    for (String dataServiceName : dataServicesNames) {
        DataService dataService = getDataServiceByName(msgCtx, dataServiceName);
        ServiceMetaData serviceMetaData = getServiceMetaData(dataService);
        // initiate summary model
        DataServiceSummary summary = null;
        if (serviceMetaData != null) {
            summary = new DataServiceSummary(serviceMetaData.getName(), serviceMetaData.getWsdlURLs());
        }
        dataServicesList.addServiceSummary(summary);
    }

    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) msgCtx)
            .getAxis2MessageContext();

    String stringPayload = new Gson().toJson(dataServicesList);
    Utils.setJsonPayLoad(axis2MessageContext, new JSONObject(stringPayload));
}
 
Example #2
Source File: GraphQLQueryAnalysisHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns the maximum query complexity value
 *
 * @param messageContext message context of the request
 * @return maximum query complexity value if exists, or -1 to denote no complexity limitation
 */
private int getMaxQueryComplexity(MessageContext messageContext) {
    Object maxQueryComplexity = messageContext.getProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY);
    if (maxQueryComplexity != null) {
        int maxComplexity = ((Integer) maxQueryComplexity).intValue();
        if (maxComplexity > 0) {
            return maxComplexity;
        } else {
            log.debug("Maximum query complexity value is 0");
            return -1;
        }
    } else {
        log.debug("Maximum query complexity not applicable");
        return -1;
    }
}
 
Example #3
Source File: RequestCountResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean invoke(MessageContext synCtx,
                      org.apache.axis2.context.MessageContext axis2MessageContext,
                      SynapseConfiguration synapseConfiguration) {

    String pathParam = Utils.getPathParameter(synCtx, "param");

    if ("count".equalsIgnoreCase(pathParam)) {
        String yearParameter = Utils.getQueryParameter(synCtx, "year");
        String monthParameter = Utils.getQueryParameter(synCtx, "month");

        return handleTransactionCountCommand(axis2MessageContext, yearParameter, monthParameter);

    } else if ("report".equalsIgnoreCase(pathParam)) {
        String start = Utils.getQueryParameter(synCtx, "start");
        String end = Utils.getQueryParameter(synCtx, "end");

        return handleTransactionReportCommand(axis2MessageContext, start, end);

    } else {
        JSONObject response = Utils.createJsonError("No such resource as management/transactions/" + pathParam,
                                                    axis2MessageContext, BAD_REQUEST);
        Utils.setJsonPayLoad(axis2MessageContext, response);
        return true;
    }
}
 
Example #4
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgContinueWhenRemoteIPIsNotSpecifiedInMsgCtx() throws XMLStreamException,
        ThrottleException {
    //Set concurrency count to be 100
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext()
            .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, new TreeMap<String, Object>());
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "IP", IP, 0, 60000, "true"),
            THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "IP", IP, 0, 60000, "true"),
            THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    //Throttling limits won't get applied, since the remote IP is not specified in message context,
    //Thus message will be continued by the gateway, even though the limits are exceeded 0/60000
    Assert.assertTrue(apiThrottleHandler.handleRequest(messageContext));
}
 
Example #5
Source File: LogoutResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean invoke(MessageContext messageContext, org.apache.axis2.context.MessageContext axis2MessageContext, SynapseConfiguration synapseConfiguration) {

    if (!JWTConfig.getInstance().getJwtConfigDto().isJwtHandlerEngaged()) {
        LOG.error("/Logout is accessible only when JWT based auth handler is engaged");
        handleServerError(axis2MessageContext, "Logout is accessible only when JWT based auth handler is engaged");
        return true;
    }

    String authHeader = (String) SecurityUtils.getHeaders(axis2MessageContext).get(HTTPConstants.HEADER_AUTHORIZATION);
    String token = authHeader.substring(AuthConstants.BEARER_AUTH_HEADER_TOKEN_TYPE.length() + 1).trim();
    //Revokes token when logging out.
    if (!JWTInMemoryTokenStore.getInstance().revokeToken(token)) {
        LOG.error("Log out failed");
        handleServerError(axis2MessageContext, "Log out failed due to incorrect credentials");
        return true;
    }
    return true;
}
 
Example #6
Source File: RegularExpressionProtector.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks whether the request path contains matching vulnerable keywords.
 *
 * @param messageContext contains the message properties of the relevant API request which was
 *                       enabled the regexValidator message mediation in flow.
 * @return true if request Headers contain matching vulnerable keywords
 */
private boolean isRequestHeadersVulnerable(MessageContext messageContext) {
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext)
            messageContext).getAxis2MessageContext();
    if (enabledCheckHeaders) {
        Map transportHeaders = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (pattern != null && transportHeaders != null && pattern.matcher(transportHeaders.toString()).find()) {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Threat detected in Transport headers [ %s ] by regex [ %s ]",
                        transportHeaders, pattern));
            }
            GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE,
                    threatType + " " + APIMgtGatewayConstants.HTTP_HEADER_THREAT_MSG);
            return true;
        }
    }
    return false;
}
 
Example #7
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplicabilityOfInvertedQueryParameterTypeCondition() {

    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditionGroupId("QueryParameterTypeConditionGroup");
    ConditionDTO nonMatchingCondition = new ConditionDTO();
    nonMatchingCondition.setConditionType("QueryParameterType");
    nonMatchingCondition.setConditionName("city");
    nonMatchingCondition.setConditionValue("colombo");
    nonMatchingCondition.isInverted(true);

    ConditionDTO[] conditionDTOS = {nonMatchingCondition};
    conditionGroupDTO.setConditions(conditionDTOS);
    ConditionGroupDTO[] conditionGroupDTOS = {conditionGroupDTO};

    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REST_URL_POSTFIX",
            "/temperature?city=colombo");
    List<ConditionGroupDTO> matchingConditionGroups = throttleConditionEvaluator.getApplicableConditions
            (messageContext, new AuthenticationContext(), conditionGroupDTOS);
    Assert.assertNull(matchingConditionGroups.get(0));
}
 
Example #8
Source File: LoggingResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private JSONObject getLoggerData(org.apache.axis2.context.MessageContext axis2MessageContext, String loggerName) {

        String logLevel;
        String componentName = "";
        jsonBody = new JSONObject();
        try {
            if (loggerName.equals(Constants.ROOT_LOGGER)) {
                logLevel = Utils.getProperty(logPropFile, loggerName + LOGGER_LEVEL_SUFFIX);
            } else {
                componentName = Utils.getProperty(logPropFile, LOGGER_PREFIX + loggerName + LOGGER_NAME_SUFFIX);
                logLevel = Utils.getProperty(logPropFile, LOGGER_PREFIX + loggerName + LOGGER_LEVEL_SUFFIX);
            }
        } catch (IOException exception) {
            jsonBody = createJsonError("Error while obtaining logger data ", exception, axis2MessageContext);
            return jsonBody;
        }
        jsonBody.put(Constants.LOGGER_NAME, loggerName);
        jsonBody.put(Constants.COMPONENT_NAME, componentName);
        jsonBody.put(Constants.LEVEL, logLevel);
        return jsonBody;
    }
 
Example #9
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private void prepareEndPointSequence(MessageContext synCtx, Endpoint endpoint) {

        Object o = synCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST);
        List<Endpoint> endpointList;
        if (o instanceof List) {
            endpointList = (List<Endpoint>) o;
            endpointList.add(this);

        } else {
            // this is the first endpoint in the hierarchy. so create the queue and
            // insert this as the first element.
            endpointList = new ArrayList<Endpoint>();
            endpointList.add(this);
            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST, endpointList);
        }

        // if the next endpoint is not a session affinity one, endpoint sequence ends
        // here. but we have to add the next endpoint to the list.
        if (!(endpoint instanceof TenantAwareLoadBalanceEndpoint)) {
            endpointList.add(endpoint);
            // Clearing out if there any any session information with current message
            if (dispatcher.isServerInitiatedSession()) {
                dispatcher.removeSessionID(synCtx);
            }
        }
    }
 
Example #10
Source File: InboundWebsocketSourceHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private void injectToSequence(org.apache.synapse.MessageContext synCtx, InboundEndpoint endpoint) {
    SequenceMediator injectingSequence = null;
    if (endpoint.getInjectingSeq() != null) {
        injectingSequence = (SequenceMediator) synCtx.getSequence(endpoint.getInjectingSeq());
    }
    if (injectingSequence == null) {
        injectingSequence = (SequenceMediator) synCtx.getMainSequence();
    }
    SequenceMediator faultSequence = getFaultSequence(synCtx, endpoint);
    MediatorFaultHandler mediatorFaultHandler = new MediatorFaultHandler(faultSequence);
    synCtx.pushFaultHandler(mediatorFaultHandler);
    if (log.isDebugEnabled()) {
        log.debug("injecting message to sequence : " + endpoint.getInjectingSeq());
    }
    synCtx.setProperty("inbound.endpoint.name", endpoint.getName());
    if (dispatchToCustomSequence) {
        String context = (subscriberPath.getPath()).substring(1);
        context = context.replace('/', '-');
        if (synCtx.getConfiguration().getDefinedSequences().containsKey(context))
            injectingSequence = (SequenceMediator) synCtx.getSequence(context);
    }
    synCtx.getEnvironment().injectMessage(synCtx, injectingSequence);
}
 
Example #11
Source File: DataProcessAndPublishingAgentTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void setDataReferenceWithHeaderConditionEnable() throws Exception {
    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnabled(true);
    throttleProperties.setEnableHeaderConditions(true);
    DataProcessAndPublishingAgent dataProcessAndPublishingAgent = new DataProcessAndPublishingAgentWrapper
            (throttleProperties);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext
            .class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--PizzaShackAPI");
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS))
            .thenReturn(new TreeMap<>());
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setContentAware(false);
    ArrayList<VerbInfoDTO> list = new ArrayList<VerbInfoDTO>();
    list.add(verbInfoDTO);
    Mockito.when(messageContext.getProperty(APIConstants.VERB_INFO_DTO)).thenReturn(list);
    dataProcessAndPublishingAgent.setDataReference(applicationLevelThrottleKey, applicationLevelTier,
            apiLevelThrottleKey, null, subscriptionLevelThrottleKey, subscriptionLevelTier,
            resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant,
            apiTenant, appId, messageContext, authenticationContext);
    dataProcessAndPublishingAgent.run();
}
 
Example #12
Source File: CORSRequestHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void handleResourceNotFound(MessageContext messageContext, List<Resource> allAPIResources) {

        Resource uriMatchingResource = null;

        for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
            uriMatchingResource = dispatcher.findResource(messageContext, allAPIResources);
            //If a resource with a matching URI was found.
            if (uriMatchingResource != null) {
                onResourceNotFoundError(messageContext, HttpStatus.SC_METHOD_NOT_ALLOWED,
                        APIMgtGatewayConstants.METHOD_NOT_FOUND_ERROR_MSG);
                return;
            }
        }

        //If a resource with a matching URI was not found.
        //Respond with a 404.
        onResourceNotFoundError(messageContext, HttpStatus.SC_NOT_FOUND,
                APIMgtGatewayConstants.RESOURCE_NOT_FOUND_ERROR_MSG);
    }
 
Example #13
Source File: SecurityHandlerAdapterTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a handler configuration similar to the following with no resources defined.
 * <p>
 * <handler name="SampleInternalApiHandlerWithNoResources"
 *          class="internal.http.api.SampleInternalApiHandlerWithNoResources"/>
 */
@Test
public void testHandledWithNoResource() {

    //set message context
    MessageContext messageContext = new TestMessageContext();
    EndpointReference endpointReference = new EndpointReference();
    endpointReference.setAddress("/sectest/resource1");
    messageContext.setTo(endpointReference);

    TestSecurityHandler internalAPIHandler = new TestSecurityHandler("/sectest");

    //test with no resources
    internalAPIHandler.setResources(new ArrayList<>());
    internalAPIHandler.invoke(messageContext);
    Assert.assertTrue("Handler should be engaged when no resources are explictely defined, but it was not engaged.",
                      internalAPIHandler.isHandleTriggered());
}
 
Example #14
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplicabilityOfMatchingJWTClaimsCondition() {

    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditionGroupId("JWTClaimsConditionGroup");
    ConditionDTO matchingCondition = new ConditionDTO();
    matchingCondition.setConditionType("JWTClaims");
    matchingCondition.setConditionName("http://wso2.org/claims/subscriber");
    matchingCondition.setConditionValue("admin");

    ConditionDTO[] conditionDTOS = {matchingCondition};
    conditionGroupDTO.setConditions(conditionDTOS);
    ConditionGroupDTO[] conditionGroupDTOS = {conditionGroupDTO};

    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setCallerToken(JWTToken);

    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    List<ConditionGroupDTO> matchingConditionGroups = throttleConditionEvaluator.getApplicableConditions
            (messageContext, authenticationContext, conditionGroupDTOS);
    Assert.assertEquals(matchingConditionGroups.get(0).getConditionGroupId(), "JWTClaimsConditionGroup");
}
 
Example #15
Source File: APIMgtFaultHandlerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMediate() throws Exception {
    APIMgtFaultHandler apiMgtFaultHandler = createAPIMgtFaultHandler(false, false);
    MessageContext messageContext = Mockito.mock(MessageContext.class);
    //Test for analytics disable path
    Assert.assertTrue(apiMgtFaultHandler.mediate(messageContext));

    APIMgtFaultHandler apiMgtFaultHandler1 = createAPIMgtFaultHandler(false, true);
    //Test for analytics enabled and  skipEventReceiverConnection disabled path
    Assert.assertTrue(apiMgtFaultHandler1.mediate(messageContext));

    //Test for analytics enabled and  skipEventReceiverConnection en
    // abled path
    APIMgtFaultHandler apiMgtFaultHandler2 = createAPIMgtFaultHandler(true, true);
    Assert.assertTrue(apiMgtFaultHandler2.mediate(messageContext));

    //Test for analytics enabled and  skipEventReceiverConnection disabled path
    APIMgtFaultHandler apiMgtFaultHandler3 = createAPIMgtFaultHandler(true, false);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.REQUEST_START_TIME)).thenReturn("564321");
    apiMgtFaultHandler3.isContentAware();
    // Test for test mediate is not failed even an exception is thrown
    Assert.assertTrue(apiMgtFaultHandler3.mediate(messageContext));

}
 
Example #16
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplicabilityOfNonMatchingJWTClaimsCondition() {

    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditionGroupId("JWTClaimsConditionGroup");
    ConditionDTO nonMatchingCondition = new ConditionDTO();
    nonMatchingCondition.setConditionType("JWTClaims");
    nonMatchingCondition.setConditionName("http://wso2.org/claims/subscriber");
    nonMatchingCondition.setConditionValue("testUser");

    ConditionDTO[] conditionDTOS = {nonMatchingCondition};
    conditionGroupDTO.setConditions(conditionDTOS);
    ConditionGroupDTO[] conditionGroupDTOS = {conditionGroupDTO};

    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setCallerToken(JWTToken);

    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    List<ConditionGroupDTO> matchingConditionGroups = throttleConditionEvaluator.getApplicableConditions
            (messageContext, authenticationContext, conditionGroupDTOS);
    Assert.assertNull(matchingConditionGroups.get(0));
}
 
Example #17
Source File: MetricHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Start the timers to observe request latency.
 *
 * @param synCtx           The Synapse Message Context
 * @param serviceName      The proxy/api/inbound endpoint name
 * @param serviceType      The service type (proxy/api/inbound endpoint)
 * @param apiInvocationUrl The api invocation url
 */
private void startTimers(MessageContext synCtx, String serviceName, String serviceType, String apiInvocationUrl) {
    switch (serviceType) {
        case SynapseConstants.PROXY_SERVICE_TYPE:
            synCtx.setProperty(MetricConstants.PROXY_LATENCY_TIMER,
                    metricReporterInstance.getTimer(MetricConstants.PROXY_LATENCY_SECONDS,
                            new String[]{serviceName, serviceType}));
            break;
        case MetricConstants.INBOUND_ENDPOINT:
            synCtx.setProperty(MetricConstants.INBOUND_ENDPOINT_LATENCY_TIMER,
                    metricReporterInstance.getTimer(MetricConstants.INBOUND_ENDPOINT_LATENCY_SECONDS,
                            new String[]{serviceName, serviceType}));
            break;
        case SynapseConstants.FAIL_SAFE_MODE_API:
            synCtx.setProperty(MetricConstants.API_LATENCY_TIMER,
                    metricReporterInstance.getTimer(MetricConstants.API_LATENCY_SECONDS,
                            new String[]{serviceName, serviceType, apiInvocationUrl}));
            break;
        default:
            log.error("No proper service type found");
            break;
    }
}
 
Example #18
Source File: LoggingResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private JSONObject updateLoggerData(org.apache.axis2.context.MessageContext axis2MessageContext, String loggerName,
                                    String loggerClass, String logLevel) {

    try {
        loadConfigs();
        String modifiedLogger = getLoggers().concat(", ").concat(loggerName);
        config.setProperty(LOGGERS_PROPERTY, modifiedLogger);
        config.setProperty(LOGGER_PREFIX + loggerName + LOGGER_NAME_SUFFIX, loggerClass);
        config.setProperty(LOGGER_PREFIX + loggerName + LOGGER_LEVEL_SUFFIX, logLevel);
        applyConfigs();
        jsonBody.put(Constants.MESSAGE, getSuccessMsg(loggerClass, loggerName, logLevel));
    } catch (ConfigurationException | IOException exception) {
        jsonBody = createJsonError("Exception while updating logger data ", exception, axis2MessageContext);
    }
    return jsonBody;
}
 
Example #19
Source File: MutualSSLCertificateHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleRequest(MessageContext messageContext) {

    org.apache.axis2.context.MessageContext axis2MsgContext =
            ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Map headers =
            (Map) axis2MsgContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    try {
        X509Certificate clientCertificate = Utils.getClientCertificate(axis2MsgContext);
        headers.remove(Utils.getClientCertificateHeader());
        if (clientCertificate != null) {
            byte[] encoded = Base64.encodeBase64(clientCertificate.getEncoded());
            String base64EncodedString =
                    APIConstants.BEGIN_CERTIFICATE_STRING
                            .concat(new String(encoded)).concat("\n")
                            .concat(APIConstants.END_CERTIFICATE_STRING);
            base64EncodedString = Base64.encodeBase64URLSafeString(base64EncodedString.getBytes());
            headers.put(Utils.getClientCertificateHeader(), base64EncodedString);
        }
    } catch (APIManagementException | CertificateEncodingException e) {
        log.error("Error while converting client certificate", e);
    }
    return true;
}
 
Example #20
Source File: OAuthMediator.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean mediate(MessageContext synCtx) {

    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }

    // checks if the message carries OAuth params
    boolean isOauth2 = validateRequest(synCtx);

    if (isOauth2) {
        return handleOAuth2(synCtx);
    } else {
        return handleOAuth1a(synCtx);
    }
}
 
Example #21
Source File: JWTValidator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Validate scopes bound to the resource of the API being invoked against the scopes specified
 * in the JWT token payload.
 *
 * @param synCtx  The message to be authenticated
 * @param openAPI The OpenAPI object of the invoked API
 * @param jwtValidationInfo Validated JWT Information
 * @throws APISecurityException in case of scope validation failure
 */
private void validateScopes(MessageContext synCtx, OpenAPI openAPI, JWTValidationInfo jwtValidationInfo)
        throws APISecurityException {

    if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        HashMap<String, String> operationScopeMappingList =
                (HashMap<String, String>) synCtx.getProperty(APIConstants.SCOPE_OPERATION_MAPPING);
        String[] operationList = ((String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE)).split(",");
        for (String operation : operationList) {
            String operationScope = operationScopeMappingList.get(operation);
            checkTokenWithTheScope(operation, operationScope, jwtValidationInfo);
        }
    } else {
        String resource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
        String resourceScope = OpenAPIUtils.getScopesOfResource(openAPI, synCtx);
        checkTokenWithTheScope(resource, resourceScope, jwtValidationInfo);
    }
}
 
Example #22
Source File: HL7Processor.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * We need to add several context properties that HL7 Axis2 transport sender depends on (also the
 * application/edi-hl7 formatter).
 *
 * @param synCtx
 */
private void addProperties(MessageContext synCtx, MLLPContext context) {
    org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) synCtx)
            .getAxis2MessageContext();

    axis2MsgCtx.setProperty(Axis2HL7Constants.HL7_MESSAGE_OBJECT, context.getHl7Message());

    if (params.getProperties().getProperty(MLLPConstants.PARAM_HL7_BUILD_RAW_MESSAGE) != null) {
        axis2MsgCtx.setProperty(Axis2HL7Constants.HL7_BUILD_RAW_MESSAGE, Boolean.valueOf(
                params.getProperties().getProperty(MLLPConstants.PARAM_HL7_BUILD_RAW_MESSAGE)));
    }

    if (params.getProperties().getProperty(MLLPConstants.PARAM_HL7_PASS_THROUGH_INVALID_MESSAGES) != null) {
        axis2MsgCtx.setProperty(Axis2HL7Constants.HL7_PASS_THROUGH_INVALID_MESSAGES, Boolean.valueOf(
                params.getProperties().getProperty(MLLPConstants.PARAM_HL7_PASS_THROUGH_INVALID_MESSAGES)));
    }

    if (parameters.get(MLLPConstants.HL7_CHARSET_DECODER) != null) {
        axis2MsgCtx.setProperty(Axis2HL7Constants.HL7_MESSAGE_CHARSET,
                                ((CharsetDecoder) parameters.get(MLLPConstants.HL7_CHARSET_DECODER)).charset()
                                        .displayName());
    }

    // Below is expensive, it is in HL7 Axis2 transport but we should not depend on this!
    //axis2MsgCtx.setProperty(Axis2HL7Constants.HL7_RAW_MESSAGE_PROPERTY_NAME, context.getCodec());

}
 
Example #23
Source File: CORSRequestHandlerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private CORSRequestHandler createCORSRequestHandler() {
    return new CORSRequestHandler() {

        @Override
        protected APIManagerConfigurationService getApiManagerConfigurationService() {
            return Mockito.mock(APIManagerConfigurationService.class);
        }

        @Override
        protected String getFullRequestPath(MessageContext messageContext) {
            return "/ishara/1.0/xx";
        }

        @Override
        protected Timer.Context startMetricTimer() {
            return null;
        }

        @Override
        protected void stopMetricTimer(Timer.Context context) {

        }

        @Override
        protected boolean isCorsEnabled() {
            return true;
        }

    };
}
 
Example #24
Source File: GraphQLQueryAnalysisHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method analyses the query
 *
 * @param messageContext message context of the request
 * @param payload        payload of the request
 * @return true, if the query is not blocked or false, if the query is blocked
 */
private boolean analyseQuery(MessageContext messageContext, String payload) {
    try {
        if (analyseQueryDepth(messageContext, payload) &&
                analyseQueryComplexity(messageContext, payload)) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        String errorMessage = "Policy definition parsing failed. ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return false;
}
 
Example #25
Source File: DataServiceCallMediator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private SOAPEnvelope createDefaultSOAPEnvelope(MessageContext inMsgCtx) {

        String soapNamespace = inMsgCtx.getEnvelope().getNamespace().getNamespaceURI();
        SOAPFactory soapFactory = null;
        if (soapNamespace.equals(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
            soapFactory = OMAbstractFactory.getSOAP11Factory();
        } else if (soapNamespace.equals(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
            soapFactory = OMAbstractFactory.getSOAP12Factory();
        } else {
            log.error("Unknown SOAP Envelope");
        }
        return soapFactory.getDefaultEnvelope();
    }
 
Example #26
Source File: APIManagerExtensionHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleRequestWithGlobalInSeqWithoutFurtherMediationAndCustomInSeq() {
	MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
	SynapseConfiguration synapseConfig = Mockito.mock(SynapseConfiguration.class);
	org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito
			.mock(org.apache.axis2.context.MessageContext.class);

	Map localRegistry = Mockito.mock(Map.class);

	Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
	Mockito.when(((Axis2MessageContext) messageContext).getConfiguration()).thenReturn(synapseConfig);
	Mockito.when(synapseConfig.getLocalRegistry()).thenReturn(localRegistry);

	Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn(API_NAME);
	

	SequenceMediator inSeq = Mockito.mock(SequenceMediator.class);
	SequenceMediator globalInSeq = Mockito.mock(SequenceMediator.class);
	Mockito.when(localRegistry.get(API_NAME + "--" + DIRECTION_IN)).thenReturn(inSeq);
	Mockito.when(localRegistry.get(EXT_SEQUENCE_PREFIX + DIRECTION_IN)).thenReturn(globalInSeq);
	Mockito.when(((Mediator) inSeq).mediate(messageContext)).thenReturn(true);
	
	//Global mediation returns a false to prevent any further mediation
	Mockito.when(((Mediator) globalInSeq).mediate(messageContext)).thenReturn(false);

	APIManagerExtensionHandler handler = createAPIManagerExtensionHandler();
	// both methods are executed during a full request path
	handler.handleRequest(messageContext);
	handler.handleResponse(messageContext);

	// check whether custom in sequnce is not executed
	Mockito.verify(inSeq, Mockito.never()).mediate(messageContext);
	// check whether global in sequnce is executed once 
	Mockito.verify(globalInSeq, Mockito.times(1)).mediate(messageContext);

}
 
Example #27
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetThrottledInConditionWithQueryConditionInvert() {

    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnableQueryParamConditions(true);
    ServiceReferenceHolder.getInstance().setThrottleProperties(throttleProperties);
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REST_URL_POSTFIX",
            "/temperature?abc=cde&bcd=xyz");
    Map<String, List<ConditionDto>> conditionMap = new HashMap<>();
    conditionMap.put("condition1", Arrays.asList(new ConditionDto[]{getQueryParamCondition(true)}));
    conditionMap.put("default", Arrays.asList(new ConditionDto[]{getQueryParamCondition(true)}));
    String condition = throttleConditionEvaluator.getThrottledInCondition(messageContext, null, conditionMap);
    Assert.assertEquals(condition, "default");
}
 
Example #28
Source File: MITenantInfoConfigurator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Override
public boolean applyTenantInfo(MessageContext messageContext) {
    if (logger.isDebugEnabled()) {
        logger.info("Applying Tenant Info...");
    }
    // Nothing to do here since Micro Integrator does not support multi tenancy
    return true;
}
 
Example #29
Source File: Utils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the string representation of a property set in the message context
 *
 * @param messageContext the message context to extract the property from
 * @param key            the key of the property
 * @return the string if a non empty value has been set. Returns null, if the property is not present or if the
 * value is empty.
 */
public static String getStringPropertyFromMessageContext(MessageContext messageContext, String key) {
    Object propertyObject = messageContext.getProperty(key);
    if (Objects.nonNull(propertyObject)) {
        String propertyString = propertyObject.toString();
        if (!StringUtils.isEmpty(propertyString)) {
            return propertyString;
        }
    }
    return null;
}
 
Example #30
Source File: ThrottleConditionEvaluatorTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetThrottledInConditionWithIPConditionWithDefaultWithInvertNegative() {

    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    Map map = new TreeMap();
    map.put("X-Forwarded-For", "127.0.0.1");
    ((Axis2MessageContext) messageContext).getAxis2MessageContext()
            .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, map);
    Map<String, List<ConditionDto>> conditionMap = new HashMap<>();
    conditionMap.put("condition1", Arrays.asList(new ConditionDto[]{getIPCondition(true)}));
    conditionMap.put("default", Arrays.asList(new ConditionDto[]{getIPCondition(true)}));
    String condition = throttleConditionEvaluator.getThrottledInCondition(messageContext, null, conditionMap);
    Assert.assertEquals(condition, "default");
}