Search in sources :

Example 41 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class OASParserUtil method setScopes.

private static void setScopes(final OpenAPI destOpenAPI, final Set<Scope> aggregatedScopes) {
    Map<String, SecurityScheme> securitySchemes;
    SecurityScheme securityScheme;
    OAuthFlow oAuthFlow;
    Scopes scopes = new Scopes();
    if (destOpenAPI.getComponents() != null && (securitySchemes = destOpenAPI.getComponents().getSecuritySchemes()) != null && (securityScheme = securitySchemes.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY)) != null && (oAuthFlow = securityScheme.getFlows().getImplicit()) != null) {
        Map<String, String> scopeBindings = new HashMap<>();
        for (Scope scope : aggregatedScopes) {
            scopes.addString(scope.getKey(), scope.getDescription());
            scopeBindings.put(scope.getKey(), scope.getRoles());
        }
        oAuthFlow.setScopes(scopes);
        Map<String, Object> extensions = new HashMap<>();
        extensions.put(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
        oAuthFlow.setExtensions(extensions);
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) HashMap(java.util.HashMap) Scopes(io.swagger.v3.oas.models.security.Scopes) JSONObject(org.json.JSONObject) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme)

Example 42 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class OAS2Parser method getURITemplates.

/**
 * This method returns URI templates according to the given swagger file
 *
 * @param resourceConfigsJSON swaggerJSON
 * @return URI Templates
 * @throws APIManagementException
 */
