Java Code Examples for org.apache.synapse.MessageContext#getProperty()

The following examples show how to use org.apache.synapse.MessageContext#getProperty() . 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: 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 2
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
    public void testMsgThrottleOutWhenBlockingConditionsAreSatisfied() {
        ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

        ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);

        MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
        ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
                .MessageContext.TRANSPORT_HEADERS);
        throttleDataHolder.addIpBlockingCondition("carbon.super", 1, "{\"fixedIp\":\"127.0.0.1\",\"invert\":false}",
                APIConstants.BLOCKING_CONDITIONS_IP);
        AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
                (API_AUTH_CONTEXT);
//        Mockito.when(throttleDataHolder.isRequestBlocked(apiContext, authenticationContext
//                .getSubscriber() + ":" + authenticationContext.getApplicationName(), authenticationContext
//                .getUsername(), "carbon.super" + ":" + "127.0.0.1")).thenReturn(true);
        Assert.assertFalse(throttleHandler.handleRequest(messageContext));
        throttleDataHolder.removeIpBlockingCondition("carbon.super", 1);
        Assert.assertTrue(throttleHandler.handleRequest(messageContext));
    }
 
Example 3
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgThrottleOutWhenApplicationLevelIsThrottled() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    matchingConditions.add(conditionGroupDTO);
    String applicationLevelThrottleKey = authenticationContext.getApplicationId() + ":" + authenticationContext
            .getUsername();
    //Set application level throttled out
    throttleDataHolder.addThrottleData(applicationLevelThrottleKey, System.currentTimeMillis() + 10000);

    //Should discontinue message flow, when application level is throttled
    Assert.assertFalse(throttleHandler.handleRequest(messageContext));
}
 
Example 4
Source File: APIManagerCacheExtensionHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public boolean mediate(MessageContext messageContext, String direction) {
    // In order to avoid a remote registry call occurring on each invocation, we
    // directly get the extension sequences from the local registry.
    Map localRegistry = messageContext.getConfiguration().getLocalRegistry();

    Object sequence = localRegistry.get(EXT_SEQUENCE_PREFIX + direction);
    if (sequence instanceof Mediator) {
        if (!((Mediator) sequence).mediate(messageContext)) {
            return false;
        }
    }

    String apiName = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API);
    sequence = localRegistry.get(apiName + "--" + direction);
    if (sequence instanceof Mediator) {
        return ((Mediator) sequence).mediate(messageContext);
    }
    return true;
}
 
Example 5
Source File: CsvValidatorMediator.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Throw Synapse Exception for any exception in class mediator
 * so that the fault handler will be invoked
 *
 * @param ERROR_CODE
 * @param ERROR_MESSAGE
 * @param ERROR_DETAIL
 * @param context
 */
public static void handle(String ERROR_CODE, String ERROR_MESSAGE, String ERROR_DETAIL, MessageContext context) {

    int array[] = {20, 20, 40};
    int total = 0;
    try {
        for (int i = 5; i >= 0; i--) {
            total += array[i];
        }
    } catch (Exception e) {
        context.setProperty(ERROR_CODE, "AB005");
        context.setProperty(ERROR_MESSAGE, "Error Message from class CsvValidatorMediator");
        context.setProperty(ERROR_DETAIL, "Error Details from class");

        String messageContextErrorCode = (String) context.getProperty(ERROR_CODE);
        String messageContextErrorMessage = (String) context.getProperty(ERROR_MESSAGE);
        String messageContextErrorDetail = (String) context.getProperty(ERROR_DETAIL);
        String separator = "?";

        String concatenatedMessage = (messageContextErrorCode + separator + messageContextErrorMessage + separator + messageContextErrorDetail);
        throw new SynapseException(concatenatedMessage);
    }
}
 
Example 6
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgDoContinueWhenAllThrottlingLevelsAreNotThrolled() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ServiceReferenceHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisher());
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    //Should continue the message flow if API level, application level, resource level, subscription level,
    //subscription spike level and hard throttling limit levels are not throttled
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
 
Example 7
Source File: DigestAuthMediator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to hash the entityBody for qop = auth-int (for calculating hash2)
 *
 * @param messageContext The message context where the entity body is stored
 * @return The hash of the entity body
 */
public String findEntityBodyHash(MessageContext messageContext) {

    String entityBody = (String) messageContext.getProperty(DigestAuthConstants.MESSAGE_BODY);

    //if the entity-body is null,take it as an empty string
    if (entityBody == null) {
        entityBody = "";
    }

    return DigestUtils.md5Hex(entityBody);
}
 
