Search in sources :

Example 1 with OpenAPIParser

use of io.swagger.parser.OpenAPIParser in project carbon-apimgt by wso2.

the class GraphQLSchemaDefinition method buildSchemaWithAdditionalInfo.

/**
 * build schema with additional info
 *
 * @param api                   api object
 * @param graphqlComplexityInfo
 * @return schemaDefinition
 */
public String buildSchemaWithAdditionalInfo(API api, GraphqlComplexityInfo graphqlComplexityInfo) {
    Swagger swagger = null;
    Map<String, String> scopeRoleMap = new HashMap<>();
    Map<String, String> operationScopeMap = new HashMap<>();
    Map<String, String> operationAuthSchemeMap = new HashMap<>();
    Map<String, String> operationThrottlingMap = new HashMap<>();
    String operationScopeType;
    StringBuilder schemaDefinitionBuilder = new StringBuilder(api.getGraphQLSchema());
    schemaDefinitionBuilder.append("\n");
    StringBuilder operationScopeMappingBuilder = new StringBuilder();
    StringBuilder scopeRoleMappingBuilder = new StringBuilder();
    StringBuilder operationAuthSchemeMappingBuilder = new StringBuilder();
    StringBuilder operationThrottlingMappingBuilder = new StringBuilder();
    StringBuilder policyBuilder = new StringBuilder();
    String swaggerDef = api.getSwaggerDefinition();
    OpenAPI openAPI = null;
    LinkedHashMap<String, Object> scopeBindings = null;
    if (swaggerDef != null) {
        OpenAPIParser parser = new OpenAPIParser();
        openAPI = parser.readContents(swaggerDef, null, null).getOpenAPI();
    }
    Map<String, Object> extensions = null;
    if (openAPI != null) {
        extensions = openAPI.getComponents().getSecuritySchemes().get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions();
    }
    if (extensions != null) {
        scopeBindings = (LinkedHashMap<String, Object>) openAPI.getComponents().getSecuritySchemes().get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    }
    if (swaggerDef != null) {
        for (URITemplate template : api.getUriTemplates()) {
            String scopeInURITemplate = template.getScope() != null ? template.getScope().getKey() : null;
            if (scopeInURITemplate != null) {
                operationScopeMap.put(template.getUriTemplate(), scopeInURITemplate);
                if (!scopeRoleMap.containsKey(scopeInURITemplate)) {
                    if (scopeBindings != null) {
                        scopeRoleMap.put(scopeInURITemplate, scopeBindings.get(scopeInURITemplate).toString());
                    }
                }
            }
        }
        for (URITemplate template : api.getUriTemplates()) {
            operationThrottlingMap.put(template.getUriTemplate(), template.getThrottlingTier());
            operationAuthSchemeMap.put(template.getUriTemplate(), template.getAuthType());
        }
        if (operationScopeMap.size() > 0) {
            String base64EncodedURLOperationKey;
            String base64EncodedURLScope;
            for (Map.Entry<String, String> entry : operationScopeMap.entrySet()) {
                base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                base64EncodedURLScope = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
                operationScopeType = "type " + APIConstants.SCOPE_OPERATION_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + base64EncodedURLScope + ": String\n}\n";
                operationScopeMappingBuilder.append(operationScopeType);
            }
            schemaDefinitionBuilder.append(operationScopeMappingBuilder.toString());
        }
        if (scopeRoleMap.size() > 0) {
            String[] roleList;
            String scopeType;
            String base64EncodedURLScopeKey;
            String scopeRoleMappingType;
            String base64EncodedURLRole;
            String roleField;
            for (Map.Entry<String, String> entry : scopeRoleMap.entrySet()) {
                List<String> scopeRoles = new ArrayList<>();
                base64EncodedURLScopeKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                scopeType = "type " + APIConstants.SCOPE_ROLE_MAPPING + "_" + base64EncodedURLScopeKey + "{\n";
                StringBuilder scopeRoleBuilder = new StringBuilder(scopeType);
                roleList = entry.getValue().split(",");
                for (String role : roleList) {
                    if (!role.equals("") && !scopeRoles.contains(role)) {
                        base64EncodedURLRole = Base64.getUrlEncoder().withoutPadding().encodeToString(role.getBytes(Charset.defaultCharset()));
                        roleField = base64EncodedURLRole + ": String\n";
                        scopeRoleBuilder.append(roleField);
                        scopeRoles.add(role);
                    }
                }
                if (scopeRoles.size() > 0 && !StringUtils.isEmpty(scopeRoleBuilder.toString())) {
                    scopeRoleMappingType = scopeRoleBuilder.toString() + "}\n";
                    scopeRoleMappingBuilder.append(scopeRoleMappingType);
                }
            }
            schemaDefinitionBuilder.append(scopeRoleMappingBuilder.toString());
        }
        if (operationThrottlingMap.size() > 0) {
            String operationThrottlingType;
            for (Map.Entry<String, String> entry : operationThrottlingMap.entrySet()) {
                String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                String base64EncodedURLThrottilingTier = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
                operationThrottlingType = "type " + APIConstants.OPERATION_THROTTLING_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + base64EncodedURLThrottilingTier + ": String\n}\n";
                operationThrottlingMappingBuilder.append(operationThrottlingType);
            }
            schemaDefinitionBuilder.append(operationThrottlingMappingBuilder.toString());
        }
        if (operationAuthSchemeMap.size() > 0) {
            String operationAuthSchemeType;
            String isSecurityEnabled;
            for (Map.Entry<String, String> entry : operationAuthSchemeMap.entrySet()) {
                String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                if (entry.getValue().equalsIgnoreCase(APIConstants.AUTH_NO_AUTHENTICATION)) {
                    isSecurityEnabled = APIConstants.OPERATION_SECURITY_DISABLED;
                } else {
                    isSecurityEnabled = APIConstants.OPERATION_SECURITY_ENABLED;
                }
                operationAuthSchemeType = "type " + APIConstants.OPERATION_AUTH_SCHEME_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + isSecurityEnabled + ": String\n}\n";
                operationAuthSchemeMappingBuilder.append(operationAuthSchemeType);
            }
            schemaDefinitionBuilder.append(operationAuthSchemeMappingBuilder.toString());
        }
        if (operationAuthSchemeMap.size() > 0) {
            // Constructing the policy definition
            JSONObject jsonPolicyDefinition = policyDefinitionToJson(graphqlComplexityInfo);
            String base64EncodedPolicyDefinition = Base64.getUrlEncoder().withoutPadding().encodeToString(jsonPolicyDefinition.toJSONString().getBytes(Charset.defaultCharset()));
            String policyDefinition = "type " + APIConstants.GRAPHQL_ACCESS_CONTROL_POLICY + " {\n" + base64EncodedPolicyDefinition + ": String\n}\n";
            policyBuilder.append(policyDefinition);
            schemaDefinitionBuilder.append(policyBuilder.toString());
        }
    }
    return schemaDefinitionBuilder.toString();
}
Also used : URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) OpenAPIParser(io.swagger.parser.OpenAPIParser) JSONObject(org.json.simple.JSONObject) Swagger(io.swagger.models.Swagger) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 2 with OpenAPIParser

