Search in sources :

Example 46 with Pet

use of io.swagger.v3.jaxrs2.resources.model.Pet in project carbon-apimgt by wso2.

the class JWTValidatorTest method testJWTValidatorExpiredInCache.

@Test
public void testJWTValidatorExpiredInCache() 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() + 5L);
    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);
    OpenAPIParser parser = new OpenAPIParser();
    String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json"));
    OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI();
    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");
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis() - 100);
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis());
    Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo);
    try {
        authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    } catch (APISecurityException e) {
        Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    }
    Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo);
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID());
    Mockito.verify(invalidTokenCache, Mockito.times(1)).put(signedJWT.getJWTClaimsSet().getJWTID(), "carbon.super");
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) 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) OpenAPIParser(io.swagger.parser.OpenAPIParser) 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) OpenAPI(io.swagger.v3.oas.models.OpenAPI) 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)

Example 47 with Pet

use of io.swagger.v3.jaxrs2.resources.model.Pet in project carbon-apimgt by wso2.

the class JWTValidatorTest method testJWTValidatorInvalid.

@Test
public void testJWTValidatorInvalid() throws ParseException, APIManagementException, IOException, APISecurityException {
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com");
    SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w");
    SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet());
    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(false);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setValidationCode(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    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);
    OpenAPIParser parser = new OpenAPIParser();
    String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json"));
    OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("api1");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    try {
        AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
        Assert.fail("JWT get Authenticated");
    } catch (APISecurityException e) {
        Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    }
    Mockito.when(invalidTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super");
    String cacheKey = GatewayUtils.getAccessTokenCacheKey(signedJWT.getJWTClaimsSet().getJWTID(), "/api1", "1.0", "/pet/findByStatus", "GET");
    try {
        jwtValidator.authenticate(signedJWTInfo, messageContext);
    } catch (APISecurityException e) {
        Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    }
    Mockito.verify(apiKeyValidator, Mockito.never()).validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID());
    Mockito.verify(gatewayKeyCache, Mockito.never()).get(cacheKey);
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) HashMap(java.util.HashMap) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) OpenAPIParser(io.swagger.parser.OpenAPIParser) 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) OpenAPI(io.swagger.v3.oas.models.OpenAPI) 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)

Example 48 with Pet

use of io.swagger.v3.jaxrs2.resources.model.Pet in project carbon-apimgt by wso2.

the class JWTValidatorTest method testJWTValidatorInvalidConsumerKey.

@Test
public void testJWTValidatorInvalidConsumerKey() throws ParseException, APIManagementException, IOException, APISecurityException {
    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");
    SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet());
    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.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    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);
    OpenAPIParser parser = new OpenAPIParser();
    String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json"));
    OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setAuthorized(false);
    apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
    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);
    try {
        jwtValidator.authenticate(signedJWTInfo, messageContext);
        Assert.fail("JWT get Authenticated");
    } catch (APISecurityException e) {
        Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_FORBIDDEN);
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) 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) OpenAPIParser(io.swagger.parser.OpenAPIParser) 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) OpenAPI(io.swagger.v3.oas.models.OpenAPI) 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)

Example 49 with Pet

use of io.swagger.v3.jaxrs2.resources.model.Pet in project swagger-parser by swagger-api.

the class OpenAPIDeserializerTest method testAllOfSchema.

@Test
public void testAllOfSchema(@Injectable List<AuthorizationValue> auths) {
    String yaml = "openapi: '3.0'\n" + "components:\n" + "  schemas:\n" + "    Pet:\n" + "      type: object\n" + "      required:\n" + "      - pet_type\n" + "      properties:\n" + "        pet_type:\n" + "          type: string\n" + "    Cat:\n" + "      allOf:\n" + "      - $ref: '#/components/schemas/Pet'\n" + "      - type: object\n" + "        # all other properties specific to a `Cat`\n" + "        properties:\n" + "          name:\n" + "            type: string\n";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = parser.readContents(yaml, auths, options);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<>(messageList);
    Schema catSchema = result.getOpenAPI().getComponents().getSchemas().get("Cat");
    assertTrue(catSchema != null);
    assertTrue(catSchema instanceof ComposedSchema);
    ComposedSchema catCompSchema = (ComposedSchema) catSchema;
    List<Schema> allOfSchemas = catCompSchema.getAllOf();
    assertTrue(allOfSchemas != null);
    assertEquals(allOfSchemas.size(), 2);
    Schema refPetSchema = allOfSchemas.get(0);
    assertTrue(refPetSchema != null);
    assertEquals(refPetSchema.get$ref(), "#/components/schemas/Pet");
    Schema otherSchema = allOfSchemas.get(1);
    assertTrue(otherSchema != null);
    assertTrue(otherSchema.getProperties() != null);
    Schema nameProp = (Schema) otherSchema.getProperties().get("name");
    assertTrue(nameProp != null);
    assertEquals(nameProp.getType(), "string");
}
Also used : DateSchema(io.swagger.v3.oas.models.media.DateSchema) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) DateTimeSchema(io.swagger.v3.oas.models.media.DateTimeSchema) ByteArraySchema(io.swagger.v3.oas.models.media.ByteArraySchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) MapSchema(io.swagger.v3.oas.models.media.MapSchema) BinarySchema(io.swagger.v3.oas.models.media.BinarySchema) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 50 with Pet

