Search in sources :

Example 6 with ResourceNotFoundException

use of org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException in project carbon-apimgt by wso2.

the class APIKeyValidatorTestCase method testFindMatchingVerb.

/*
     *  This method will test for findMatchingVerb()
     * */
@Test
public void testFindMatchingVerb() {
    MessageContext synCtx = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION_STRATEGY)).thenReturn(null);
    Mockito.when(synCtx.getProperty(APIConstants.API_RESOURCE_CACHE_KEY)).thenReturn("abc");
    Mockito.when(synCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH)).thenReturn("abc");
    Mockito.when(synCtx.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("");
    Mockito.when(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(((Axis2MessageContext) synCtx).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    SynapseConfiguration synapseConfiguration = Mockito.mock(SynapseConfiguration.class);
    Mockito.when(synapseConfiguration.getAPI("abc")).thenReturn(new API("abc", "/"));
    Mockito.when(synCtx.getConfiguration()).thenReturn(synapseConfiguration);
    Mockito.when(synCtx.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    VerbInfoDTO verbInfoDTO = getDefaultVerbInfoDTO();
    APIKeyValidator apiKeyValidator = createAPIKeyValidator(true, getDefaultURITemplates("/menu", "GET"), verbInfoDTO);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.GATEWAY_RESOURCE_CACHE_ENABLED)).thenReturn("true");
    try {
        List<VerbInfoDTO> verbList = apiKeyValidator.findMatchingVerb(synCtx);
        int length = verbList.toArray().length;
        // Test for ResourceNotFoundexception
        PowerMockito.mockStatic(Cache.class);
        Cache cache = Mockito.mock(Cache.class);
        PowerMockito.mockStatic(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        PowerMockito.mockStatic(APIManagerConfigurationService.class);
        PowerMockito.mockStatic(CacheProvider.class);
        org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        final APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        PowerMockito.when(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        PowerMockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        CacheProvider cacheProvider = Mockito.mock(CacheProvider.class);
        PowerMockito.when(cacheProvider.getDefaultCacheTimeout()).thenReturn((long) 900);
        Mockito.when(CacheProvider.getResourceCache()).thenReturn(cache);
        assertNotNull(verbList.get(0));
    // todo    Mockito.when(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION_STRATEGY)).thenReturn("url");
    } catch (ResourceNotFoundException e) {
        assert true;
    } catch (APISecurityException e) {
        fail("APISecurityException is thrown " + e);
    }
    APIKeyValidator apiKeyValidator1 = createAPIKeyValidator(false, getDefaultURITemplates("/menu", "GET"), verbInfoDTO);
    Resource resource = Mockito.mock(Resource.class);
    API api = new API("abc", "/");
    Mockito.when(synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/menu");
    api.addResource(resource);
    Mockito.when(synapseConfiguration.getAPI("abc")).thenReturn((api));
    try {
        List<VerbInfoDTO> verbInfoList = new ArrayList<>();
        verbInfoList.add(verbInfoDTO);
        // Test for matching verb is found path
        PowerMockito.mockStatic(Cache.class);
        Cache cache = Mockito.mock(Cache.class);
        PowerMockito.mockStatic(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        PowerMockito.mockStatic(APIManagerConfigurationService.class);
        PowerMockito.mockStatic(CacheProvider.class);
        org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
        final APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        PowerMockito.when(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        PowerMockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        CacheProvider cacheProvider = Mockito.mock(CacheProvider.class);
        PowerMockito.when(cacheProvider.getDefaultCacheTimeout()).thenReturn((long) 900);
        Mockito.when(CacheProvider.getResourceCache()).thenReturn(cache);
        assertEquals("", verbInfoList, apiKeyValidator1.findMatchingVerb(synCtx));
    } catch (ResourceNotFoundException e) {
        fail("ResourceNotFoundException exception is thrown " + e);
    } catch (APISecurityException e) {
        fail("APISecurityException is thrown " + e);
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) Resource(org.apache.synapse.api.Resource) ArrayList(java.util.ArrayList) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) CacheProvider(org.wso2.carbon.apimgt.impl.caching.CacheProvider) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) API(org.apache.synapse.api.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 7 with ResourceNotFoundException

use of org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException 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 8 with ResourceNotFoundException

use of org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException in project carbon-apimgt by wso2.

the class RestApiUtilTest method testRootCauseMessageMatchesNegative.

@Test
public void testRootCauseMessageMatchesNegative() throws Exception {
    String rootCauseMessage = "Entered start index seems to be greater than the limit count. Please verify your " + "parameters";
    ResourceNotFoundException resourceNotFoundException = new ResourceNotFoundException("Resource Not Found Exception");
    Throwable testThrowable = Mockito.mock(Throwable.class);
    PowerMockito.spy(RestApiUtil.class);
    PowerMockito.doReturn(testThrowable).when(RestApiUtil.class, "getPossibleErrorCause", resourceNotFoundException);
    when(testThrowable.getMessage()).thenReturn(rootCauseMessage);
    Assert.assertFalse(RestApiUtil.rootCauseMessageMatches(resourceNotFoundException, "Caused by exceeded limit count"));
}
Also used : ResourceNotFoundException(org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 9 with ResourceNotFoundException

use of org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException in project carbon-apimgt by wso2.

the class RestApiUtilTest method testRootCauseMessageMatches.

@Test
public void testRootCauseMessageMatches() throws Exception {
    String rootCauseMessage = "Entered start index seems to be greater than the limit count. Please verify your " + "parameters";
    ResourceNotFoundException resourceNotFoundException = new ResourceNotFoundException("Resource Not Found Exception");
    Throwable testThrowable = Mockito.mock(Throwable.class);
    PowerMockito.spy(RestApiUtil.class);
    PowerMockito.doReturn(testThrowable).when(RestApiUtil.class, "getPossibleErrorCause", resourceNotFoundException);
    when(testThrowable.getMessage()).thenReturn(rootCauseMessage);
    Assert.assertTrue(RestApiUtil.rootCauseMessageMatches(resourceNotFoundException, "index seems to be greater than the limit count"));
}
Also used : ResourceNotFoundException(org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 10 with ResourceNotFoundException

use of org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException in project carbon-apimgt by wso2.

the class RestApiUtilTest method testIsDueToResourceNotFoundWithResourceNotFoundException.

@Test
public void testIsDueToResourceNotFoundWithResourceNotFoundException() throws Exception {
    ResourceNotFoundException testResourceNotFoundException = new ResourceNotFoundException("New Sample exception");
    Throwable testThrowable = new Throwable();
    PowerMockito.spy(RestApiUtil.class);
    PowerMockito.doReturn(testResourceNotFoundException).when(RestApiUtil.class, "getPossibleErrorCause", testThrowable);
    Assert.assertTrue("Invalid exception has been passed.", RestApiUtil.isDueToResourceNotFound(testThrowable));
}
Also used : ResourceNotFoundException(org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 API (org.apache.synapse.api.API)6 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)6 MessageContext (org.apache.synapse.MessageContext)5 Resource (org.apache.synapse.api.Resource)5 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)5 Cache (javax.cache.Cache)4 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)4 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)4 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)4 APIManagerConfigurationService (org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)4 CacheProvider (org.wso2.carbon.apimgt.impl.caching.CacheProvider)4 ResourceNotFoundException (org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException)4 StringWriter (java.io.StringWriter)3 ArrayList (java.util.ArrayList)3 Template (org.apache.velocity.Template)3 VelocityContext (org.apache.velocity.VelocityContext)3 VelocityEngine (org.apache.velocity.app.VelocityEngine)3 ParseErrorException (org.apache.velocity.exception.ParseErrorException)3