Search in sources :

Example 11 with APIKeyValidator

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

the class APIKeyValidatorTestCase method testGetResourceAuthenticationScheme.

@Test
public void testGetResourceAuthenticationScheme() {
    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("https");
    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("https");
    APIKeyValidator apiKeyValidator = createAPIKeyValidator(true, getDefaultURITemplates("/menu", "GET"), getDefaultVerbInfoDTO());
    // test for ResourceNotFoundException path
    try {
        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);
        String result = apiKeyValidator.getResourceAuthenticationScheme(synCtx);
        Assert.assertEquals("noMatchedAuthScheme", result);
    } catch (APISecurityException e) {
        e.printStackTrace();
    }
    APIKeyValidator apiKeyValidator1 = createAPIKeyValidator(false, getDefaultURITemplates("/menu", "GET"), getDefaultVerbInfoDTO());
    Resource resource = Mockito.mock(Resource.class);
    API api = new API("abc", "/");
    Mockito.when(synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/menu");
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    api.addResource(resource);
    Mockito.when(synapseConfiguration.getAPI("abc")).thenReturn((api));
    String result1 = null;
    try {
        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);
        Mockito.when(APIUtil.getAPIInfoDTOCacheKey("", "1.0")).thenReturn("abc");
        result1 = apiKeyValidator1.getResourceAuthenticationScheme(synCtx);
    } catch (APISecurityException e) {
        e.printStackTrace();
    }
    Assert.assertEquals(StringUtils.capitalize(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.toLowerCase()), result1);
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) Resource(org.apache.synapse.api.Resource) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) CacheProvider(org.wso2.carbon.apimgt.impl.caching.CacheProvider) 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 12 with APIKeyValidator

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

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

the class APIKeyValidatorTestCase method testCheckForInValidToken.