use of io.swagger.v3.jaxrs2.resources.model.Pet in project swagger-parser by swagger-api.

the class OpenAPIDeserializerTest method readPathsObject.

@Test(dataProvider = "data")
public void readPathsObject(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);
    Assert.assertNotNull(result);
    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    final Paths paths = openAPI.getPaths();
    Assert.assertNotNull(paths);
    Assert.assertEquals(paths.size(), 19);
    PathItem petRef = paths.get("/pathItemRef");
    PathItem petEndpoint = paths.get("/pet");
    Assert.assertNotNull(petEndpoint);
    Assert.assertEquals(petEndpoint.getSummary(), "summary");
    Assert.assertEquals(petEndpoint.getDescription(), "description");
    Assert.assertNotNull(petEndpoint.getPost().getExternalDocs());
    Assert.assertEquals(petEndpoint.getPost().getExternalDocs().getUrl(), "http://swagger.io");
    Assert.assertEquals(petEndpoint.getPost().getExternalDocs().getDescription(), "Find out more");
    // Operation trace
    Assert.assertNotNull(petEndpoint.getTrace());
    Assert.assertNotNull(petEndpoint.getDescription());
    // Operation post
    Assert.assertNotNull(petEndpoint.getPost());
    Assert.assertNotNull(petEndpoint.getPost().getTags());
    Assert.assertEquals(petEndpoint.getPost().getTags().size(), 1);
    Assert.assertEquals(petEndpoint.getPost().getSummary(), "Add a new pet to the store");
    Assert.assertEquals(petEndpoint.getPost().getDescription(), "");
    Assert.assertEquals(petEndpoint.getPost().getOperationId(), "addPet");
    Assert.assertNotNull(petEndpoint.getServers());
    Assert.assertEquals(petEndpoint.getServers().size(), 1);
    Assert.assertNotNull(petEndpoint.getParameters());
    Assert.assertEquals(petEndpoint.getParameters().size(), 2);
    Assert.assertNotNull(petEndpoint.getPost().getParameters());
    Assert.assertEquals(petEndpoint.getPost().getSecurity().get(0).get("petstore_auth").get(0), "write:pets");
    Assert.assertEquals(petEndpoint.getPost().getSecurity().get(0).get("petstore_auth").get(1), "read:pets");
    ApiResponses responses = petEndpoint.getPost().getResponses();
    Assert.assertNotNull(responses);
    assertTrue(responses.containsKey("405"));
    ApiResponse response = responses.get("405");
    Assert.assertEquals(response.getDescription(), "Invalid input");
    Assert.assertEquals(response.getHeaders().get("X-Rate-Limit").getDescription(), "calls per hour allowed by the user");
    // parameters operation get
    PathItem petByStatusEndpoint = paths.get("/pet/findByStatus");
    Assert.assertNotNull(petByStatusEndpoint.getGet());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getTags());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getIn(), "query");
    Assert.assertEquals(petByStatusEndpoint.getGet().getCallbacks().get("mainHook").get("$request.body#/url").getPost().getResponses().get("200").getDescription(), "webhook successfully processed operation");
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Paths(io.swagger.v3.oas.models.Paths) OpenAPI(io.swagger.v3.oas.models.OpenAPI) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)69 OpenAPI (io.swagger.v3.oas.models.OpenAPI)60 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)37 Schema (io.swagger.v3.oas.models.media.Schema)32 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)28 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)28 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)24 StringSchema (io.swagger.v3.oas.models.media.StringSchema)24 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)20 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)17 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)17 PathItem (io.swagger.v3.oas.models.PathItem)16 ByteArraySchema (io.swagger.v3.oas.models.media.ByteArraySchema)15 MapSchema (io.swagger.v3.oas.models.media.MapSchema)12 DateSchema (io.swagger.v3.oas.models.media.DateSchema)10 DateTimeSchema (io.swagger.v3.oas.models.media.DateTimeSchema)10 ArrayList (java.util.ArrayList)10 Operation (io.swagger.v3.oas.models.Operation)9 Paths (io.swagger.v3.oas.models.Paths)9 Parameter (io.swagger.v3.oas.models.parameters.Parameter)8