use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.
the class APIThrottleHandlerTest method testMsgThrottleOutWhenHardLevelQuotaExceededForProductionEndpoint.
@Test
public void testMsgThrottleOutWhenHardLevelQuotaExceededForProductionEndpoint() throws XMLStreamException, ThrottleException {
concurrentAccessController = new ConcurrentAccessController(100);
configurationContext.setProperty(throttleKey, concurrentAccessController);
AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty(API_AUTH_CONTEXT);
authenticationContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
messageContext.setProperty(APIConstants.VERB_INFO_DTO, new VerbInfoDTO());
((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000, "true"), THROTTLE_POLICY_KEY, true, 0, messageContext);
TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "ROLE", "Silver", 1, 60000, "true"), THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
messageContext.setProperty(RESPONSE, "false");
apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
apiThrottleHandler.setId(throttleID);
apiThrottleHandler.setProductionMaxCount(PRODUCTION_MAX_COUNT);
Mockito.when(throttleContext.getThrottleConfiguration()).thenReturn(throttleConfiguration);
Mockito.when(throttleConfiguration.getCallerConfiguration(Mockito.anyString())).thenReturn(callerConfiguration);
Mockito.when(callerConfiguration.getAccessState()).thenReturn(1);
Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.
the class GraphQLResponseProcessorTest method testHandleThrottleOut.
@Test
public void testHandleThrottleOut() {
InboundMessageContext inboundMessageContext = new InboundMessageContext();
int msgSize = 100;
String msgText = "{\"type\":\"data\",\"id\":\"1\",\"payload\":{\"data\":" + "{\"liftStatusChange\":{\"name\":\"Astra Express\"}}}}";
PowerMockito.mockStatic(InboundWebsocketProcessorUtil.class);
InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setHttpVerb("SUBSCRIPTION");
verbInfoDTO.setThrottling("Unlimited");
GraphQLOperationDTO graphQLOperationDTO = new GraphQLOperationDTO(verbInfoDTO, "liftStatusChange");
inboundMessageContext.addVerbInfoForGraphQLMsgId("1", graphQLOperationDTO);
PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(inboundMessageContext, "liftStatusChange", "1")).thenReturn(responseDTO);
GraphQLProcessorResponseDTO throttleResponseDTO = new GraphQLProcessorResponseDTO();
throttleResponseDTO.setError(true);
throttleResponseDTO.setErrorCode(WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR);
throttleResponseDTO.setErrorMessage(WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR_MESSAGE);
throttleResponseDTO.setId("1");
PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(msgSize, verbInfoDTO, inboundMessageContext, "1")).thenReturn(throttleResponseDTO);
GraphQLResponseProcessor responseProcessor = new GraphQLResponseProcessor();
InboundProcessorResponseDTO processorResponseDTO = responseProcessor.handleResponse(msgSize, msgText, inboundMessageContext);
Assert.assertTrue(processorResponseDTO.isError());
Assert.assertNotNull(processorResponseDTO.getErrorMessage());
Assert.assertFalse(processorResponseDTO.isCloseConnection());
Assert.assertEquals(processorResponseDTO.getErrorResponseString(), throttleResponseDTO.getErrorResponseString());
Assert.assertEquals(processorResponseDTO.getErrorMessage(), throttleResponseDTO.getErrorMessage());
Assert.assertEquals(processorResponseDTO.getErrorCode(), throttleResponseDTO.getErrorCode());
}
use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.
the class GraphQLResponseProcessorTest method testHandleInvalidScope.
@Test
public void testHandleInvalidScope() {
InboundMessageContext inboundMessageContext = new InboundMessageContext();
int msgSize = 100;
String msgText = "{\"type\":\"data\",\"id\":\"1\",\"payload\":{\"data\":" + "{\"liftStatusChange\":{\"name\":\"Astra Express\"}}}}";
PowerMockito.mockStatic(InboundWebsocketProcessorUtil.class);
InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setHttpVerb("SUBSCRIPTION");
verbInfoDTO.setThrottling("Unlimited");
verbInfoDTO.setAuthType("Any");
GraphQLOperationDTO graphQLOperationDTO = new GraphQLOperationDTO(verbInfoDTO, "liftStatusChange");
inboundMessageContext.addVerbInfoForGraphQLMsgId("1", graphQLOperationDTO);
GraphQLProcessorResponseDTO graphQLProcessorResponseDTO = new GraphQLProcessorResponseDTO();
graphQLProcessorResponseDTO.setError(true);
graphQLProcessorResponseDTO.setErrorCode(WebSocketApiConstants.FrameErrorConstants.RESOURCE_FORBIDDEN_ERROR);
graphQLProcessorResponseDTO.setErrorMessage("User is NOT authorized to access the Resource");
graphQLProcessorResponseDTO.setCloseConnection(false);
graphQLProcessorResponseDTO.setId("1");
PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(inboundMessageContext, "liftStatusChange", "1")).thenReturn(graphQLProcessorResponseDTO);
PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(msgSize, verbInfoDTO, inboundMessageContext, "1")).thenReturn(responseDTO);
GraphQLResponseProcessor responseProcessor = new GraphQLResponseProcessor();
InboundProcessorResponseDTO processorResponseDTO = responseProcessor.handleResponse(msgSize, msgText, inboundMessageContext);
Assert.assertTrue(processorResponseDTO.isError());
Assert.assertNotNull(processorResponseDTO.getErrorMessage());
Assert.assertFalse(processorResponseDTO.isCloseConnection());
Assert.assertEquals(processorResponseDTO.getErrorResponseString(), graphQLProcessorResponseDTO.getErrorResponseString());
Assert.assertEquals(processorResponseDTO.getErrorMessage(), graphQLProcessorResponseDTO.getErrorMessage());
Assert.assertEquals(processorResponseDTO.getErrorCode(), graphQLProcessorResponseDTO.getErrorCode());
}
use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.
the class ApiKeyAuthenticator method authenticate.
@Override
public AuthenticationResponse authenticate(MessageContext synCtx) {
if (log.isDebugEnabled()) {
log.info("ApiKey Authentication initialized");
}
try {
// Extract apikey from the request while removing it from the msg context.
String apiKey = extractApiKey(synCtx);
JWTTokenPayloadInfo payloadInfo = null;
if (jwtConfigurationDto == null) {
jwtConfigurationDto = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration().getJwtConfigurationDto();
}
if (jwtGenerationEnabled == null) {
jwtGenerationEnabled = jwtConfigurationDto.isEnabled();
}
if (apiMgtGatewayJWTGenerator == null) {
apiMgtGatewayJWTGenerator = ServiceReferenceHolder.getInstance().getApiMgtGatewayJWTGenerator().get(jwtConfigurationDto.getGatewayJWTGeneratorImpl());
}
String[] splitToken = apiKey.split("\\.");
JWSHeader decodedHeader;
JWTClaimsSet payload = null;
SignedJWT signedJWT = null;
String tokenIdentifier, certAlias;
if (splitToken.length != 3) {
log.error("Api Key does not have the format {header}.{payload}.{signature} ");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
signedJWT = SignedJWT.parse(apiKey);
payload = signedJWT.getJWTClaimsSet();
decodedHeader = signedJWT.getHeader();
tokenIdentifier = payload.getJWTID();
// Check if the decoded header contains type as 'JWT'.
if (!JOSEObjectType.JWT.equals(decodedHeader.getType())) {
if (log.isDebugEnabled()) {
log.debug("Invalid Api Key token type. Api Key: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Api Key token type.");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
if (!GatewayUtils.isAPIKey(payload)) {
log.error("Invalid Api Key. Internal Key Sent");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
if (decodedHeader.getKeyID() == null) {
if (log.isDebugEnabled()) {
log.debug("Invalid Api Key. Could not find alias in header. Api Key: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Api Key. Could not find alias in header");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
} else {
certAlias = decodedHeader.getKeyID();
}
String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
OpenAPI openAPI = (OpenAPI) synCtx.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT);
if (openAPI == null && !APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
log.error("Swagger is missing in the gateway. " + "Therefore, Api Key authentication cannot be performed.");
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF_ERROR_MESSAGE);
}
String resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, matchingResource, httpMethod);
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setHttpVerb(httpMethod);
// Not doing resource level authentication
verbInfoDTO.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
verbInfoDTO.setRequestKey(resourceCacheKey);
verbInfoDTO.setThrottling(OpenAPIUtils.getResourceThrottlingTier(openAPI, synCtx));
List<VerbInfoDTO> verbInfoList = new ArrayList<>();
verbInfoList.add(verbInfoDTO);
synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
String cacheKey = GatewayUtils.getAccessTokenCacheKey(tokenIdentifier, apiContext, apiVersion, matchingResource, httpMethod);
String tenantDomain = GatewayUtils.getTenantDomain();
boolean isVerified = false;
// Validate from cache
if (isGatewayTokenCacheEnabled == null) {
isGatewayTokenCacheEnabled = GatewayUtils.isGatewayTokenCacheEnabled();
}
if (isGatewayTokenCacheEnabled) {
String cacheToken = (String) getGatewayApiKeyCache().get(tokenIdentifier);
if (cacheToken != null) {
if (log.isDebugEnabled()) {
log.debug("Api Key retrieved from the Api Key cache.");
}
if (getGatewayApiKeyDataCache().get(cacheKey) != null) {
// Token is found in the key cache
payloadInfo = (JWTTokenPayloadInfo) getGatewayApiKeyDataCache().get(cacheKey);
String accessToken = payloadInfo.getAccessToken();
if (!accessToken.equals(apiKey)) {
isVerified = false;
} else {
isVerified = true;
}
}
} else if (getInvalidGatewayApiKeyCache().get(tokenIdentifier) != null) {
if (log.isDebugEnabled()) {
log.debug("Api Key retrieved from the invalid Api Key cache. Api Key: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Api Key." + GatewayUtils.getMaskedToken(splitToken[0]));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
} else if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(tokenIdentifier)) {
if (log.isDebugEnabled()) {
log.debug("Token retrieved from the revoked jwt token map. Token: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid API Key. " + GatewayUtils.getMaskedToken(splitToken[0]));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid API Key");
}
} else {
if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(tokenIdentifier)) {
if (log.isDebugEnabled()) {
log.debug("Token retrieved from the revoked jwt token map. Token: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(splitToken[0]));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
}
}
// Not found in cache or caching disabled
if (!isVerified) {
if (log.isDebugEnabled()) {
log.debug("Api Key not found in the cache.");
}
try {
signedJWT = (SignedJWT) JWTParser.parse(apiKey);
payload = signedJWT.getJWTClaimsSet();
} catch (JSONException | IllegalArgumentException | ParseException e) {
if (log.isDebugEnabled()) {
log.debug("Invalid Api Key. Api Key: " + GatewayUtils.getMaskedToken(splitToken[0]), e);
}
log.error("Invalid JWT token. Failed to decode the Api Key body.");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
}
try {
isVerified = GatewayUtils.verifyTokenSignature(signedJWT, certAlias);
} catch (APISecurityException e) {
if (e.getErrorCode() == APISecurityConstants.API_AUTH_INVALID_CREDENTIALS) {
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
} else {
throw e;
}
}
if (isGatewayTokenCacheEnabled) {
// Add token to tenant token cache
if (isVerified) {
getGatewayApiKeyCache().put(tokenIdentifier, tenantDomain);
} else {
getInvalidGatewayApiKeyCache().put(tokenIdentifier, tenantDomain);
}
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
try {
// Start super tenant flow
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
// Add token to super tenant token cache
if (isVerified) {
getGatewayApiKeyCache().put(tokenIdentifier, tenantDomain);
} else {
getInvalidGatewayApiKeyCache().put(tokenIdentifier, tenantDomain);
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
}
// If Api Key signature is verified
if (isVerified) {
if (log.isDebugEnabled()) {
log.debug("Api Key signature is verified.");
}
if (isGatewayTokenCacheEnabled && payloadInfo != null) {
// Api Key is found in the key cache
payload = payloadInfo.getPayload();
if (isJwtTokenExpired(payload)) {
getGatewayApiKeyCache().remove(tokenIdentifier);
getInvalidGatewayApiKeyCache().put(tokenIdentifier, tenantDomain);
log.error("Api Key is expired");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
validateAPIKeyRestrictions(payload, synCtx);
} else {
// Retrieve payload from ApiKey
if (log.isDebugEnabled()) {
log.debug("ApiKey payload not found in the cache.");
}
if (payload == null) {
try {
signedJWT = (SignedJWT) JWTParser.parse(apiKey);
payload = signedJWT.getJWTClaimsSet();
} catch (JSONException | IllegalArgumentException | ParseException e) {
if (log.isDebugEnabled()) {
log.debug("Invalid ApiKey. ApiKey: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Api Key. Failed to decode the Api Key body.");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
}
}
if (isJwtTokenExpired(payload)) {
if (isGatewayTokenCacheEnabled) {
getGatewayApiKeyCache().remove(tokenIdentifier);
getInvalidGatewayApiKeyCache().put(tokenIdentifier, tenantDomain);
}
log.error("Api Key is expired");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
validateAPIKeyRestrictions(payload, synCtx);
if (isGatewayTokenCacheEnabled) {
JWTTokenPayloadInfo jwtTokenPayloadInfo = new JWTTokenPayloadInfo();
jwtTokenPayloadInfo.setPayload(payload);
jwtTokenPayloadInfo.setAccessToken(apiKey);
getGatewayApiKeyDataCache().put(cacheKey, jwtTokenPayloadInfo);
}
}
net.minidev.json.JSONObject api = GatewayUtils.validateAPISubscription(apiContext, apiVersion, payload, splitToken, false);
if (log.isDebugEnabled()) {
log.debug("Api Key authentication successful.");
}
String endUserToken = null;
String contextHeader = null;
if (jwtGenerationEnabled) {
SignedJWTInfo signedJWTInfo = new SignedJWTInfo(apiKey, signedJWT, payload);
JWTValidationInfo jwtValidationInfo = getJwtValidationInfo(signedJWTInfo);
JWTInfoDto jwtInfoDto = GatewayUtils.generateJWTInfoDto(api, jwtValidationInfo, null, synCtx);
endUserToken = generateAndRetrieveBackendJWTToken(tokenIdentifier, jwtInfoDto);
contextHeader = getContextHeader();
}
AuthenticationContext authenticationContext;
authenticationContext = GatewayUtils.generateAuthenticationContext(tokenIdentifier, payload, api, getApiLevelPolicy(), endUserToken, synCtx);
APISecurityUtils.setAuthenticationContext(synCtx, authenticationContext, contextHeader);
if (log.isDebugEnabled()) {
log.debug("User is authorized to access the resource using Api Key.");
}
return new AuthenticationResponse(true, isMandatory, false, 0, null);
}
if (log.isDebugEnabled()) {
log.debug("Api Key signature verification failure. Api Key: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Api Key. Signature verification failed.");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
} catch (APISecurityException e) {
return new AuthenticationResponse(false, isMandatory, true, e.getErrorCode(), e.getMessage());
} catch (ParseException e) {
log.error("Error while parsing API Key", e);
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
use of org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO in project carbon-apimgt by wso2.
the class APIKeyValidator method mapToAPIInfo.
private APIInfoDTO mapToAPIInfo(ArrayList<URITemplate> uriTemplates, String context, String apiVersion) {
APIInfoDTO apiInfoDTO = new APIInfoDTO();
apiInfoDTO.setApiName(context);
apiInfoDTO.setContext(context);
apiInfoDTO.setVersion(apiVersion);
apiInfoDTO.setResources(new LinkedHashSet<ResourceInfoDTO>());
ResourceInfoDTO resourceInfoDTO = null;
VerbInfoDTO verbInfoDTO = null;
// The following map is used to retrieve already created ResourceInfoDTO rather than iterating -
// the resource Set in apiInfoDTO.
LinkedHashMap<String, ResourceInfoDTO> resourcesMap = new LinkedHashMap<String, ResourceInfoDTO>();
for (URITemplate uriTemplate : uriTemplates) {
resourceInfoDTO = resourcesMap.get(uriTemplate.getUriTemplate());
if (null == resourceInfoDTO) {
resourceInfoDTO = new ResourceInfoDTO();
resourceInfoDTO.setUrlPattern(uriTemplate.getUriTemplate());
resourceInfoDTO.setHttpVerbs(new LinkedHashSet());
apiInfoDTO.getResources().add(resourceInfoDTO);
resourcesMap.put(uriTemplate.getUriTemplate(), resourceInfoDTO);
}
verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setHttpVerb(uriTemplate.getHTTPVerb());
verbInfoDTO.setAuthType(uriTemplate.getAuthType());
verbInfoDTO.setThrottling(uriTemplate.getThrottlingTier());
verbInfoDTO.setContentAware(uriTemplate.checkContentAwareFromThrottlingTiers());
verbInfoDTO.setThrottlingConditions(uriTemplate.getThrottlingConditions());
verbInfoDTO.setConditionGroups(uriTemplate.getConditionGroups());
verbInfoDTO.setApplicableLevel(uriTemplate.getApplicableLevel());
resourceInfoDTO.getHttpVerbs().add(verbInfoDTO);
}
return apiInfoDTO;
}
Aggregations