Search in sources :

Example 1 with WebSocketApiException

use of org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException in project carbon-apimgt by wso2.

the class InboundWebSocketProcessor method handleHandshake.

/**
 * This method process websocket handshake and extract necessary API information from the channel context and
 * request. Finally, hand over the processing to relevant handshake processor for authentication etc.
 *
 * @param req                   Handshake request
 * @param ctx                   Channel pipeline context
 * @param inboundMessageContext InboundMessageContext
 * @return InboundProcessorResponseDTO with handshake processing response
 */
public InboundProcessorResponseDTO handleHandshake(FullHttpRequest req, ChannelHandlerContext ctx, InboundMessageContext inboundMessageContext) {
    InboundProcessorResponseDTO inboundProcessorResponseDTO;
    try {
        HandshakeProcessor handshakeProcessor = new HandshakeProcessor();
        setUris(req, inboundMessageContext);
        InboundWebsocketProcessorUtil.setTenantDomainToContext(inboundMessageContext);
        setMatchingResource(ctx, req, inboundMessageContext);
        String userAgent = req.headers().get(HttpHeaders.USER_AGENT);
        // '-' is used for empty values to avoid possible errors in DAS side.
        // Required headers are stored one by one as validateOAuthHeader()
        // removes some headers from the request
        userAgent = userAgent != null ? userAgent : "-";
        inboundMessageContext.getRequestHeaders().put(HttpHeaders.USER_AGENT, userAgent);
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(inboundMessageContext.getTenantDomain(), true);
        if (validateOAuthHeader(req, inboundMessageContext)) {
            setRequestHeaders(req, inboundMessageContext);
            inboundMessageContext.getRequestHeaders().put(HttpHeaders.AUTHORIZATION, req.headers().get(HttpHeaders.AUTHORIZATION));
            inboundProcessorResponseDTO = handshakeProcessor.processHandshake(inboundMessageContext);
        } else {
            String errorMessage = "No Authorization Header or access_token query parameter present";
            log.error(errorMessage + " in request for the websocket context " + inboundMessageContext.getApiContext());
            inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.API_AUTH_ERROR, errorMessage);
        }
        publishHandshakeAuthErrorEvent(ctx, inboundProcessorResponseDTO.getErrorMessage());
        return inboundProcessorResponseDTO;
    } catch (APISecurityException e) {
        log.error("Authentication Failure for the websocket context: " + inboundMessageContext.getApiContext() + e.getMessage());
        inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.API_AUTH_ERROR, e.getMessage());
        publishHandshakeAuthErrorEvent(ctx, e.getMessage());
    } catch (WebSocketApiException e) {
        log.error(e.getMessage());
        inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (ResourceNotFoundException e) {
        log.error(e.getMessage());
        inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.RESOURCE_NOT_FOUND_ERROR, e.getMessage());
        publishResourceNotFoundEvent(ctx);
    }
    return inboundProcessorResponseDTO;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) WebSocketApiException(org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException) ResourceNotFoundException(org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException) HandshakeProcessor(org.wso2.carbon.apimgt.gateway.inbound.websocket.handshake.HandshakeProcessor)

Example 2 with WebSocketApiException

use of org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException in project carbon-apimgt by wso2.

the class InboundWebSocketProcessor method setUris.

/**
 * Extract full request path from the request and update InboundMessageContext.
 *
 * @param req                   Request object
 * @param inboundMessageContext InboundMessageContext
 */
