use of org.wso2.carbon.apimgt.api.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAuditReportOfAPI.
/**
* Method to retrieve Security Audit Report
* @param apiId API ID of the API
* @param accept Accept header string
* @param messageContext Message Context string
* @return Response object of Security Audit
*/
@Override
public Response getAuditReportOfAPI(String apiId, String accept, MessageContext messageContext) {
boolean isDebugEnabled = log.isDebugEnabled();
try {
String username = RestApiCommonUtil.getLoggedInUsername();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
API api = apiProvider.getAPIbyUUID(apiId, organization);
APIIdentifier apiIdentifier = api.getId();
String apiDefinition = apiProvider.getOpenAPIDefinition(apiIdentifier, organization);
// Get configuration file, retrieve API token and collection id
JSONObject securityAuditPropertyObject = apiProvider.getSecurityAuditAttributesFromConfig(username);
String apiToken = (String) securityAuditPropertyObject.get("apiToken");
String collectionId = (String) securityAuditPropertyObject.get("collectionId");
String baseUrl = (String) securityAuditPropertyObject.get("baseUrl");
if (baseUrl == null) {
baseUrl = APIConstants.BASE_AUDIT_URL;
}
// Retrieve the uuid from the database
String auditUuid = ApiMgtDAO.getInstance().getAuditApiId(api.getUuid());
if (auditUuid != null) {
updateAuditApi(apiDefinition, apiToken, auditUuid, baseUrl, isDebugEnabled);
} else {
auditUuid = createAuditApi(collectionId, apiToken, apiIdentifier, apiDefinition, baseUrl, isDebugEnabled, organization);
}
// Logic for the HTTP request
String getUrl = baseUrl + "/" + auditUuid + APIConstants.ASSESSMENT_REPORT;
URL getReportUrl = new URL(getUrl);
try (CloseableHttpClient getHttpClient = (CloseableHttpClient) APIUtil.getHttpClient(getReportUrl.getPort(), getReportUrl.getProtocol())) {
HttpGet httpGet = new HttpGet(getUrl);
// Set the header properties of the request
httpGet.setHeader(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
httpGet.setHeader(APIConstants.HEADER_API_TOKEN, apiToken);
httpGet.setHeader(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
// Code block for the processing of the response
try (CloseableHttpResponse response = getHttpClient.execute(httpGet)) {
if (isDebugEnabled) {
log.debug("HTTP status " + response.getStatusLine().getStatusCode());
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder responseString = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
reader.close();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
String report = responseJson.get(APIConstants.DATA).toString();
String grade = (String) ((JSONObject) ((JSONObject) responseJson.get(APIConstants.ATTR)).get(APIConstants.DATA)).get(APIConstants.GRADE);
Integer numErrors = Integer.valueOf((String) ((JSONObject) ((JSONObject) responseJson.get(APIConstants.ATTR)).get(APIConstants.DATA)).get(APIConstants.NUM_ERRORS));
String decodedReport = new String(Base64Utils.decode(report), StandardCharsets.UTF_8);
AuditReportDTO auditReportDTO = new AuditReportDTO();
auditReportDTO.setReport(decodedReport);
auditReportDTO.setGrade(grade);
auditReportDTO.setNumErrors(numErrors);
auditReportDTO.setExternalApiId(auditUuid);
return Response.ok().entity(auditReportDTO).build();
}
}
}
} catch (IOException e) {
RestApiUtil.handleInternalServerError("Error occurred while getting " + "HttpClient instance", e, log);
} catch (ParseException e) {
RestApiUtil.handleInternalServerError("API Definition String " + "could not be parsed into JSONObject.", e, log);
} catch (APIManagementException e) {
String errorMessage = "Error while Auditing API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIDefinition in project carbon-apimgt by wso2.
the class APIMappingUtil method getScopesFromSwagger.
/**
* Extract scopes from the swagger.
*
* @param swagger swagger document
* @return list of scopes
* @throws APIManagementException throw if parsing exception occur
*/
private static List<ScopeDTO> getScopesFromSwagger(String swagger) throws APIManagementException {
APIDefinition apiDefinition = OASParserUtil.getOASParser(swagger);
Set<Scope> scopes = apiDefinition.getScopes(swagger);
List<ScopeDTO> scopeDTOS = new ArrayList<>();
for (Scope aScope : scopes) {
ScopeDTO scopeDTO = new ScopeDTO();
scopeDTO.setName(aScope.getKey());
scopeDTO.setDisplayName(aScope.getName());
scopeDTO.setDescription(aScope.getDescription());
String roles = aScope.getRoles();
if (roles == null || roles.isEmpty()) {
scopeDTO.setBindings(Collections.emptyList());
} else {
scopeDTO.setBindings(Arrays.asList((roles).split(",")));
}
scopeDTOS.add(scopeDTO);
}
return scopeDTOS;
}
use of org.wso2.carbon.apimgt.api.APIDefinition in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateApi.
/**
* Update an API.
*
* @param originalAPI Existing API
* @param apiDtoToUpdate New API DTO to update
* @param apiProvider API Provider
* @param tokenScopes Scopes of the token
* @throws ParseException If an error occurs while parsing the endpoint configuration
* @throws CryptoException If an error occurs while encrypting the secret key of API
* @throws APIManagementException If an error occurs while updating the API
* @throws FaultGatewaysException If an error occurs while updating manage of an existing API
*/
public static API updateApi(API originalAPI, APIDTO apiDtoToUpdate, APIProvider apiProvider, String[] tokenScopes) throws ParseException, CryptoException, APIManagementException, FaultGatewaysException {
APIIdentifier apiIdentifier = originalAPI.getId();
// Validate if the USER_REST_API_SCOPES is not set in WebAppAuthenticator when scopes are validated
if (tokenScopes == null) {
throw new APIManagementException("Error occurred while updating the API " + originalAPI.getUUID() + " as the token information hasn't been correctly set internally", ExceptionCodes.TOKEN_SCOPES_NOT_SET);
}
boolean isGraphql = originalAPI.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(originalAPI.getType());
boolean isAsyncAPI = originalAPI.getType() != null && (APIConstants.APITransportType.WS.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.SSE.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.ASYNC.toString().equals(originalAPI.getType()));
Scope[] apiDtoClassAnnotatedScopes = APIDTO.class.getAnnotationsByType(Scope.class);
boolean hasClassLevelScope = checkClassScopeAnnotation(apiDtoClassAnnotatedScopes, tokenScopes);
JSONParser parser = new JSONParser();
String oldEndpointConfigString = originalAPI.getEndpointConfig();
JSONObject oldEndpointConfig = null;
if (StringUtils.isNotBlank(oldEndpointConfigString)) {
oldEndpointConfig = (JSONObject) parser.parse(oldEndpointConfigString);
}
String oldProductionApiSecret = null;
String oldSandboxApiSecret = null;
if (oldEndpointConfig != null) {
if ((oldEndpointConfig.containsKey(APIConstants.ENDPOINT_SECURITY))) {
JSONObject oldEndpointSecurity = (JSONObject) oldEndpointConfig.get(APIConstants.ENDPOINT_SECURITY);
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION)) {
JSONObject oldEndpointSecurityProduction = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
if (oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldProductionApiSecret = oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX)) {
JSONObject oldEndpointSecuritySandbox = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
if (oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldSandboxApiSecret = oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
}
}
Map endpointConfig = (Map) apiDtoToUpdate.getEndpointConfig();
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
// OAuth 2.0 backend protection: API Key and API Secret encryption
encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, oldProductionApiSecret, oldSandboxApiSecret, apiDtoToUpdate);
// AWS Lambda: secret key encryption while updating the API
if (apiDtoToUpdate.getEndpointConfig() != null) {
if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
if (!StringUtils.isEmpty(secretKey)) {
if (!APIConstants.AWS_SECRET_KEY.equals(secretKey)) {
String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
} else {
JSONParser jsonParser = new JSONParser();
JSONObject originalEndpointConfig = (JSONObject) jsonParser.parse(originalAPI.getEndpointConfig());
String encryptedSecretKey = (String) originalEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
}
}
}
}
if (!hasClassLevelScope) {
// Validate per-field scopes
apiDtoToUpdate = getFieldOverriddenAPIDTO(apiDtoToUpdate, originalAPI, tokenScopes);
}
// API Name change not allowed if OnPrem
if (APIUtil.isOnPremResolver()) {
apiDtoToUpdate.setName(apiIdentifier.getApiName());
}
apiDtoToUpdate.setVersion(apiIdentifier.getVersion());
apiDtoToUpdate.setProvider(apiIdentifier.getProviderName());
apiDtoToUpdate.setContext(originalAPI.getContextTemplate());
apiDtoToUpdate.setLifeCycleStatus(originalAPI.getStatus());
apiDtoToUpdate.setType(APIDTO.TypeEnum.fromValue(originalAPI.getType()));
List<APIResource> removedProductResources = getRemovedProductResources(apiDtoToUpdate, originalAPI);
if (!removedProductResources.isEmpty()) {
throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, originalAPI.getId().getApiName(), originalAPI.getId().getVersion()));
}
// Validate API Security
List<String> apiSecurity = apiDtoToUpdate.getSecurityScheme();
// validation for tiers
List<String> tiersFromDTO = apiDtoToUpdate.getPolicies();
String originalStatus = originalAPI.getStatus();
if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
if ((tiersFromDTO == null || tiersFromDTO.isEmpty() && !(APIConstants.CREATED.equals(originalStatus) || APIConstants.PROTOTYPED.equals(originalStatus))) && !apiDtoToUpdate.getAdvertiseInfo().isAdvertised()) {
throw new APIManagementException("A tier should be defined if the API is not in CREATED or PROTOTYPED state", ExceptionCodes.TIER_CANNOT_BE_NULL);
}
}
if (tiersFromDTO != null && !tiersFromDTO.isEmpty()) {
// check whether the added API's tiers are all valid
Set<Tier> definedTiers = apiProvider.getTiers();
List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
if (invalidTiers.size() > 0) {
throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
}
}
if (apiDtoToUpdate.getAccessControlRoles() != null) {
String errorMessage = validateUserRoles(apiDtoToUpdate.getAccessControlRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getVisibleRoles() != null) {
String errorMessage = validateRoles(apiDtoToUpdate.getVisibleRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getAdditionalProperties() != null) {
String errorMessage = validateAdditionalProperties(apiDtoToUpdate.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiDtoToUpdate.getName(), apiDtoToUpdate.getVersion()));
}
}
// Validate if resources are empty
if (apiDtoToUpdate.getOperations() == null || apiDtoToUpdate.getOperations().isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
API apiToUpdate = APIMappingUtil.fromDTOtoAPI(apiDtoToUpdate, apiIdentifier.getProviderName());
if (APIConstants.PUBLIC_STORE_VISIBILITY.equals(apiToUpdate.getVisibility())) {
apiToUpdate.setVisibleRoles(StringUtils.EMPTY);
}
apiToUpdate.setUUID(originalAPI.getUUID());
apiToUpdate.setOrganization(originalAPI.getOrganization());
validateScopes(apiToUpdate);
apiToUpdate.setThumbnailUrl(originalAPI.getThumbnailUrl());
if (apiDtoToUpdate.getKeyManagers() instanceof List) {
apiToUpdate.setKeyManagers((List<String>) apiDtoToUpdate.getKeyManagers());
} else {
apiToUpdate.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
}
if (!isAsyncAPI) {
String oldDefinition = apiProvider.getOpenAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
APIDefinition apiDefinition = OASParserUtil.getOASParser(oldDefinition);
SwaggerData swaggerData = new SwaggerData(apiToUpdate);
String newDefinition = apiDefinition.generateAPIDefinition(swaggerData, oldDefinition);
apiProvider.saveSwaggerDefinition(apiToUpdate, newDefinition, originalAPI.getOrganization());
if (!isGraphql) {
Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(newDefinition);
// set operation policies from the original API Payload
Set<URITemplate> uriTemplatesFromPayload = apiToUpdate.getUriTemplates();
Map<String, List<OperationPolicy>> operationPoliciesPerURITemplate = new HashMap<>();
for (URITemplate uriTemplate : uriTemplatesFromPayload) {
if (!uriTemplate.getOperationPolicies().isEmpty()) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
operationPoliciesPerURITemplate.put(key, uriTemplate.getOperationPolicies());
}
}
for (URITemplate uriTemplate : uriTemplates) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
if (operationPoliciesPerURITemplate.containsKey(key)) {
uriTemplate.setOperationPolicies(operationPoliciesPerURITemplate.get(key));
}
}
apiToUpdate.setUriTemplates(uriTemplates);
}
} else {
String oldDefinition = apiProvider.getAsyncAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
AsyncApiParser asyncApiParser = new AsyncApiParser();
String updateAsyncAPIDefinition = asyncApiParser.updateAsyncAPIDefinition(oldDefinition, apiToUpdate);
apiProvider.saveAsyncApiDefinition(originalAPI, updateAsyncAPIDefinition);
}
apiToUpdate.setWsdlUrl(apiDtoToUpdate.getWsdlUrl());
// validate API categories
List<APICategory> apiCategories = apiToUpdate.getApiCategories();
List<APICategory> apiCategoriesList = new ArrayList<>();
for (APICategory category : apiCategories) {
category.setOrganization(originalAPI.getOrganization());
apiCategoriesList.add(category);
}
apiToUpdate.setApiCategories(apiCategoriesList);
if (apiCategoriesList.size() > 0) {
if (!APIUtil.validateAPICategories(apiCategoriesList, originalAPI.getOrganization())) {
throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
}
}
apiToUpdate.setOrganization(originalAPI.getOrganization());
apiProvider.updateAPI(apiToUpdate, originalAPI);
return apiProvider.getAPIbyUUID(originalAPI.getUuid(), originalAPI.getOrganization());
// TODO use returend api
}
use of org.wso2.carbon.apimgt.api.APIDefinition in project carbon-apimgt by wso2.
the class APIMappingUtil method fromAPItoDTO.
public static APIDTO fromAPItoDTO(APIProduct model, String organization) throws APIManagementException {
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
APIDTO dto = new APIDTO();
dto.setName(model.getId().getName());
dto.setVersion(model.getId().getVersion());
String providerName = model.getId().getProviderName();
dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
dto.setId(model.getUuid());
dto.setContext(model.getContext());
dto.setDescription(model.getDescription());
dto.setLifeCycleStatus(model.getState());
dto.setType(model.getType());
dto.setAvgRating(String.valueOf(model.getRating()));
/* todo: created and last updated times
if (null != model.getLastUpdated()) {
Date lastUpdateDate = model.getLastUpdated();
Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
dto.setLastUpdatedTime(String.valueOf(timeStamp));
}
String createdTimeStamp = model.getCreatedTime();
if (null != createdTimeStamp) {
Date date = new Date(Long.valueOf(createdTimeStamp));
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String dateFormatted = formatter.format(date);
dto.setCreatedTime(dateFormatted);
} */
String apiDefinition = null;
if (model.isAsync()) {
// for asyncAPI retrieve asyncapi.yml specification
apiDefinition = apiConsumer.getAsyncAPIDefinition(model.getUuid(), organization);
} else {
// retrieve open API definition
if (model.getDefinition() != null) {
apiDefinition = model.getDefinition();
} else {
apiDefinition = apiConsumer.getOpenAPIDefinition(model.getUuid(), organization);
}
}
dto.setApiDefinition(apiDefinition);
Set<String> apiTags = model.getTags();
List<String> tagsToReturn = new ArrayList<>();
tagsToReturn.addAll(apiTags);
dto.setTags(tagsToReturn);
Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
List<APITiersDTO> tiersToReturn = new ArrayList<>();
// set the monetization status of this API (enabled or disabled)
APIMonetizationInfoDTO monetizationInfoDTO = new APIMonetizationInfoDTO();
monetizationInfoDTO.enabled(model.getMonetizationStatus());
dto.setMonetization(monetizationInfoDTO);
for (org.wso2.carbon.apimgt.api.model.Tier currentTier : apiTiers) {
APITiersDTO apiTiersDTO = new APITiersDTO();
apiTiersDTO.setTierName(currentTier.getName());
apiTiersDTO.setTierPlan(currentTier.getTierPlan());
// monetization attributes are applicable only for commercial tiers
if (APIConstants.COMMERCIAL_TIER_PLAN.equalsIgnoreCase(currentTier.getTierPlan())) {
APIMonetizationAttributesDTO monetizationAttributesDTO = new APIMonetizationAttributesDTO();
if (MapUtils.isNotEmpty(currentTier.getMonetizationAttributes())) {
Map<String, String> monetizationAttributes = currentTier.getMonetizationAttributes();
// check the billing plan (fixed or price per request)
if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE))) {
monetizationAttributesDTO.setFixedPrice(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE));
} else if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST))) {
monetizationAttributesDTO.setPricePerRequest(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST));
}
monetizationAttributesDTO.setCurrencyType(monetizationAttributes.get(APIConstants.Monetization.CURRENCY) != null ? monetizationAttributes.get(APIConstants.Monetization.CURRENCY) : StringUtils.EMPTY);
monetizationAttributesDTO.setBillingCycle(monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) != null ? monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) : StringUtils.EMPTY);
}
apiTiersDTO.setMonetizationAttributes(monetizationAttributesDTO);
}
tiersToReturn.add(apiTiersDTO);
}
dto.setTiers(tiersToReturn);
List<APIOperationsDTO> operationList = new ArrayList<>();
Map<String, ScopeInfoDTO> uniqueScopes = new HashMap<>();
for (APIProductResource productResource : model.getProductResources()) {
URITemplate uriTemplate = productResource.getUriTemplate();
APIOperationsDTO operation = new APIOperationsDTO();
operation.setTarget(uriTemplate.getUriTemplate());
operation.setVerb(uriTemplate.getHTTPVerb());
operationList.add(operation);
List<Scope> scopes = uriTemplate.retrieveAllScopes();
for (Scope scope : scopes) {
if (!uniqueScopes.containsKey(scope.getKey())) {
ScopeInfoDTO scopeInfoDTO = new ScopeInfoDTO().key(scope.getKey()).name(scope.getName()).description(scope.getDescription());
if (StringUtils.isNotBlank(scope.getRoles())) {
scopeInfoDTO.roles(Arrays.asList(scope.getRoles().trim().split(",")));
}
uniqueScopes.put(scope.getKey(), scopeInfoDTO);
}
}
}
dto.setOperations(operationList);
dto.setScopes(new ArrayList<>(uniqueScopes.values()));
dto.setTransport(Arrays.asList(model.getTransports().split(",")));
APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
dto.setBusinessInformation(apiBusinessInformationDTO);
if (!StringUtils.isBlank(model.getThumbnailUrl())) {
dto.setHasThumbnail(true);
}
if (model.getAdditionalProperties() != null) {
JSONObject additionalProperties = model.getAdditionalProperties();
List<APIAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
for (Object propertyKey : additionalProperties.keySet()) {
APIAdditionalPropertiesDTO additionalPropertiesDTO = new APIAdditionalPropertiesDTO();
String key = (String) propertyKey;
int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
if (index > 0) {
additionalPropertiesDTO.setName(key.substring(0, index));
additionalPropertiesDTO.setDisplay(true);
additionalPropertiesList.add(additionalPropertiesDTO);
}
}
dto.setAdditionalProperties(additionalPropertiesList);
}
if (model.getEnvironments() != null) {
List<String> environmentListToReturn = new ArrayList<>(model.getEnvironments());
dto.setEnvironmentList(environmentListToReturn);
}
dto.setAuthorizationHeader(model.getAuthorizationHeader());
if (model.getApiSecurity() != null) {
dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
}
// Since same APIInfoDTO is used for APIProduct in StoreUI set default AdvertisedInfo to the DTO
AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
advertiseInfoDTO.setAdvertised(false);
dto.setAdvertiseInfo(advertiseInfoDTO);
String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
String subscriptionAvailability = model.getSubscriptionAvailability();
String subscriptionAllowedTenants = model.getSubscriptionAvailableTenants();
dto.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
return dto;
}
use of org.wso2.carbon.apimgt.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];
}
Aggregations