@Override
public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException {
    Swagger swagger = getSwagger(resourceConfigsJSON);
    Set<URITemplate> urlTemplates = new LinkedHashSet<>();
    Set<Scope> scopes = getScopes(resourceConfigsJSON);
    String oauth2SchemeKey = getOAuth2SecuritySchemeKey(swagger);
    for (String pathString : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathString);
        Map<HttpMethod, Operation> operationMap = path.getOperationMap();
        for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
            Operation operation = entry.getValue();
            URITemplate template = new URITemplate();
            template.setHTTPVerb(entry.getKey().name().toUpperCase());
            template.setHttpVerbs(entry.getKey().name().toUpperCase());
            template.setUriTemplate(pathString);
            List<String> opScopes = getScopeOfOperations(oauth2SchemeKey, operation);
            if (!opScopes.isEmpty()) {
                if (opScopes.size() == 1) {
                    String firstScope = opScopes.get(0);
                    if (StringUtils.isNotBlank(firstScope)) {
                        Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
                        if (scope == null) {
                            throw new APIManagementException("Scope '" + firstScope + "' not found.");
                        }
                        template.setScope(scope);
                        template.setScopes(scope);
                    }
                } else {
                    template = OASParserUtil.setScopesToTemplate(template, opScopes, scopes);
                }
            }
            Map<String, Object> extensions = operation.getVendorExtensions();
            if (extensions != null) {
                if (extensions.containsKey(APIConstants.SWAGGER_X_AUTH_TYPE)) {
                    String authType = (String) extensions.get(APIConstants.SWAGGER_X_AUTH_TYPE);
                    template.setAuthType(authType);
                    template.setAuthTypes(authType);
                } else {
                    template.setAuthType("Any");
                    template.setAuthTypes("Any");
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_THROTTLING_TIER)) {
                    String throttlingTier = (String) extensions.get(APIConstants.SWAGGER_X_THROTTLING_TIER);
                    template.setThrottlingTier(throttlingTier);
                    template.setThrottlingTiers(throttlingTier);
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                    String mediationScript = (String) extensions.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                    template.setMediationScript(mediationScript);
                    template.setMediationScripts(template.getHTTPVerb(), mediationScript);
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                    template.setAmznResourceName((String) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                    template.setAmznResourceTimeout(((Long) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                }
            }
            urlTemplates.add(template);
        }
    }
    return urlTemplates;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Operation(io.swagger.models.Operation) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 43 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class OAS3Parser method updateSwaggerSecurityDefinition.

/**
 * Include Scope details to the definition
 *
 * @param openAPI     openapi definition
 * @param swaggerData Swagger related API data
 */
private void updateSwaggerSecurityDefinition(OpenAPI openAPI, SwaggerData swaggerData, String authUrl) {
    if (openAPI.getComponents() == null) {
        openAPI.setComponents(new Components());
    }
    Map<String, SecurityScheme> securitySchemes = openAPI.getComponents().getSecuritySchemes();
    if (securitySchemes == null) {
        securitySchemes = new HashMap<>();
        openAPI.getComponents().setSecuritySchemes(securitySchemes);
    }
    SecurityScheme securityScheme = securitySchemes.get(OPENAPI_SECURITY_SCHEMA_KEY);
    if (securityScheme == null) {
        securityScheme = new SecurityScheme();
        securityScheme.setType(SecurityScheme.Type.OAUTH2);
        securitySchemes.put(OPENAPI_SECURITY_SCHEMA_KEY, securityScheme);
        List<SecurityRequirement> security = new ArrayList<SecurityRequirement>();
        SecurityRequirement secReq = new SecurityRequirement();
        secReq.addList(OPENAPI_SECURITY_SCHEMA_KEY, new ArrayList<String>());
        security.add(secReq);
        openAPI.setSecurity(security);
    }
    if (securityScheme.getFlows() == null) {
        securityScheme.setFlows(new OAuthFlows());
    }
    OAuthFlow oAuthFlow = securityScheme.getFlows().getImplicit();
    if (oAuthFlow == null) {
        oAuthFlow = new OAuthFlow();
        securityScheme.getFlows().setImplicit(oAuthFlow);
    }
    oAuthFlow.setAuthorizationUrl(authUrl);
    Scopes oas3Scopes = new Scopes();
    Set<Scope> scopes = swaggerData.getScopes();
    if (scopes != null && !scopes.isEmpty()) {
        Map<String, String> scopeBindings = new HashMap<>();
        for (Scope scope : scopes) {
            String description = scope.getDescription() != null ? scope.getDescription() : "";
            oas3Scopes.put(scope.getKey(), description);
            String roles = (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) ? scope.getRoles() : StringUtils.EMPTY;
            scopeBindings.put(scope.getKey(), roles);
        }
        oAuthFlow.addExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
    }
    oAuthFlow.setScopes(oas3Scopes);
}
Also used : OAuthFlows(io.swagger.v3.oas.models.security.OAuthFlows) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) Components(io.swagger.v3.oas.models.Components) Scope(org.wso2.carbon.apimgt.api.model.Scope) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) Scopes(io.swagger.v3.oas.models.security.Scopes) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 44 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class APIDefinitionFromOpenAPISpec method validateScopesFromSwagger.

/**
 * Called using the jaggery api. Checks if the swagger contains valid api scopes.
 *
 * @param swagger Swagger definition
 * @return true if the scope definition is valid
 * @throws APIManagementException
 */
