use of org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException in project carbon-apimgt by wso2.
the class InboundWebsocketProcessorUtil method validateScopes.
/**
* Validates scopes for subscription operations.
*
* @param inboundMessageContext InboundMessageContext
* @param subscriptionOperation Subscription operation
* @param operationId GraphQL message Id
* @return InboundProcessorResponseDTO
*/
public static InboundProcessorResponseDTO validateScopes(InboundMessageContext inboundMessageContext, String subscriptionOperation, String operationId) {
InboundProcessorResponseDTO responseDTO = new GraphQLProcessorResponseDTO();
// validate scopes based on subscription payload
try {
if (!InboundWebsocketProcessorUtil.authorizeGraphQLSubscriptionEvents(subscriptionOperation, inboundMessageContext)) {
String errorMessage = WebSocketApiConstants.FrameErrorConstants.RESOURCE_FORBIDDEN_ERROR_MESSAGE + StringUtils.SPACE + subscriptionOperation;
log.error(errorMessage);
responseDTO = InboundWebsocketProcessorUtil.getGraphQLFrameErrorDTO(WebSocketApiConstants.FrameErrorConstants.RESOURCE_FORBIDDEN_ERROR, errorMessage, false, operationId);
}
} catch (APIManagementException e) {
log.error(WebSocketApiConstants.FrameErrorConstants.API_AUTH_GENERAL_MESSAGE, e);
responseDTO = InboundWebsocketProcessorUtil.getFrameErrorDTO(WebSocketApiConstants.FrameErrorConstants.API_AUTH_GENERAL_ERROR, WebSocketApiConstants.FrameErrorConstants.API_AUTH_GENERAL_MESSAGE, true);
} catch (APISecurityException e) {
log.error(WebSocketApiConstants.FrameErrorConstants.RESOURCE_FORBIDDEN_ERROR_MESSAGE, e);
responseDTO = InboundWebsocketProcessorUtil.getGraphQLFrameErrorDTO(WebSocketApiConstants.FrameErrorConstants.RESOURCE_FORBIDDEN_ERROR, e.getMessage(), false, operationId);
}
return responseDTO;
}
use of org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException in project carbon-apimgt by wso2.
the class OAuthMediator method mediate.
@Override
public boolean mediate(MessageContext messageContext) {
if (log.isDebugEnabled()) {
log.debug("OAuth Mediator is invoked...");
}
CountDownLatch latch = new CountDownLatch(1);
TokenResponse tokenResponse = null;
if (oAuthEndpoint != null) {
try {
tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
latch.await();
} catch (InterruptedException | APISecurityException e) {
log.error("Could not generate access token...", e);
}
}
if (tokenResponse != null) {
String accessToken = tokenResponse.getAccessToken();
Map<String, Object> transportHeaders = (Map<String, Object>) ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty("TRANSPORT_HEADERS");
transportHeaders.put("Authorization", "Bearer " + accessToken);
if (log.isDebugEnabled()) {
log.debug("Access token set: " + GatewayUtils.getMaskedToken(accessToken));
}
} else {
log.debug("Token Response is empty...");
}
messageContext.setProperty(APIMgtGatewayConstants.OAUTH_ENDPOINT_INSTANCE, oAuthEndpoint);
return true;
}
use of org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException in project carbon-apimgt by wso2.
the class BasicAuthAuthenticatorTest method setup.
@Before
public void setup() throws Exception {
PowerMockito.mockStatic(OpenAPIUtils.class);
PowerMockito.when(OpenAPIUtils.getResourceAuthenticationScheme(Mockito.any(), Mockito.any())).thenReturn(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
messageContext = Mockito.mock(Axis2MessageContext.class);
axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
Mockito.when(axis2MsgCntxt.getProperty(APIMgtGatewayConstants.REQUEST_RECEIVED_TIME)).thenReturn("1506576365");
Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
Mockito.when((messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT))).thenReturn(Mockito.mock(OpenAPI.class));
basicAuthAuthenticator = new BasicAuthAuthenticator(CUSTOM_AUTH_HEADER, true, UNLIMITED_THROTTLE_POLICY);
BasicAuthCredentialValidator basicAuthCredentialValidator = Mockito.mock(BasicAuthCredentialValidator.class);
BasicAuthValidationInfoDTO basicAuthValidationInfoDTO = new BasicAuthValidationInfoDTO();
Mockito.when(basicAuthCredentialValidator.validate(Mockito.anyString(), Mockito.anyString())).thenAnswer(invocationOnMock -> {
Object argument1 = invocationOnMock.getArguments()[0];
Object argument2 = invocationOnMock.getArguments()[1];
if ((argument1.equals("test_username@carbon.super") || argument1.equals("test_username_blocked@carbon.super")) && argument2.equals("test_password")) {
basicAuthValidationInfoDTO.setAuthenticated(true);
basicAuthValidationInfoDTO.setHashedPassword("hashed_test_password");
if ("test_username@carbon.super".equals(argument1)) {
basicAuthValidationInfoDTO.setDomainQualifiedUsername("test_username@carbon.super");
} else if ("test_username_blocked@carbon.super".equals(argument1)) {
basicAuthValidationInfoDTO.setDomainQualifiedUsername("test_username_blocked@carbon.super");
}
String[] userRoleList = { "roleQ", "roleX" };
basicAuthValidationInfoDTO.setUserRoleList(userRoleList);
return basicAuthValidationInfoDTO;
}
return basicAuthValidationInfoDTO;
});
Mockito.when(basicAuthCredentialValidator.validateScopes(Mockito.anyString(), Mockito.any(OpenAPI.class), Mockito.any(MessageContext.class), Mockito.anyObject())).thenAnswer(invocationOnMock -> {
Object argument = invocationOnMock.getArguments()[0];
if (argument.equals("test_username@carbon.super")) {
return true;
} else if (argument.equals("test_username_blocked@carbon.super")) {
throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
}
return false;
});
PowerMockito.whenNew(BasicAuthCredentialValidator.class).withNoArguments().thenReturn(basicAuthCredentialValidator);
Mockito.when(messageContext.getProperty(BasicAuthAuthenticator.PUBLISHER_TENANT_DOMAIN)).thenReturn("carbon.super");
}
use of org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException 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" + "W1abU9E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ConfigurationDto = 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());
}
use of org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException in project carbon-apimgt by wso2.
the class JWTValidatorTest method testJWTValidatorForNonJTIScenario.
@Test
public void testJWTValidatorForNonJTIScenario() throws ParseException, APISecurityException, APIManagementException, IOException {
Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super");
SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + ".eyJpc3MiOiJodHRwczovL2xvY2FsaG9zdCIsImlhdCI6MTU5OTU0ODE3NCwiZXhwIjoxNjMxMDg0MTc0LC" + "JhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiR2l2ZW5OYW1l" + "IjoiSm9obm55IiwiU3VybmFtZSI6IlJvY2tldCIsIkVtYWlsIjoianJvY2tldEBleGFtcGxlLmNvbSIsIl" + "JvbGUiOlsiTWFuYWdlciIsIlByb2plY3QgQWRtaW5pc3RyYXRvciJdfQ.SSQyg_VTxF5drIogztn2SyEK" + "2wRE07wG6OW3tufD3vo");
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.getSignature().toString())).thenReturn("carbon.super");
Mockito.when(gatewayKeyCache.get(signedJWT.getSignature().toString())).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.getSignature().toString());
}
Aggregations