use of io.swagger.parser.OpenAPIParser in project carbon-apimgt by wso2.

the class APIMgtLatencyStatsHandler method setSwaggerToMessageContext.

private void setSwaggerToMessageContext(MessageContext messageContext) {
    // Read OpenAPI from local entry
    if (openAPI == null && apiUUID != null) {
        synchronized (this) {
            if (openAPI == null) {
                long startTime = System.currentTimeMillis();
                Entry localEntryObj = (Entry) messageContext.getConfiguration().getLocalRegistry().get(apiUUID);
                if (localEntryObj != null) {
                    swagger = localEntryObj.getValue().toString();
                    OpenAPIParser parser = new OpenAPIParser();
                    openAPI = parser.readContents(swagger, null, null).getOpenAPI();
                }
                long endTime = System.currentTimeMillis();
                if (log.isDebugEnabled()) {
                    log.debug("Time to parse the swagger(ms) : " + (endTime - startTime));
                }
            }
        }
    }
    // Add OpenAPI to message context
    messageContext.setProperty(APIMgtGatewayConstants.OPEN_API_OBJECT, openAPI);
    // Add swagger String to message context
    messageContext.setProperty(APIMgtGatewayConstants.OPEN_API_STRING, swagger);
}
Also used : Entry(org.apache.synapse.config.Entry) OpenAPIParser(io.swagger.parser.OpenAPIParser)

Example 3 with OpenAPIParser

use of io.swagger.parser.OpenAPIParser 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 4 with OpenAPIParser

use of io.swagger.parser.OpenAPIParser in project carbon-apimgt by wso2.

the class SchemaValidator method getOpenAPIValidator.

/**
 * Method to generate OpenApiInteractionValidator when the swagger is provided.
 *
 * @param swagger Swagger definition.
 * @return OpenApiInteractionValidator object for the provided swagger.
 */
private static OpenApiInteractionValidator getOpenAPIValidator(String swagger) {
    OpenAPIParser openAPIParser = new OpenAPIParser();
    ParseOptions options = new ParseOptions();
    options.setResolveFully(true);
    SwaggerParseResult swaggerParseResult = openAPIParser.readContents(swagger, new ArrayList<>(), options);
    OpenAPI openAPI = swaggerParseResult.getOpenAPI();
    return OpenApiInteractionValidator.createFor(openAPI).withLevelResolver(LevelResolver.create().withLevel("validation.schema.required", ValidationReport.Level.INFO).withLevel("validation.response.body.missing", ValidationReport.Level.INFO).build()).build();
}
Also used : ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) OpenAPIParser(io.swagger.parser.OpenAPIParser) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 5 with OpenAPIParser

use of io.swagger.parser.OpenAPIParser 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)

Aggregations

OpenAPIParser (io.swagger.parser.OpenAPIParser)6 OpenAPI (io.swagger.v3.oas.models.OpenAPI)5 SignedJWT (com.nimbusds.jwt.SignedJWT)3 HashMap (java.util.HashMap)3 Cache (javax.cache.Cache)3 MessageContext (org.apache.synapse.MessageContext)3 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)3 Test (org.junit.Test)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)3 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)3 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)3 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)3 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)3 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)3 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)3 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)3 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)2 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)2 Swagger (io.swagger.models.Swagger)1