public Boolean validateScopesFromSwagger(String swagger) throws APIManagementException {
    try {
        Set<Scope> scopes = getScopes(swagger);
        JSONParser parser = new JSONParser();
        JSONObject swaggerJson;
        swaggerJson = (JSONObject) parser.parse(swagger);
        if (swaggerJson.get("paths") != null) {
            JSONObject paths = (JSONObject) swaggerJson.get("paths");
            for (Object uriTempKey : paths.keySet()) {
                String uriTemp = (String) uriTempKey;
                // if url template is a custom attribute "^x-" ignore.
                if (uriTemp.startsWith("x-") || uriTemp.startsWith("X-")) {
                    continue;
                }
                JSONObject path = (JSONObject) paths.get(uriTemp);
                // See field types supported by "Path Item Object" in swagger spec.
                if (path.containsKey("$ref")) {
                    continue;
                }
                for (Object httpVerbKey : path.keySet()) {
                    String httpVerb = (String) httpVerbKey;
                    JSONObject operation = (JSONObject) path.get(httpVerb);
                    String operationScope = (String) operation.get(APIConstants.SWAGGER_X_SCOPE);
                    Scope scope = APIUtil.findScopeByKey(scopes, operationScope);
                    if (scope == null && operationScope != null) {
                        return false;
                    }
                }
            }
        }
        return true;
    } catch (APIManagementException e) {
        handleException("Error when validating scopes", e);
        return false;
    } catch (ParseException e) {
        handleException("Error when validating scopes", e);
        return false;
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Example 45 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class AsyncApiParser method updateAsyncAPIDefinition.

public String updateAsyncAPIDefinition(String oldDefinition, API apiToUpdate) {
    Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(oldDefinition);
    if (document.components == null) {
        document.components = document.createComponents();
    }
    // add scopes
    if (document.components.securitySchemes == null) {
        document.components.securitySchemes = new HashMap<>();
    }
    Aai20SecurityScheme oauth2SecurityScheme = new Aai20SecurityScheme(document.components, APIConstants.DEFAULT_API_SECURITY_OAUTH2);
    oauth2SecurityScheme.type = APIConstants.DEFAULT_API_SECURITY_OAUTH2;
    if (oauth2SecurityScheme.flows == null) {
        oauth2SecurityScheme.flows = new Aai20OAuthFlows(oauth2SecurityScheme);
    }
    if (oauth2SecurityScheme.flows.implicit == null) {
        oauth2SecurityScheme.flows.implicit = new Aai20ImplicitOAuthFlow(oauth2SecurityScheme.flows);
    }
    oauth2SecurityScheme.flows.implicit.authorizationUrl = "http://localhost:9999";
    Map<String, String> scopes = new HashMap<>();
    Map<String, String> scopeBindings = new HashMap<>();
    Iterator<Scope> iterator = apiToUpdate.getScopes().iterator();
    while (iterator.hasNext()) {
        Scope scope = iterator.next();
        scopes.put(scope.getName(), scope.getDescription());
        scopeBindings.put(scope.getName(), scope.getRoles());
    }
    oauth2SecurityScheme.flows.implicit.scopes = scopes;
    Extension xScopeBindings = oauth2SecurityScheme.flows.implicit.createExtension();
    xScopeBindings.name = APIConstants.SWAGGER_X_SCOPES_BINDINGS;
    xScopeBindings.value = scopeBindings;
    oauth2SecurityScheme.flows.implicit.addExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS, xScopeBindings);
    document.components.securitySchemes.put(APIConstants.DEFAULT_API_SECURITY_OAUTH2, oauth2SecurityScheme);
    return Library.writeDocumentToJSONString(document);
}
Also used : Extension(io.apicurio.datamodels.core.models.Extension) Aai20SecurityScheme(io.apicurio.datamodels.asyncapi.v2.models.Aai20SecurityScheme) Aai20ImplicitOAuthFlow(io.apicurio.datamodels.asyncapi.v2.models.Aai20ImplicitOAuthFlow) Scope(org.wso2.carbon.apimgt.api.model.Scope) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Aai20Document(io.apicurio.datamodels.asyncapi.v2.models.Aai20Document) Aai20OAuthFlows(io.apicurio.datamodels.asyncapi.v2.models.Aai20OAuthFlows)

Aggregations

Scope (org.wso2.carbon.apimgt.api.model.Scope)97 HashMap (java.util.HashMap)76 ArrayList (java.util.ArrayList)58 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 Scope (org.wso2.carbon.apimgt.core.models.Scope)41 Map (java.util.Map)39 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)39 LinkedHashSet (java.util.LinkedHashSet)32 LinkedHashMap (java.util.LinkedHashMap)29 HashSet (java.util.HashSet)26 RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)25 List (java.util.List)24 Test (org.testng.annotations.Test)23 JSONObject (org.json.simple.JSONObject)22 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)19 PreparedStatement (java.sql.PreparedStatement)17 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 SQLException (java.sql.SQLException)16 Gson (com.google.gson.Gson)15 Connection (java.sql.Connection)15