Search in sources :

Example 61 with APISecurityException

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

the class APIKeyValidatorTestCase method testCheckForValidTokenWhileTokenInCache.

// Token is valid in cache
// Expectation : token get from token cache is not null then get from key cache check token is expired then send
// Token not accessed or insert into invalid token cache
@Test
public void testCheckForValidTokenWhileTokenInCache() 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(true);
        PowerMockito.when(APIUtil.isAccessTokenExpired(apiKeyValidationInfoDTO)).thenReturn(false);
        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("carbon.super");
        Mockito.when(keyCache.get(Mockito.anyString())).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(0)).get(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(1)).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(0)).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(0)).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 62 with APISecurityException

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

the class APIKeyValidatorTestCase method createAPIKeyValidator.

/*
     * This method will create an instance of APIKeyValidator
     * */
private APIKeyValidator createAPIKeyValidator(final boolean isWithEmptyCache, final ArrayList<URITemplate> urlTemplates, final VerbInfoDTO verbInfoDTO) {
    AxisConfiguration axisConfig = Mockito.mock(AxisConfiguration.class);
    List<VerbInfoDTO> verbInfoDTOList = new ArrayList<>();
    verbInfoDTOList.add(verbInfoDTO);
    return new APIKeyValidator() {

        @Override
        protected APIManagerConfiguration getApiManagerConfiguration() {
            APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);
            Mockito.when(configuration.getFirstProperty(APIConstants.TOKEN_CACHE_EXPIRY)).thenReturn("900");
            Mockito.when(configuration.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED)).thenReturn("true");
            Mockito.when(configuration.getFirstProperty(APIConstants.GATEWAY_RESOURCE_CACHE_ENABLED)).thenReturn("true");
            return configuration;
        }

        @Override
        protected Cache getCache(String cacheManagerName, String cacheName, long modifiedExp, long accessExp) {
            return Mockito.mock(Cache.class);
        }

        @Override
        protected ArrayList<URITemplate> getAllURITemplates(MessageContext messageContext, String context, String apiVersion) throws APISecurityException {
            return urlTemplates;
        }

        @Override
        protected APIKeyValidationInfoDTO doGetKeyValidationInfo(String context, String apiVersion, String apiKey, String authenticationScheme, String matchingResource, String httpVerb, String tenantDomain, List<String> keyManagers) throws APISecurityException {
            APIKeyValidationInfoDTO apiKeyValidationInfoDTO = Mockito.mock(APIKeyValidationInfoDTO.class);
            Mockito.when(apiKeyValidationInfoDTO.getApiName()).thenReturn(apiKey);
            return apiKeyValidationInfoDTO;
        }
    };
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) List(java.util.List) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 63 with APISecurityException

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

the class APIAuthenticationHandler method handleRequest.