Example 8
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testMsgThrottleOutWhenHardThrottlingFailedWithThrottleException() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
            accessInformation);
    throttleHandler.setProductionMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setKeyType("SANDBOX");
    authenticationContext.setSpikeArrestLimit(0);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    matchingConditions.add(conditionGroupDTO);


    //Throw ThrottleException while retrieving access information
    Mockito.doThrow(ThrottleException.class).when(accessInformation).isAccessAllowed();
    //Should discontinue message flow, when an exception is thrown during hard limit throttling information
    //process time
    Assert.assertFalse(throttleHandler.handleRequest(messageContext));
}
 
Example 9
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
    public void testMsgThrottleOutWhenSandBoxHardThrottlingLimitsThrottled() {
        ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

        ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
                accessInformation);
        throttleHandler.setSandboxMaxCount("100");
        SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
        throttleHandler.init(synapseEnvironment);
        MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
        messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
        ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
                .MessageContext.TRANSPORT_HEADERS);
        AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
                (API_AUTH_CONTEXT);
        authenticationContext.setApiTier(throttlingTier);
        authenticationContext.setStopOnQuotaReach(false);
        authenticationContext.setKeyType("SANDBOX");
        authenticationContext.setSpikeArrestLimit(0);
        messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

        verbInfo.setConditionGroups(conditionGroupDTOs);
        ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
        matchingConditions.add(conditionGroupDTO);
        String subscriptionLevelThrottleKey = authenticationContext.getApplicationId() + ":" + apiContext + ":"
                + apiVersion;
        String applicationLevelThrottleKey = authenticationContext.getApplicationId() + ":" + authenticationContext
                .getUsername();
        String combinedResourceLevelThrottleKey = resourceLevelThrottleKey + conditionGroupDTO.getConditionGroupId();
//        Mockito.when(throttleDataHolder.isThrottled(combinedResourceLevelThrottleKey)).thenReturn(false);
//        Mockito.when(throttleDataHolder.isThrottled(subscriptionLevelThrottleKey)).thenReturn(false);
//        Mockito.when(throttleDataHolder.isThrottled(applicationLevelThrottleKey)).thenReturn(false);
//        Mockito.when(throttleDataHolder.isKeyTemplatesPresent()).thenReturn(false);
//        Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);

        //Should discontinue message flow if SANDBOX hard throttling limits are exceeded
        Assert.assertFalse(throttleHandler.handleRequest(messageContext));
    }
 
Example 10
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckForStaledThrottleData() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ServiceReferenceHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisher());
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
            accessInformation);
    throttleHandler.setProductionMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setSpikeArrestLimit(0);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);
    matchingConditions.add(conditionGroupDTO);
    throttleDataHolder.addKeyTemplate("testKeyTemplate", "testKeyTemplateValue");
    throttleDataHolder.addThrottleData("testKeyTemplate", System.currentTimeMillis() - 10000);
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
 
Example 11
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private void decrementInFlightRequestCount(MessageContext messageContext) {
    try {
        String clusterId = (String) messageContext.getProperty(LoadBalancerConstants.CLUSTER_ID);
        if (StringUtils.isBlank(clusterId)) {
            throw new RuntimeException("Cluster id not found in message context");
        }
        FutureTask<Object> task = new FutureTask<Object>(new InFlightRequestDecrementCallable(clusterId));
        LoadBalancerStatisticsExecutor.getInstance().getService().submit(task);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Could not decrement in-flight request count", e);
        }
    }
}
 
Example 12
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static String getRequestPath(MessageContext synCtx, String fullRequestPath, String apiContext, String
        apiVersion) {
    String requestPath;
    String versionStrategy = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION_STRATEGY);

    if(VersionStrategyFactory.TYPE_URL.equals(versionStrategy)){
        // most used strategy. server:port/context/version/resource
        requestPath = fullRequestPath.substring((apiContext + apiVersion).length() + 1, fullRequestPath.length());
     }else{
        // default version. assume there is no version is used
        requestPath = fullRequestPath.substring(apiContext.length(), fullRequestPath.length());
    }
    return requestPath;
}
 
Example 13
Source File: ProxyLogHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public void handleLogAppenderSetter (MessageContext synCtx) {
    String proxyName = (String) synCtx.getProperty(SynapseConstants.PROXY_SERVICE);

    ProxyService proxyService;
    if (proxyName != null && (proxyService = synCtx.getConfiguration().getProxyService(proxyName)) != null ) {
        proxyService.setLogSetterValue();
    }
}
 
