Search in sources :

Example 21 with APIDefinition

use of org.wso2.carbon.apimgt.core.api.APIDefinition 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 22 with APIDefinition

use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.

the class CompositeApisApiServiceImpl method compositeApisApiIdSwaggerPut.

/**
 * Updates the swagger defnition of an API
 *
 * @param apiId             UUID of API
 * @param apiDefinition     updated swagger defintion
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return Updated swagger definition
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response compositeApisApiIdSwaggerPut(String apiId, String apiDefinition, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String existingFingerprint = compositeApisApiIdSwaggerGetFingerprint(apiId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        apiStore.updateCompositeApiDefinition(apiId, apiDefinition);
        String apiSwagger = apiStore.getCompositeApiDefinition(apiId);
        String newFingerprint = compositeApisApiIdSwaggerGetFingerprint(apiId, null, null, request);
        return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(apiSwagger).build();
    } catch (APIManagementException e) {
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 23 with APIDefinition

use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
    businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    Set<String> visibleRoles = new HashSet<>();
    visibleRoles.add("testRple");
    List<String> labels = new ArrayList<>();
    labels.add("testLabel");
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put("TestEndpoint", createMockEndpoint());
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 24 with APIDefinition

use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method generateApiFromSwaggerResource.

/**
 * return API Object
 *
 * @param provider      Provider of the API.
 * @param apiDefinition API definition as string
 * @return API object.
 * @throws APIManagementException If failed to generate API from swagger.
 */
@Override
public API.APIBuilder generateApiFromSwaggerResource(String provider, String apiDefinition) throws APIManagementException {
    SwaggerParser swaggerParser = new SwaggerParser();
    Swagger swagger = swaggerParser.parse(apiDefinition);
    if (swagger == null) {
        throw new APIManagementException("Swagger could not be generated from provided API definition");
    }
    Info apiInfo = swagger.getInfo();
    if (apiInfo == null) {
        throw new APIManagementException("Swagger doesn't contains the info");
    } else {
        String apiName = apiInfo.getTitle();
        String apiVersion = apiInfo.getVersion();
        String apiDescription = apiInfo.getDescription();
        Contact contact = apiInfo.getContact();
        BusinessInformation businessInformation = new BusinessInformation();
        if (contact != null) {
            businessInformation.setBusinessOwner(contact.getName());
            businessInformation.setBusinessOwnerEmail(contact.getEmail());
        }
        API.APIBuilder apiBuilder = new API.APIBuilder(provider, apiName, apiVersion);
        apiBuilder.businessInformation(businessInformation);
        apiBuilder.description(apiDescription);
        apiBuilder.context(swagger.getBasePath());
        List<APIResource> apiResourceList = parseSwaggerAPIResources(new StringBuilder(apiDefinition));
        Map<String, UriTemplate> uriTemplateMap = new HashMap();
        for (APIResource apiResource : apiResourceList) {
            uriTemplateMap.put(apiResource.getUriTemplate().getTemplateId(), apiResource.getUriTemplate());
        }
        apiBuilder.uriTemplates(uriTemplateMap);
        apiBuilder.id(UUID.randomUUID().toString());
        return apiBuilder;
    }
}
Also used : BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) APIResource(org.wso2.carbon.apimgt.core.models.APIResource) Info(io.swagger.models.Info) ServiceMethodInfo(org.wso2.msf4j.ServiceMethodInfo) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Contact(io.swagger.models.Contact) SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Swagger(io.swagger.models.Swagger) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API)

Example 25 with APIDefinition

use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    List<String> defaultLabels = getDefaultLabels();
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).labels(defaultLabels).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(new HashSet<>()).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).securityScheme(3).threatProtectionPolicies(threatProtectionPolicies);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) ThreatProtectionPolicy(org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) HashMap(java.util.HashMap) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) Map(java.util.Map) HashedMap(org.apache.commons.collections.map.HashedMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Aggregations

API (org.wso2.carbon.apimgt.core.models.API)30 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)25 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 HashMap (java.util.HashMap)16 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)13 HashSet (java.util.HashSet)12 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)12 CorsConfiguration (org.wso2.carbon.apimgt.core.models.CorsConfiguration)12 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)12 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)11 Map (java.util.Map)9 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)8 QuotaPolicy (org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy)7 ArrayList (java.util.ArrayList)5 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)5 CustomPolicy (org.wso2.carbon.apimgt.core.models.policy.CustomPolicy)5 ThreatProtectionPolicy (org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy)5 HashedMap (org.apache.commons.collections.map.HashedMap)4