use of io.swagger.v3.oas.models.security.SecurityScheme.In in project carbon-apimgt by wso2.
the class OAS3Parser method getOASDefinitionForPublisher.
/**
* Update OAS definition for API Publisher
*
* @param api API
* @param oasDefinition
* @return OAS definition
* @throws APIManagementException throws if an error occurred
*/
@Override
public String getOASDefinitionForPublisher(API api, String oasDefinition) throws APIManagementException {
OpenAPI openAPI = getOpenAPI(oasDefinition);
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());
}
// setting scopes id if it is null
// https://github.com/swagger-api/swagger-parser/issues/1202
OAuthFlow oAuthFlow = securityScheme.getFlows().getImplicit();
if (oAuthFlow == null) {
oAuthFlow = new OAuthFlow();
securityScheme.getFlows().setImplicit(oAuthFlow);
}
if (oAuthFlow.getScopes() == null) {
oAuthFlow.setScopes(new Scopes());
}
oAuthFlow.setAuthorizationUrl(OPENAPI_DEFAULT_AUTHORIZATION_URL);
if (api.getAuthorizationHeader() != null) {
openAPI.addExtension(APIConstants.X_WSO2_AUTH_HEADER, api.getAuthorizationHeader());
}
if (api.getApiLevelPolicy() != null) {
openAPI.addExtension(APIConstants.X_THROTTLING_TIER, api.getApiLevelPolicy());
}
openAPI.addExtension(APIConstants.X_WSO2_CORS, api.getCorsConfiguration());
Object prodEndpointObj = OASParserUtil.generateOASConfigForEndpoints(api, true);
if (prodEndpointObj != null) {
openAPI.addExtension(APIConstants.X_WSO2_PRODUCTION_ENDPOINTS, prodEndpointObj);
}
Object sandEndpointObj = OASParserUtil.generateOASConfigForEndpoints(api, false);
if (sandEndpointObj != null) {
openAPI.addExtension(APIConstants.X_WSO2_SANDBOX_ENDPOINTS, sandEndpointObj);
}
openAPI.addExtension(APIConstants.X_WSO2_BASEPATH, api.getContext());
if (api.getTransports() != null) {
openAPI.addExtension(APIConstants.X_WSO2_TRANSPORTS, api.getTransports().split(","));
}
String apiSecurity = api.getApiSecurity();
// set mutual ssl extension if enabled
if (apiSecurity != null) {
List<String> securityList = Arrays.asList(apiSecurity.split(","));
if (securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL)) {
String mutualSSLOptional = !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY) ? APIConstants.OPTIONAL : APIConstants.MANDATORY;
openAPI.addExtension(APIConstants.X_WSO2_MUTUAL_SSL, mutualSSLOptional);
}
}
// This app security is should given in resource level,
// otherwise the default oauth2 scheme defined at each resouce level will override application securities
JsonNode appSecurityExtension = OASParserUtil.getAppSecurity(apiSecurity);
for (String pathKey : openAPI.getPaths().keySet()) {
PathItem pathItem = openAPI.getPaths().get(pathKey);
for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) {
Operation operation = entry.getValue();
operation.addExtension(APIConstants.X_WSO2_APP_SECURITY, appSecurityExtension);
}
}
openAPI.addExtension(APIConstants.X_WSO2_RESPONSE_CACHE, OASParserUtil.getResponseCacheConfig(api.getResponseCache(), api.getCacheTimeout()));
return Json.pretty(openAPI);
}
use of io.swagger.v3.oas.models.security.SecurityScheme.In in project carbon-apimgt by wso2.
the class OAS3Parser method processDisableSecurityExtension.
/**
* This method will extractX-WSO2-disable-security extension provided in API level
* by mgw and inject that extension to all resources in OAS file
*
* @param swaggerContent String
* @return String
* @throws APIManagementException
*/
@Override
public String processDisableSecurityExtension(String swaggerContent) throws APIManagementException {
OpenAPI openAPI = getOpenAPI(swaggerContent);
Map<String, Object> apiExtensions = openAPI.getExtensions();
if (apiExtensions == null) {
return swaggerContent;
}
// Check Disable Security is enabled in API level
boolean apiLevelDisableSecurity = OASParserUtil.getDisableSecurity(apiExtensions);
Paths paths = openAPI.getPaths();
for (String pathKey : paths.keySet()) {
Map<PathItem.HttpMethod, Operation> operationsMap = paths.get(pathKey).readOperationsMap();
for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) {
Operation operation = entry.getValue();
Map<String, Object> resourceExtensions = operation.getExtensions();
boolean extensionsAreEmpty = false;
if (apiLevelDisableSecurity) {
if (resourceExtensions == null) {
resourceExtensions = new HashMap<>();
extensionsAreEmpty = true;
}
resourceExtensions.put(APIConstants.SWAGGER_X_AUTH_TYPE, "None");
if (extensionsAreEmpty) {
operation.setExtensions(resourceExtensions);
}
} else if (resourceExtensions != null && resourceExtensions.containsKey(APIConstants.X_WSO2_DISABLE_SECURITY)) {
// Check Disable Security is enabled in resource level
boolean resourceLevelDisableSecurity = Boolean.parseBoolean(String.valueOf(resourceExtensions.get(APIConstants.X_WSO2_DISABLE_SECURITY)));
if (resourceLevelDisableSecurity) {
resourceExtensions.put(APIConstants.SWAGGER_X_AUTH_TYPE, "None");
}
}
}
}
return Json.pretty(openAPI);
}
use of io.swagger.v3.oas.models.security.SecurityScheme.In in project carbon-apimgt by wso2.
the class OAS3Parser method injectMgwThrottlingExtensionsToDefault.
/**
* This method returns openAPI definition which replaced X-WSO2-throttling-tier extension comes from
* mgw with X-throttling-tier extensions in openAPI file(openAPI version 3)
*
* @param swaggerContent String
* @return String
* @throws APIManagementException
*/
@Override
public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException {
OpenAPI openAPI = getOpenAPI(swaggerContent);
Paths paths = openAPI.getPaths();
for (String pathKey : paths.keySet()) {
Map<PathItem.HttpMethod, Operation> operationsMap = paths.get(pathKey).readOperationsMap();
for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) {
Operation operation = entry.getValue();
Map<String, Object> extensions = operation.getExtensions();
if (extensions != null && extensions.containsKey(APIConstants.X_WSO2_THROTTLING_TIER)) {
Object tier = extensions.get(APIConstants.X_WSO2_THROTTLING_TIER);
extensions.remove(APIConstants.X_WSO2_THROTTLING_TIER);
extensions.put(APIConstants.SWAGGER_X_THROTTLING_TIER, tier);
}
}
}
return Json.pretty(openAPI);
}
use of io.swagger.v3.oas.models.security.SecurityScheme.In in project carbon-apimgt by wso2.
the class OAS3Parser method generateExample.
/**
* This method generates Sample/Mock payloads for Open API Specification (3.0) definitions
*
* @param apiDefinition API Definition
* @return swagger Json
*/
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException {
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
log.debug("Errors found when parsing OAS definition");
}
OpenAPI swagger = parseAttemptForV3.getOpenAPI();
// return map
Map<String, Object> returnMap = new HashMap<>();
// List for APIResMedPolicyList
List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
int minResponseCode = 0;
int responseCode = 0;
String path = entry.getKey();
Map<String, Schema> definitions = swagger.getComponents().getSchemas();
// operation map to get verb
Map<PathItem.HttpMethod, Operation> operationMap = entry.getValue().readOperationsMap();
List<Operation> operations = swagger.getPaths().get(path).readOperations();
for (int i = 0, operationsSize = operations.size(); i < operationsSize; i++) {
Operation op = operations.get(i);
// initializing apiResourceMediationPolicyObject
APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
// setting path for apiResourceMediationPolicyObject
apiResourceMediationPolicyObject.setPath(path);
ArrayList<Integer> responseCodes = new ArrayList<Integer>();
// for each HTTP method get the verb
StringBuilder genCode = new StringBuilder();
boolean hasJsonPayload = false;
boolean hasXmlPayload = false;
// for setting only one initializing if condition per response code
boolean respCodeInitialized = false;
Object[] operationsArray = operationMap.entrySet().toArray();
if (operationsArray.length > i) {
Map.Entry<PathItem.HttpMethod, Operation> operationEntry = (Map.Entry<PathItem.HttpMethod, Operation>) operationsArray[i];
apiResourceMediationPolicyObject.setVerb(String.valueOf(operationEntry.getKey()));
} else {
throw new APIManagementException("Cannot find the HTTP method for the API Resource Mediation Policy");
}
for (String responseEntry : op.getResponses().keySet()) {
if (!responseEntry.equals("default")) {
responseCode = Integer.parseInt(responseEntry);
responseCodes.add(responseCode);
minResponseCode = Collections.min(responseCodes);
}
Content content = op.getResponses().get(responseEntry).getContent();
if (content != null) {
MediaType applicationJson = content.get(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
MediaType applicationXml = content.get(APIConstants.APPLICATION_XML_MEDIA_TYPE);
if (applicationJson != null) {
Schema jsonSchema = applicationJson.getSchema();
if (jsonSchema != null) {
String jsonExample = getJsonExample(jsonSchema, definitions);
genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
respCodeInitialized = true;
hasJsonPayload = true;
}
}
if (applicationXml != null) {
Schema xmlSchema = applicationXml.getSchema();
if (xmlSchema != null) {
String xmlExample = getXmlExample(xmlSchema, definitions);
genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
hasXmlPayload = true;
}
}
} else {
setDefaultGeneratedResponse(genCode, responseEntry);
hasJsonPayload = true;
hasXmlPayload = true;
}
}
// inserts minimum response code and mock payload variables to static script
String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
// gets response section string depending on availability of json/xml payloads
String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
String finalScript = finalGenCode + responseConditions;
apiResourceMediationPolicyObject.setContent(finalScript);
// sets script to each resource in the swagger
op.addExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
}
checkAndSetEmptyScope(swagger);
returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
}
return returnMap;
}
use of io.swagger.v3.oas.models.security.SecurityScheme.In in project carbon-apimgt by wso2.
the class OASParserUtil method extractAndValidateOpenAPIArchive.
/**
* Extract the archive file and validates the openAPI definition
*
* @param inputStream file as input stream
* @param returnContent whether to return the content of the definition in the response DTO
* @return APIDefinitionValidationResponse
* @throws APIManagementException if error occurred while parsing definition
*/
public static APIDefinitionValidationResponse extractAndValidateOpenAPIArchive(InputStream inputStream, boolean returnContent) throws APIManagementException {
String path = System.getProperty(APIConstants.JAVA_IO_TMPDIR) + File.separator + APIConstants.OPENAPI_ARCHIVES_TEMP_FOLDER + File.separator + UUID.randomUUID().toString();
String archivePath = path + File.separator + APIConstants.OPENAPI_ARCHIVE_ZIP_FILE;
String extractedLocation = APIFileUtil.extractUploadedArchive(inputStream, APIConstants.OPENAPI_EXTRACTED_DIRECTORY, archivePath, path);
File[] listOfFiles = new File(extractedLocation).listFiles();
File archiveDirectory = null;
if (listOfFiles != null) {
if (listOfFiles.length > 1) {
throw new APIManagementException("Swagger Definitions should be placed under one root folder.");
}
for (File file : listOfFiles) {
if (file.isDirectory()) {
archiveDirectory = file.getAbsoluteFile();
break;
}
}
}
// If it is a single swagger file without remote references it can be imported directly, without zipping.
if (archiveDirectory == null) {
throw new APIManagementException("Could not find an archive in the given ZIP file.");
}
File masterSwagger = checkMasterSwagger(archiveDirectory);
String content;
try {
InputStream masterInputStream = new FileInputStream(masterSwagger);
content = IOUtils.toString(masterInputStream, APIConstants.DigestAuthConstants.CHARSET);
} catch (IOException e) {
throw new APIManagementException("Error reading master swagger file" + e);
}
String openAPIContent = "";
SwaggerVersion version;
version = getSwaggerVersion(content);
String filePath = masterSwagger.getAbsolutePath();
if (SwaggerVersion.OPEN_API.equals(version)) {
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
OpenAPI openAPI = openAPIV3Parser.read(filePath, null, options);
openAPIContent = Json.pretty(openAPI);
} else if (SwaggerVersion.SWAGGER.equals(version)) {
SwaggerParser parser = new SwaggerParser();
Swagger swagger = parser.read(filePath, null, true);
try {
openAPIContent = Yaml.pretty().writeValueAsString(swagger);
} catch (IOException e) {
throw new APIManagementException("Error in converting swagger to openAPI content. " + e);
}
}
APIDefinitionValidationResponse apiDefinitionValidationResponse;
apiDefinitionValidationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
return apiDefinitionValidationResponse;
}
Aggregations