Example 14
Source File: InternalAPIDispatcher.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private APIResource findResource(MessageContext synCtx, InternalAPI internalApi) {

        org.apache.axis2.context.MessageContext axis2Ctx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
        String method = (String) axis2Ctx.getProperty(Constants.Configuration.HTTP_METHOD);

        String path = (String) synCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
        String subPath = path.substring(internalApi.getContext().length());
        if ("".equals(subPath)) {
            subPath = "/";
        }

        for (APIResource resource : internalApi.getResources()) {
            if (!resource.getMethods().contains(method)) {
                continue;
            }
            DispatcherHelper helper = resource.getDispatcherHelper();
            URITemplateHelper templateHelper = (URITemplateHelper) helper;
            Map<String, String> variables = new HashMap<>();
            if (templateHelper.getUriTemplate().matches(subPath, variables)) {
                for (Map.Entry<String, String> entry : variables.entrySet()) {
                    synCtx.setProperty(RESTConstants.REST_URI_VARIABLE_PREFIX + entry.getKey(), entry.getValue());
                }
                RESTUtils.populateQueryParamsToMessageContext(synCtx);
                return resource;
            }
        }
        return null;
    }
 
Example 15
Source File: RegularExpressionProtector.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This mediate method gets the message context and validate against the special characters.
 *
 * @param messageContext contains the message properties of the relevant API request which was
 *                       enabled the regexValidator message mediation in flow.
 * @return A boolean value.True if successful and false if not.
 */
public boolean mediate(MessageContext messageContext) {
    if (logger.isDebugEnabled()) {
        logger.debug("RegularExpressionProtector mediator is activated...");
    }
    if (!isTenantAllowed(messageContext)) {
        return true;
    }
    Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.ENABLED_CHECK_BODY);

    if (messageProperty != null) {
        enabledCheckBody = Boolean.valueOf(messageProperty.toString());
    }
    if (isContentAware() && isPayloadSizeExceeded(messageContext)) {
        return true;
    }

    messageProperty = messageContext.getProperty(APIMgtGatewayConstants.REGEX_PATTERN);
    if (messageProperty != null) {
        if (pattern == null) {
            pattern = Pattern.compile(messageProperty.toString(), Pattern.CASE_INSENSITIVE);
        }
    } else {
        GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE,
                "Threat detection key words are missing");
        return true;
    }

    messageProperty = messageContext.getProperty(APIMgtGatewayConstants.ENABLED_CHECK_PATHPARAM);
    if (messageProperty != null) {
        enabledCheckPathParam = Boolean.valueOf(messageProperty.toString());
    }
    messageProperty = messageContext.getProperty(APIMgtGatewayConstants.ENABLED_CHECK_HEADERS);
    if (messageProperty != null) {
        enabledCheckHeaders = Boolean.valueOf(messageProperty.toString());
    }
    messageProperty = messageContext.getProperty(APIMgtGatewayConstants.THREAT_TYPE);
    if (messageProperty != null) {
        threatType = String.valueOf(messageProperty);
    }
    if (isRequestBodyVulnerable(messageContext) || isRequestHeadersVulnerable(messageContext) ||
            isRequestPathVulnerable(messageContext)) {
        return true;
    }
    return true;
}
 