@MethodStats
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EXS_EXCEPTION_SOFTENING_RETURN_FALSE", justification = "Error is sent through payload")
public boolean handleRequest(MessageContext messageContext) {
    TracingSpan keySpan = null;
    if (Util.tracingEnabled()) {
        TracingSpan responseLatencySpan = (TracingSpan) messageContext.getProperty(APIMgtGatewayConstants.RESOURCE_SPAN);
        TracingTracer tracer = Util.getGlobalTracer();
        keySpan = Util.startSpan(APIMgtGatewayConstants.KEY_VALIDATION, responseLatencySpan, tracer);
        messageContext.setProperty(APIMgtGatewayConstants.KEY_VALIDATION, keySpan);
        org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
        axis2MC.setProperty(APIMgtGatewayConstants.KEY_VALIDATION, keySpan);
    }
    Timer.Context context = startMetricTimer();
    long startTime = System.nanoTime();
    long endTime;
    long difference;
    if (Utils.isGraphQLSubscriptionRequest(messageContext)) {
        if (log.isDebugEnabled()) {
            log.debug("Skipping GraphQL subscription handshake request.");
        }
        return true;
    }
    try {
        if (isAnalyticsEnabled()) {
            long currentTime = System.currentTimeMillis();
            messageContext.setProperty("api.ut.requestTime", Long.toString(currentTime));
        }
        messageContext.setProperty(APIMgtGatewayConstants.API_TYPE, apiType);
        if (ExtensionListenerUtil.preProcessRequest(messageContext, type)) {
            if (!isAuthenticatorsInitialized) {
                initializeAuthenticators();
            }
            if (!isOauthParamsInitialized) {
                initOAuthParams();
            }
            String authenticationScheme = getAPIKeyValidator().getResourceAuthenticationScheme(messageContext);
            if (APIConstants.AUTH_NO_AUTHENTICATION.equals(authenticationScheme)) {
                if (log.isDebugEnabled()) {
                    log.debug("Found Authentication Scheme: ".concat(authenticationScheme));
                }
                handleNoAuthentication(messageContext);
                return true;
            }
            try {
                if (isAuthenticate(messageContext)) {
                    setAPIParametersToMessageContext(messageContext);
                    return ExtensionListenerUtil.postProcessRequest(messageContext, type);
                }
            } catch (APIManagementException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Authentication of message context failed", e);
                }
            }
        }
    } catch (APISecurityException e) {
        if (Util.tracingEnabled() && keySpan != null) {
            Util.setTag(keySpan, APIMgtGatewayConstants.ERROR, APIMgtGatewayConstants.KEY_SPAN_ERROR);
        }
        if (log.isDebugEnabled()) {
            // We do the calculations only if the debug logs are enabled. Otherwise this would be an overhead
            // to all the gateway calls that is happening.
            endTime = System.nanoTime();
            difference = (endTime - startTime) / 1000000;
            String messageDetails = logMessageDetails(messageContext);
            log.debug("Call to Key Manager : " + messageDetails + ", elapsedTimeInMilliseconds=" + difference / 1000000);
        }
        String errorMessage = APISecurityConstants.getAuthenticationFailureMessage(e.getErrorCode());
        if (APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE.equals(errorMessage)) {
            log.error("API authentication failure due to " + APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE, e);
        } else {
            // We do not need to log known authentication failures as errors since these are not product errors.
            log.warn("API authentication failure due to " + errorMessage);
            if (log.isDebugEnabled()) {
                log.debug("API authentication failed with error " + e.getErrorCode(), e);
            }
        }
        handleAuthFailure(messageContext, e);
    } finally {
        if (Util.tracingEnabled()) {
            Util.finishSpan(keySpan);
        }
        messageContext.setProperty(APIMgtGatewayConstants.SECURITY_LATENCY, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
        stopMetricTimer(context);
    }
    return false;
}
Also used : Timer(org.wso2.carbon.metrics.manager.Timer) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TracingTracer(org.wso2.carbon.apimgt.tracing.TracingTracer) TracingSpan(org.wso2.carbon.apimgt.tracing.TracingSpan) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 64 with APISecurityException

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

the class APIKeyValidator method getResourceAuthenticationScheme.

@MethodStats
public String getResourceAuthenticationScheme(MessageContext synCtx) throws APISecurityException {
    String authType = "";
    List<VerbInfoDTO> verbInfoList;
    try {
        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) {
        log.error("Could not find matching resource for request", e);
        return APIConstants.NO_MATCHING_AUTH_SCHEME;
    }
    if (!authType.isEmpty()) {
        return authType;
    } else {
        // No matching resource found. return the highest level of security
        return APIConstants.NO_MATCHING_AUTH_SCHEME;
    }
}
Also used : VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 65 with APISecurityException

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

the class APIKeyValidator method getAPIProductURITemplates.

@MethodStats
protected ArrayList<URITemplate> getAPIProductURITemplates(MessageContext messageContext, String context, String apiVersion) throws APISecurityException {
    if (uriTemplates == null) {
        synchronized (this) {
            if (uriTemplates == null) {
                String swagger = (String) messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_STRING);
                if (swagger != null) {
                    APIDefinition oasParser;
                    try {
                        oasParser = OASParserUtil.getOASParser(swagger);
                        uriTemplates = new ArrayList<>();
                        uriTemplates.addAll(oasParser.getURITemplates(swagger));
                        return uriTemplates;
                    } catch (APIManagementException e) {
                        log.error("Error while parsing swagger content to get URI Templates", e);
                    }
                }
                uriTemplates = dataStore.getAPIProductURITemplates(context, apiVersion);
            }
        }
    }
    return uriTemplates;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Aggregations

APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)34 Test (org.junit.Test)28 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)28 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)28 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)26 Cache (javax.cache.Cache)22 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)16 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)15 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)15 MessageContext (org.apache.synapse.MessageContext)14 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)14 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)12 SignedJWT (com.nimbusds.jwt.SignedJWT)11 HashMap (java.util.HashMap)11 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)11 ArrayList (java.util.ArrayList)10 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)10 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)10 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)10 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)10