Search in sources :

Example 16 with APIDefinitionFromSwagger20

use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20TestCase method testGenerateMergedResourceDefinition.

@Test
public void testGenerateMergedResourceDefinition() throws IOException {
    APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
    String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithAuthorization.yaml"));
    UriTemplate uriTemplate1 = new UriTemplate.UriTemplateBuilder().uriTemplate("/apis").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
    UriTemplate uriTemplate2 = new UriTemplate.UriTemplateBuilder().uriTemplate("/endpoints").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
    Map<String, UriTemplate> hasTemplateMap = new HashMap<>();
    hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate1.getUriTemplate(), uriTemplate1.getHttpVerb()), uriTemplate1);
    hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate2.getUriTemplate(), uriTemplate2.getHttpVerb()), uriTemplate2);
    API api = new API.APIBuilder("admin", "admin", "1.0.0").uriTemplates(hasTemplateMap).id(UUID.randomUUID().toString()).build();
    apiDefinitionFromSwagger20.generateMergedResourceDefinition(sampleApi, api);
}
Also used : HashMap(java.util.HashMap) API(org.wso2.carbon.apimgt.core.models.API) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Test(org.testng.annotations.Test)

Example 17 with APIDefinitionFromSwagger20

use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20TestCase method testAddNewScopeToSecurityDefinitionExistingSwaggerNonExisting.

@Test()
public void testAddNewScopeToSecurityDefinitionExistingSwaggerNonExisting() throws IOException, APIManagementException {
    APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
    String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithAuthorizationApiKey.yaml"));
    Scope scope = new Scope();
    scope.setName("apim:api_delete");
    scope.setDescription("Delete API");
    String scopeAddedSwagger = apiDefinitionFromSwagger20.addScopeToSwaggerDefinition(sampleApi, scope);
    Map<String, String> scopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(scopeAddedSwagger);
    Assert.assertTrue(scopes.containsKey("apim:api_delete"));
}
Also used : Scope(org.wso2.carbon.apimgt.core.models.Scope) Test(org.testng.annotations.Test)

Example 18 with APIDefinitionFromSwagger20

use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.

the class OAuth2Authenticator method validateScopes.

/*
    * This method validates the given scope against scopes defined in the api resource
    * @param Request
    * @param ServiceMethodInfo
    * @param scopesToValidate scopes extracted from the access token
    * @return true if scope validation successful
    * */
@SuppressFBWarnings({ "DLS_DEAD_LOCAL_STORE" })
private boolean validateScopes(Request request, ServiceMethodInfo serviceMethodInfo, String scopesToValidate, String restAPIResource) throws APIMgtSecurityException {
    final boolean[] authorized = { false };
    String path = (String) request.getProperty(APIConstants.REQUEST_URL);
    String verb = (String) request.getProperty(APIConstants.HTTP_METHOD);
    if (log.isDebugEnabled()) {
        log.debug("Invoking rest api resource path " + verb + " " + path + " ");
        log.debug("LoggedIn user scopes " + scopesToValidate);
    }
    String[] scopesArr = new String[0];
    if (scopesToValidate != null) {
        scopesArr = scopesToValidate.split(" ");
    }
    if (scopesToValidate != null && scopesArr.length > 0) {
        final List<String> scopes = Arrays.asList(scopesArr);
        if (restAPIResource != null) {
            APIDefinition apiDefinition = new APIDefinitionFromSwagger20();
            try {
                String apiResourceDefinitionScopes = apiDefinition.getScopeOfResourcePath(restAPIResource, request, serviceMethodInfo);
                if (StringUtils.isEmpty(apiResourceDefinitionScopes)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Scope not defined in swagger for matching resource " + path + " and verb " + verb + " . Hence consider as anonymous permission and let request to continue.");
                    }
                    // scope validation gets through if no scopes found in the api definition
                    authorized[0] = true;
                } else {
                    Arrays.stream(apiResourceDefinitionScopes.split(" ")).forEach(scopeKey -> {
                        Optional<String> key = scopes.stream().filter(scp -> {
                            return scp.equalsIgnoreCase(scopeKey);
                        }).findAny();
                        if (key.isPresent()) {
                            // scope validation success if one of the
                            authorized[0] = true;
                        // apiResourceDefinitionScopes found.
                        }
                    });
                }
            } catch (APIManagementException e) {
                String message = "Error while validating scopes";
                log.error(message, e);
                throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Rest API resource could not be found for request path '" + path + "'");
            }
        }
    } else {
        // scope validation gets through if access token does not contain scopes to validate
        authorized[0] = true;
    }
    if (!authorized[0]) {
        String message = "Scope validation fails for the scopes " + scopesToValidate;
        throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
    }
    return authorized[0];
}
Also used : Arrays(java.util.Arrays) TypeToken(com.google.gson.reflect.TypeToken) ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) RESTAPIAuthenticator(org.wso2.carbon.apimgt.rest.api.common.api.RESTAPIAuthenticator) LoggerFactory(org.slf4j.LoggerFactory) Request(org.wso2.msf4j.Request) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) APIManagerFactory(org.wso2.carbon.apimgt.core.impl.APIManagerFactory) APIDefinitionFromSwagger20(org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20) StringUtils(org.apache.commons.lang3.StringUtils) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) RestApiUtil(org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) Response(org.wso2.msf4j.Response) Locale(java.util.Locale) APIDefinition(org.wso2.carbon.apimgt.core.api.APIDefinition) ServiceMethodInfo(org.wso2.msf4j.ServiceMethodInfo) Logger(org.slf4j.Logger) APIConstants(org.wso2.carbon.apimgt.rest.api.common.APIConstants) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) SystemVariableUtil(org.wso2.msf4j.util.SystemVariableUtil) ExceptionCodes(org.wso2.carbon.apimgt.core.exception.ExceptionCodes) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Optional(java.util.Optional) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) APIDefinition(org.wso2.carbon.apimgt.core.api.APIDefinition) APIDefinitionFromSwagger20(org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 19 with APIDefinitionFromSwagger20

use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testGetScopesFromApi.

@Test(description = "Save swagger definition for API")
public void testGetScopesFromApi() throws APIManagementException, IOException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO);
    String newSwagger = IOUtils.toString(new FileInputStream("src" + File.separator + "test" + File.separator + "resources" + File.separator + "swagger" + File.separator + "swaggerWithAuthorization" + ".yaml"));
    Mockito.when(apiDAO.getApiSwaggerDefinition("abcd")).thenReturn(newSwagger);
    Map<String, String> scopesSet = apiPublisher.getScopesForApi("abcd");
    Map<String, String> scopes = new APIDefinitionFromSwagger20().getScopesFromSecurityDefinition(newSwagger);
    scopesSet.keySet().removeAll(scopes.keySet());
    Assert.assertTrue(scopesSet.isEmpty());
}
Also used : ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) FileInputStream(java.io.FileInputStream) Test(org.testng.annotations.Test)