private void setUris(FullHttpRequest req, InboundMessageContext inboundMessageContext) throws WebSocketApiException {
    try {
        String fullRequestPath = req.uri();
        inboundMessageContext.setFullRequestPath(req.uri());
        URI uriTemp;
        uriTemp = new URI(fullRequestPath);
        String requestPath = new URI(uriTemp.getScheme(), uriTemp.getAuthority(), uriTemp.getPath(), null, uriTemp.getFragment()).toString();
        if (requestPath.endsWith(WebSocketApiConstants.URL_SEPARATOR)) {
            requestPath = requestPath.substring(0, requestPath.length() - 1);
        }
        inboundMessageContext.setRequestPath(requestPath);
        if (log.isDebugEnabled()) {
            log.debug("Websocket API fullRequestPath = " + inboundMessageContext.getRequestPath());
        }
    } catch (URISyntaxException e) {
        throw new WebSocketApiException("Error while parsing uri: " + e.getMessage());
    }
}
Also used : WebSocketApiException(org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 3 with WebSocketApiException

use of org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException in project carbon-apimgt by wso2.

the class InboundWebsocketProcessorUtil method publishGoogleAnalyticsData.

/**
 * Publish Google Analytics data.
 *
 * @param inboundMessageContext InboundMessageContext
 * @param remoteAddress         Remote IP address
 * @throws WebSocketApiException if an  error occurs
 */
public static void publishGoogleAnalyticsData(InboundMessageContext inboundMessageContext, String remoteAddress) throws WebSocketApiException {
    // publish Google Analytics data
    GoogleAnalyticsData.DataBuilder gaData;
    try {
        gaData = new GoogleAnalyticsData.DataBuilder(null, null, null, null).setDocumentPath(inboundMessageContext.getFullRequestPath()).setDocumentHostName(DataPublisherUtil.getHostAddress()).setSessionControl("end").setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId()).setIPOverride(remoteAddress);
        APIMgtGoogleAnalyticsUtils gaUtils = new APIMgtGoogleAnalyticsUtils();
        gaUtils.init(inboundMessageContext.getTenantDomain());
        gaUtils.publishGATrackingData(gaData, inboundMessageContext.getRequestHeaders().get(HttpHeaders.USER_AGENT), inboundMessageContext.getRequestHeaders().get(HttpHeaders.AUTHORIZATION));
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        throw new WebSocketApiException("Error while publishing google analytics data for API " + inboundMessageContext.getApiContext());
    }
}
Also used : WebSocketApiException(org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException) APIMgtGoogleAnalyticsUtils(org.wso2.carbon.apimgt.gateway.utils.APIMgtGoogleAnalyticsUtils) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GoogleAnalyticsData(org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 4 with WebSocketApiException

use of org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException in project carbon-apimgt by wso2.

the class InboundWebSocketProcessor method setMatchingResource.

/**
 * Get matching resource for invoking handshake request.
 *
 * @param ctx                   Channel context
 * @param req                   Handshake request
 * @param inboundMessageContext InboundMessageContext
 * @throws WebSocketApiException     If an error occurs
 * @throws ResourceNotFoundException If no matching API or resource found
 */
private void setMatchingResource(ChannelHandlerContext ctx, FullHttpRequest req, InboundMessageContext inboundMessageContext) throws WebSocketApiException, ResourceNotFoundException {
    String matchingResource;
    try {
        MessageContext synCtx = getMessageContext(inboundMessageContext);
        API api = InboundWebsocketProcessorUtil.getApi(synCtx, inboundMessageContext);
        if (api == null) {
            throw new ResourceNotFoundException("No matching API found to dispatch the request");
        }
        inboundMessageContext.setApi(api);
        reConstructFullUriWithVersion(req, synCtx, inboundMessageContext);
        inboundMessageContext.setApiContext(api.getContext());
        Resource selectedResource = null;
        Utils.setSubRequestPath(api, synCtx);
        Set<Resource> acceptableResources = new LinkedHashSet<>(Arrays.asList(api.getResources()));
        if (!acceptableResources.isEmpty()) {
            for (RESTDispatcher dispatcher : ApiUtils.getDispatchers()) {
                Resource resource = dispatcher.findResource(synCtx, acceptableResources);
                if (resource != null) {
                    selectedResource = resource;
                    if (APIUtil.isAnalyticsEnabled()) {
                        WebSocketUtils.setApiPropertyToChannel(ctx, APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS, WebSocketUtils.getEndpointUrl(resource, synCtx));
                    }
                    break;
                }
            }
        }
        setApiPropertiesToChannel(ctx, inboundMessageContext);
        if (selectedResource == null) {
            throw new ResourceNotFoundException("No matching resource found to dispatch the request");
        }
        if (APIConstants.GRAPHQL_API.equals(inboundMessageContext.getElectedAPI().getApiType())) {
            inboundMessageContext.setGraphQLSchemaDTO(DataHolder.getInstance().getGraphQLSchemaDTOForAPI(inboundMessageContext.getElectedAPI().getUuid()));
        }
        matchingResource = selectedResource.getDispatcherHelper().getString();
        if (log.isDebugEnabled()) {
            log.info("Selected resource for API dispatch : " + matchingResource);
        }
    } catch (AxisFault | URISyntaxException e) {
        throw new WebSocketApiException("Error while getting matching resource for Websocket API");
    }
    inboundMessageContext.setMatchingResource(matchingResource);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) AxisFault(org.apache.axis2.AxisFault) RESTDispatcher(org.apache.synapse.api.dispatch.RESTDispatcher) WebSocketApiException(org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException) Resource(org.apache.synapse.api.Resource) API(org.apache.synapse.api.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) URISyntaxException(java.net.URISyntaxException) ResourceNotFoundException(org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException)

Aggregations

WebSocketApiException (org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException)4 URISyntaxException (java.net.URISyntaxException)2 ResourceNotFoundException (org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 LinkedHashSet (java.util.LinkedHashSet)1 AxisFault (org.apache.axis2.AxisFault)1 MessageContext (org.apache.synapse.MessageContext)1 API (org.apache.synapse.api.API)1 Resource (org.apache.synapse.api.Resource)1 RESTDispatcher (org.apache.synapse.api.dispatch.RESTDispatcher)1 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)1 InboundMessageContext (org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext)1 HandshakeProcessor (org.wso2.carbon.apimgt.gateway.inbound.websocket.handshake.HandshakeProcessor)1 APIMgtGoogleAnalyticsUtils (org.wso2.carbon.apimgt.gateway.utils.APIMgtGoogleAnalyticsUtils)1 GoogleAnalyticsData (org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData)1