// Test case for Invalid,expired,revoked tokens when first time invocation
// Expectation : invalid token need to put into invalid token cache
@Test
public void testCheckForInValidToken() throws APISecurityException {
    try {
        String tenantDomain = "carbon.super";
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername("admin");
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
        apiKeyValidationInfoDTO.setAuthorized(false);
        apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
        AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
        Cache tokenCache = Mockito.mock(Cache.class);
        Cache keyCache = Mockito.mock(Cache.class);
        Cache resourceCache = Mockito.mock(Cache.class);
        Cache invalidTokenCache = Mockito.mock(Cache.class);
        APIKeyDataStore apiKeyDataStore = Mockito.mock(APIKeyDataStore.class);
        APIKeyValidator apiKeyValidator = getAPIKeyValidator(axisConfiguration, invalidTokenCache, tokenCache, keyCache, resourceCache, apiKeyDataStore, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Mockito.when(tokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(invalidTokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(apiKeyDataStore.getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>())).thenReturn(apiKeyValidationInfoDTO);
        apiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, matchingResource, httpVerb, defaultVersionInvoked, new ArrayList<>());
        Mockito.verify(tokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).get(Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).put(Mockito.any(APIKeyValidationInfoDTO.class), Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(1)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(apiKeyDataStore, Mockito.times(1)).getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>());
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) WSAPIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.WSAPIKeyDataStore) APIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 14 with APIKeyValidator

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

the class APIManagerConfiguration method readChildElements.

private void readChildElements(OMElement serverConfig, Stack<String> nameStack) throws APIManagementException {
    for (Iterator childElements = serverConfig.getChildElements(); childElements.hasNext(); ) {
        OMElement element = (OMElement) childElements.next();
        String localName = element.getLocalName();
        nameStack.push(localName);
        if ("APIKeyValidator".equals(localName)) {
            OMElement keyManagerServiceUrl = element.getFirstChildWithName(new QName(APIConstants.AUTHSERVER_URL));
            if (keyManagerServiceUrl != null) {
                String serviceUrl = keyManagerServiceUrl.getText();
                addKeyManagerConfigsAsSystemProperties(APIUtil.replaceSystemProperty(serviceUrl));
            }
        } else if (TOKEN_REVOCATION_NOTIFIERS.equals(localName)) {
            tokenRevocationClassName = element.getAttributeValue(new QName("class"));
        } else if (REALTIME_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
            }
            realtimeNotifierProperties = properties;
        } else if (PERSISTENT_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                if (propertyElem.getAttributeValue(new QName("name")).equalsIgnoreCase("password")) {
                    if (secretResolver.isInitialized() && secretResolver.isTokenProtected(TOKEN_REVOCATION_NOTIFIERS_PASSWORD)) {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), secretResolver.resolve(TOKEN_REVOCATION_NOTIFIERS_PASSWORD));
                    } else {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                    }
                } else {
                    properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                }
            }
            persistentNotifierProperties = properties;
        } else if ("Analytics".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> analyticsProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                analyticsProps.put(name, value);
            }
            OMElement authTokenElement = element.getFirstChildWithName(new QName("AuthToken"));
            String resolvedAuthToken = MiscellaneousUtil.resolve(authTokenElement, secretResolver);
            analyticsProps.put("auth.api.token", resolvedAuthToken);
            analyticsProperties = analyticsProps;
        } else if ("PersistenceConfigs".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> persistenceProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                persistenceProps.put(name, value);
            }
            persistenceProperties = persistenceProps;
        } else if (APIConstants.REDIS_CONFIG.equals(localName)) {
            OMElement redisHost = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_HOST));
            OMElement redisPort = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PORT));
            OMElement redisUser = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_USER));
            OMElement redisPassword = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PASSWORD));
            OMElement redisDatabaseId = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_DATABASE_ID));
            OMElement redisConnectionTimeout = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_CONNECTION_TIMEOUT));
            OMElement redisIsSslEnabled = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_IS_SSL_ENABLED));
            OMElement propertiesElement = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PROPERTIES));
            redisConfig.setRedisEnabled(true);
            redisConfig.setHost(redisHost.getText());
            redisConfig.setPort(Integer.parseInt(redisPort.getText()));
            if (redisUser != null && redisPassword != null && redisDatabaseId != null && redisConnectionTimeout != null && redisIsSslEnabled != null) {
                redisConfig.setUser(redisUser.getText());
                redisConfig.setPassword(MiscellaneousUtil.resolve(redisPassword, secretResolver).toCharArray());
                redisConfig.setDatabaseId(Integer.parseInt(redisDatabaseId.getText()));
                redisConfig.setConnectionTimeout(Integer.parseInt(redisConnectionTimeout.getText()));
                redisConfig.setSslEnabled(Boolean.parseBoolean(redisIsSslEnabled.getText()));
            }
            if (propertiesElement != null) {
                Iterator<OMElement> properties = propertiesElement.getChildElements();
                if (properties != null) {
                    while (properties.hasNext()) {
                        OMElement propertyNode = properties.next();
                        if (APIConstants.CONFIG_REDIS_MAX_TOTAL.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxTotal(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MAX_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_BORROW.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnBorrow(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_RETURN.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnReturn(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_WHILE_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestWhileIdle(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_BLOCK_WHEN_EXHAUSTED.equals(propertyNode.getLocalName())) {
                            redisConfig.setBlockWhenExhausted(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_EVICTABLE_IDLE_TIME_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinEvictableIdleTimeMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TIME_BETWEEN_EVICTION_RUNS_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_NUM_TESTS_PER_EVICTION_RUNS.equals(propertyNode.getLocalName())) {
                            redisConfig.setNumTestsPerEvictionRun(Integer.parseInt(propertyNode.getText()));
                        }
                    }
                }
            }
        } else if (elementHasText(element)) {
            String key = getKey(nameStack);
            String value = MiscellaneousUtil.resolve(element, secretResolver);
            addToConfiguration(key, APIUtil.replaceSystemProperty(value));
        } else if ("Environments".equals(localName)) {
            Iterator environmentIterator = element.getChildrenWithLocalName("Environment");
            apiGatewayEnvironments = new LinkedHashMap<String, Environment>();
            while (environmentIterator.hasNext()) {
                OMElement environmentElem = (OMElement) environmentIterator.next();
                setEnvironmentConfig(environmentElem);
            }
        } else if (APIConstants.EXTERNAL_API_STORES.equals(localName)) {
            // Initialize 'externalAPIStores' config elements
            Iterator apistoreIterator = element.getChildrenWithLocalName("ExternalAPIStore");
            externalAPIStores = new HashSet<APIStore>();
            while (apistoreIterator.hasNext()) {
                APIStore store = new APIStore();
                OMElement storeElem = (OMElement) apistoreIterator.next();
                String type = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_TYPE));
                // Set Store type [eg:wso2]
                store.setType(type);
                String className = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_CLASS_NAME));
                try {
                    store.setPublisher((APIPublisher) APIUtil.getClassInstance(className));
                } catch (InstantiationException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be instantiated";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (IllegalAccessException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be access";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (ClassNotFoundException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be found";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                }
                String name = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_ID));
                if (name == null) {
                    log.error("The ExternalAPIStore name attribute is not defined in api-manager.xml.");
                }
                // Set store name
                store.setName(name);
                OMElement configDisplayName = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_DISPLAY_NAME));
                String displayName = (configDisplayName != null) ? APIUtil.replaceSystemProperty(configDisplayName.getText()) : name;
                // Set store display name
                store.setDisplayName(displayName);
                store.setEndpoint(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_ENDPOINT)).getText()));
                store.setPublished(false);
                if (APIConstants.WSO2_API_STORE_TYPE.equals(type)) {
                    OMElement password = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_PASSWORD));
                    if (password != null) {
                        String value = MiscellaneousUtil.resolve(password, secretResolver);
                        store.setPassword(APIUtil.replaceSystemProperty(value));
                        store.setUsername(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_USERNAME)).getText()));
                    } else {
                        log.error("The user-credentials of API Publisher is not defined in the <ExternalAPIStore> " + "config of api-manager.xml.");
                    }
                }
                externalAPIStores.add(store);
            }
        } else if (APIConstants.LOGIN_CONFIGS.equals(localName)) {
            Iterator loginConfigIterator = element.getChildrenWithLocalName(APIConstants.LOGIN_CONFIGS);
            while (loginConfigIterator.hasNext()) {
                OMElement loginOMElement = (OMElement) loginConfigIterator.next();
                parseLoginConfig(loginOMElement);
            }
        } else if (APIConstants.AdvancedThrottleConstants.THROTTLING_CONFIGURATIONS.equals(localName)) {
            setThrottleProperties(serverConfig);
        } else if (APIConstants.WorkflowConfigConstants.WORKFLOW.equals(localName)) {
            setWorkflowProperties(serverConfig);
        } else if (APIConstants.ApplicationAttributes.APPLICATION_ATTRIBUTES.equals(localName)) {
            Iterator iterator = element.getChildrenWithLocalName(APIConstants.ApplicationAttributes.ATTRIBUTE);
            while (iterator.hasNext()) {
                OMElement omElement = (OMElement) iterator.next();
                Iterator attributes = omElement.getChildElements();
                JSONObject jsonObject = new JSONObject();
                boolean isHidden = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.HIDDEN)));
                boolean isRequired = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.REQUIRED)));
                jsonObject.put(APIConstants.ApplicationAttributes.HIDDEN, isHidden);
                while (attributes.hasNext()) {
                    OMElement attribute = (OMElement) attributes.next();
                    if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.NAME)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.ATTRIBUTE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DESCRIPTION)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DESCRIPTION, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TOOLTIP)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TOOLTIP, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TYPE)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TYPE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DEFAULT) && isRequired) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DEFAULT, attribute.getText());
                    }
                }
                if (isHidden && isRequired && !jsonObject.containsKey(APIConstants.ApplicationAttributes.DEFAULT)) {
                    log.error("A default value needs to be given for required, hidden application attributes.");
                }
                jsonObject.put(APIConstants.ApplicationAttributes.REQUIRED, isRequired);
                applicationAttributes.add(jsonObject);
            }
        } else if (APIConstants.Monetization.MONETIZATION_CONFIG.equals(localName)) {
            OMElement additionalAttributes = element.getFirstChildWithName(new QName(APIConstants.Monetization.ADDITIONAL_ATTRIBUTES));
            if (additionalAttributes != null) {
                setMonetizationAdditionalAttributes(additionalAttributes);
            }
        } else if (APIConstants.JWT_CONFIGS.equals(localName)) {
            setJWTConfiguration(element);
        } else if (APIConstants.TOKEN_ISSUERS.equals(localName)) {
            setJWTTokenIssuers(element);
        } else if (APIConstants.API_RECOMMENDATION.equals(localName)) {
            setRecommendationConfigurations(element);
        } else if (APIConstants.GlobalCacheInvalidation.GLOBAL_CACHE_INVALIDATION.equals(localName)) {
            setGlobalCacheInvalidationConfiguration(element);
        } else if (APIConstants.KeyManager.EVENT_HUB_CONFIGURATIONS.equals(localName)) {
            setEventHubConfiguration(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_PUBLISHER_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncPublisherConfig(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_GATEWAY_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncGatewayConfig(element);
        } else if (APIConstants.SkipListConstants.SKIP_LIST_CONFIG.equals(localName)) {
            setSkipListConfigurations(element);
        } else if (APIConstants.ExtensionListenerConstants.EXTENSION_LISTENERS.equals(localName)) {
            setExtensionListenerConfigurations(element);
        } else if (APIConstants.JWT_AUDIENCES.equals(localName)) {
            setRestApiJWTAuthAudiences(element);
        }
        readChildElements(element, nameStack);
        nameStack.pop();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) Properties(java.util.Properties) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) Iterator(java.util.Iterator) Environment(org.wso2.carbon.apimgt.api.model.Environment) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) APIPublisher(org.wso2.carbon.apimgt.api.model.APIPublisher) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 15 with APIKeyValidator

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

