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();
}
}
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;
}
};
}
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;
}
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;
}
}
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;
}
Aggregations