Example 16
Source File: APIMgtGoogleAnalyticsTrackingHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
    * Track a page view, updates all the cookies and campaign tracker, makes a
    * server side request to Google Analytics and writes the transparent gif
    * byte data to the response.
    *
    * @throws Exception
    */
   private void trackPageView(MessageContext msgCtx) throws Exception {
       @SuppressWarnings("rawtypes")
       Map headers = (Map) ((Axis2MessageContext) msgCtx).getAxis2MessageContext()
                                              .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

       String host = (String) headers.get(HttpHeaders.HOST);
       String domainName = host;
       if (host != null && host.indexOf(":") != -1) {
           domainName = host.substring(0, host.indexOf(":"));
       }
       if (isEmpty(domainName)) {
           domainName = "";
       }

       // Get client IP
       String xForwardedFor = (String) headers.get(APIMgtUsagePublisherConstants.X_FORWARDED_FOR_HEADER);
       String userIP;
       if(xForwardedFor == null || xForwardedFor.isEmpty()) {
           userIP = (String) ((Axis2MessageContext) msgCtx).getAxis2MessageContext()
                   .getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
       } else {
           userIP = xForwardedFor.split(",")[0];
       }
       String path = (String) msgCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
       String documentPath = path;
       if (isEmpty(documentPath)) {
           documentPath = "";
       }

       String account = config.googleAnalyticsTrackingID;

       String userAgent = (String) headers.get(HttpHeaders.USER_AGENT);
       if (isEmpty(userAgent)) {
           userAgent = "";
       }

       String visitorId = getVisitorId(account, userAgent, msgCtx);

       /* Set the visitorId in MessageContext */
       msgCtx.setProperty(COOKIE_NAME, visitorId);

       String httpMethod =
                           (String) ((Axis2MessageContext) msgCtx).getAxis2MessageContext()
                                                                  .getProperty(Constants.Configuration.HTTP_METHOD);

	GoogleAnalyticsData data = new GoogleAnalyticsData
               .DataBuilder(account, GOOGLE_ANALYTICS_TRACKER_VERSION , visitorId , GoogleAnalyticsConstants.HIT_TYPE_PAGEVIEW)
               .setDocumentPath(documentPath)
               .setDocumentHostName(domainName)
               .setDocumentTitle(httpMethod)
               .setSessionControl("end")
               .setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId())
               .setIPOverride(userIP)
               .build();

       String payload = GoogleAnalyticsDataPublisher.buildPayloadString(data);
       if (log.isDebugEnabled()) {
           log.debug("Publishing https GET from gateway to Google analytics" + " with ID: " + msgCtx.getMessageID()
                   + " started at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
       }
       GoogleAnalyticsDataPublisher.publishGET(payload, userAgent, false);
       if (log.isDebugEnabled()) {
           log.debug("Publishing https GET from gateway to Google analytics" + " with ID: " + msgCtx.getMessageID()
                   + " ended at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
       }
}
 
Example 17
Source File: APIKeyValidator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@MethodStats
public String getResourceAuthenticationScheme(MessageContext synCtx) throws APISecurityException {
    String authType = "";
    List<VerbInfoDTO> verbInfoList;
    TracingSpan span = null;
    try {
        if (Util.tracingEnabled()) {
            TracingSpan keySpan = (TracingSpan) synCtx.getProperty(APIMgtGatewayConstants.KEY_VALIDATION);
            TracingTracer tracer = Util.getGlobalTracer();
            span = Util.startSpan(APIMgtGatewayConstants.FIND_MATCHING_VERB, keySpan, tracer);
        }
        verbInfoList = findMatchingVerb(synCtx);
        if (verbInfoList != null && verbInfoList.toArray().length > 0) {
            for (VerbInfoDTO verb : verbInfoList) {
                authType = verb.getAuthType();
                if (authType == null || !StringUtils.capitalize(APIConstants.AUTH_TYPE_NONE.toLowerCase())
                        .equals(authType)) {
                    authType = StringUtils.capitalize(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN
                            .toLowerCase());
                    break;
                }
            }
            synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
        }
    } catch (ResourceNotFoundException e) {
        if (Util.tracingEnabled() && span != null) {
            Util.setTag(span, APIMgtGatewayConstants.ERROR,
                    APIMgtGatewayConstants.RESOURCE_AUTH_ERROR);
        }
        log.error("Could not find matching resource for request", e);
        return APIConstants.NO_MATCHING_AUTH_SCHEME;
    } finally {
        if (Util.tracingEnabled()) {
            Util.finishSpan(span);
        }
    }

    if (!authType.isEmpty()) {
        return authType;
    } else {
        //No matching resource found. return the highest level of security
        return APIConstants.NO_MATCHING_AUTH_SCHEME;
    }
}
 
Example 18
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public void send(MessageContext synCtx) {
    SessionInformation sessionInformation = null;
    org.apache.axis2.clustering.Member currentMember = null;
    if (isSessionAffinityBasedLB()) {
        // Check existing session information
        sessionInformation = (SessionInformation) synCtx.getProperty(
                SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);

        currentMember = (org.apache.axis2.clustering.Member) synCtx.getProperty(
                SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER);

        if (sessionInformation == null && currentMember == null) {
            sessionInformation = dispatcher.getSession(synCtx);
            if (sessionInformation != null) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Existing session found: %s for request: %s", sessionInformation.getId(),
                            synCtx.getMessageID()));
                }

                currentMember = sessionInformation.getMember();
                synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
                // This is for reliably recovery any session information if while response is getting ,
                // session information has been removed by cleaner.
                // This will not be a cost as session information is not a heavy data structure
                synCtx.setProperty(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
            }
        }

    }

    TenantAwareLoadBalanceFaultHandler faultHandler = new TenantAwareLoadBalanceFaultHandler();
    if (sessionInformation != null && currentMember != null) {
        // Update axis2 member ports
        updateAxis2MemberPorts(synCtx, currentMember);
        // Send request to the member with the existing session
        sessionInformation.updateExpiryTime();
        sendToApplicationMember(synCtx, currentMember, faultHandler, false);
    } else {
        // No existing session found
        // Find next member
        org.apache.axis2.clustering.Member axis2Member = findNextMember(synCtx);
        if (axis2Member != null) {
            // Send request to member
            sendToApplicationMember(synCtx, axis2Member, faultHandler, true);
        } else {
            throwSynapseException(synCtx, 404, "Active application instances not found");
        }
    }
}
 