the class JWTValidatorTest method testJWTValidator.

@Test
public void testJWTValidator() throws ParseException, APISecurityException, APIManagementException, IOException {
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super");
    SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w");
    ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto();
    JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class);
    APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class);
    Cache gatewayTokenCache = Mockito.mock(Cache.class);
    Cache invalidTokenCache = Mockito.mock(Cache.class);
    Cache gatewayKeyCache = Mockito.mock(Cache.class);
    Cache gatewayJWTTokenCache = Mockito.mock(Cache.class);
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    jwtValidationInfo.setValid(true);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis());
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L);
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet());
    Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo);
    JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus");
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)).thenReturn("true");
    jwtValidator.setApiManagerConfiguration(apiManagerConfiguration);
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("api1");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())).thenReturn(true);
    Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO);
    AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    Mockito.verify(apiKeyValidator).validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.when(gatewayTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super");
    Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo);
    authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo);
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID());
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) HashMap(java.util.HashMap) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) SignedJWT(com.nimbusds.jwt.SignedJWT) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) ExtendedJWTConfigurationDto(org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Cache (javax.cache.Cache)25 Test (org.junit.Test)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)25 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)20 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)17 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)17 MessageContext (org.apache.synapse.MessageContext)16 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)15 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)12 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)11 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)10 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)10 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)10 SignedJWT (com.nimbusds.jwt.SignedJWT)9 HashMap (java.util.HashMap)9 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)9 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)9 WSAPIKeyDataStore (org.wso2.carbon.apimgt.gateway.handlers.security.keys.WSAPIKeyDataStore)8 APIManagerConfigurationService (org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)8 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)8