Example 20 with APIDefinitionFromSwagger20

use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.

the class APIPublisherImpl method saveSwagger20Definition.

/**
 * {@inheritDoc}
 */
@Override
public void saveSwagger20Definition(String apiId, String jsonText) throws APIManagementException {
    try {
        LocalDateTime localDateTime = LocalDateTime.now();
        Map<String, String> oldScopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(getApiSwaggerDefinition(apiId));
        Map<String, String> newScopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(jsonText);
        Map<String, String> updatedScopes = new HashMap<>(newScopes);
        updatedScopes.keySet().retainAll(oldScopes.keySet());
        oldScopes.keySet().removeAll(updatedScopes.keySet());
        newScopes.keySet().removeAll(updatedScopes.keySet());
        for (Map.Entry<String, String> scopeEntry : newScopes.entrySet()) {
            getKeyManager().registerScope(new Scope(scopeEntry.getKey(), scopeEntry.getValue()));
        }
        for (Map.Entry<String, String> scopeEntry : oldScopes.entrySet()) {
            getKeyManager().deleteScope(scopeEntry.getKey());
        }
        for (Map.Entry<String, String> scopeEntry : updatedScopes.entrySet()) {
            Scope scope = getKeyManager().retrieveScope(scopeEntry.getKey());
            scope.setDescription(scopeEntry.getValue());
            getKeyManager().updateScope(scope);
        }
        API api = getAPIbyUUID(apiId);
        Map<String, UriTemplate> oldUriTemplateMap = api.getUriTemplates();
        List<APIResource> apiResourceList = apiDefinitionFromSwagger20.parseSwaggerAPIResources(new StringBuilder(jsonText));
        Map<String, UriTemplate> updatedUriTemplateMap = new HashMap<>();
        for (APIResource apiResource : apiResourceList) {
            updatedUriTemplateMap.put(apiResource.getUriTemplate().getTemplateId(), apiResource.getUriTemplate());
        }
        Map<String, UriTemplate> uriTemplateMapNeedTobeUpdate = APIUtils.getMergedUriTemplates(oldUriTemplateMap, updatedUriTemplateMap);
        API.APIBuilder apiBuilder = new API.APIBuilder(api);
        apiBuilder.uriTemplates(uriTemplateMapNeedTobeUpdate);
        createUriTemplateList(apiBuilder, true);
        apiBuilder.updatedBy(getUsername());
        apiBuilder.lastUpdatedTime(localDateTime);
        api = apiBuilder.build();
        GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
        APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
        gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
        String existingGatewayConfig = getApiGatewayConfig(apiId);
        String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(existingGatewayConfig, jsonText);
        getApiDAO().updateAPI(apiId, api);
        getApiDAO().updateApiDefinition(apiId, jsonText, getUsername());
        getApiDAO().updateGatewayConfig(apiId, updatedGatewayConfig, getUsername());
    } catch (APIMgtDAOException e) {
        String errorMsg = "Couldn't update the Swagger Definition";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) HashMap(java.util.HashMap) APIResource(org.wso2.carbon.apimgt.core.models.APIResource) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Scope(org.wso2.carbon.apimgt.core.models.Scope) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) Map(java.util.Map) HashMap(java.util.HashMap) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)15 HashMap (java.util.HashMap)12 API (org.wso2.carbon.apimgt.core.models.API)12 Test (org.testng.annotations.Test)10 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)9 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)8 Scope (org.wso2.carbon.apimgt.core.models.Scope)7 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)5 IOException (java.io.IOException)4 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)4 GatewayException (org.wso2.carbon.apimgt.core.exception.GatewayException)4 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)4 APIConfigContext (org.wso2.carbon.apimgt.core.template.APIConfigContext)4 LocalDateTime (java.time.LocalDateTime)3 Map (java.util.Map)3 ParseException (org.json.simple.parser.ParseException)3 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)3 APIDefinitionFromSwagger20 (org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20)3 LifecycleException (org.wso2.carbon.lcm.core.exception.LifecycleException)3 FileInputStream (java.io.FileInputStream)2