Example 19
Source File: JWTValidator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticates the given request with a JWT token to see if an API consumer is allowed to access
 * a particular API or not.
 *
 * @param jwtToken The JWT token sent with the API request
 * @param synCtx   The message to be authenticated
 * @param openAPI  The OpenAPI object of the invoked API
 * @return an AuthenticationContext object which contains the authentication information
 * @throws APISecurityException in case of authentication failure
 */
@MethodStats
public AuthenticationContext authenticate(SignedJWT jwtToken, MessageContext synCtx, OpenAPI openAPI)
        throws APISecurityException {

    String tokenSignature = jwtToken.getSignature().toString();
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().
            getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);

    String jwtHeader = jwtToken.getHeader().toString();
    if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(tokenSignature)) {
        if (log.isDebugEnabled()) {
            log.debug("Token retrieved from the revoked jwt token map. Token: " + GatewayUtils.
                    getMaskedToken(jwtHeader));
        }
        log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(jwtHeader));
        throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
                "Invalid JWT token");
    }
    String cacheKey = GatewayUtils
            .getAccessTokenCacheKey(tokenSignature, apiContext, apiVersion, matchingResource, httpMethod);

    JWTValidationInfo jwtValidationInfo = getJwtValidationInfo(jwtToken, cacheKey);

    if (jwtValidationInfo != null) {
        if (jwtValidationInfo.isValid()) {
            // validate scopes
            validateScopes(synCtx, openAPI, jwtValidationInfo);
            // Validate subscriptions


            APIKeyValidationInfoDTO apiKeyValidationInfoDTO = null;
            
            log.debug("Begin subscription validation via Key Manager");
            apiKeyValidationInfoDTO = validateSubscriptionUsingKeyManager(synCtx, jwtValidationInfo);

            if (log.isDebugEnabled()) {
                log.debug("Subscription validation via Key Manager. Status: "
                        + apiKeyValidationInfoDTO.isAuthorized());
            }
            if (apiKeyValidationInfoDTO.isAuthorized()) {
                /*
                 * Set api.ut.apiPublisher of the subscribed api to the message context.
                 * This is necessary for the functionality of Publisher alerts.
                 * */
                synCtx.setProperty(APIMgtGatewayConstants.API_PUBLISHER, apiKeyValidationInfoDTO.getApiPublisher());
                log.debug("JWT authentication successful.");
            } else {
                log.debug(
                        "User is NOT authorized to access the Resource. API Subscription validation " + "failed.");
                throw new APISecurityException(apiKeyValidationInfoDTO.getValidationStatus(),
                        "User is NOT authorized to access the Resource. API Subscription validation " + "failed.");
            }
        
            log.debug("JWT authentication successful.");
            String endUserToken = null;
            try {
                if (jwtGenerationEnabled) {
                    JWTInfoDto jwtInfoDto =
                            GatewayUtils
                                    .generateJWTInfoDto(jwtValidationInfo, null, apiKeyValidationInfoDTO, synCtx);
                    endUserToken = generateAndRetrieveJWTToken(tokenSignature, jwtInfoDto);
                }
                return GatewayUtils
                        .generateAuthenticationContext(tokenSignature, jwtValidationInfo, null,
                                apiKeyValidationInfoDTO,
                                getApiLevelPolicy(), endUserToken, true);
            } catch (ParseException e) {
                throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                        APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
            }
        } else {
            throw new APISecurityException(jwtValidationInfo.getValidationCode(),
                    APISecurityConstants.getAuthenticationFailureMessage(jwtValidationInfo.getValidationCode()));
        }
    } else {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
    }
}
 
Example 20
Source File: HL7Processor.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@Override
public void sendBack(MessageContext messageContext) {
    MLLPContext mllpContext = (MLLPContext) messageContext.getProperty(MLLPConstants.MLLP_CONTEXT);
    sendBack(messageContext, mllpContext);
}