use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.
the class APIMappingUtil method fromDTOtoAPIProduct.
public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
APIProduct product = new APIProduct();
APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
APIConstants.API_PRODUCT_VERSION);
product.setID(id);
product.setUuid(dto.getId());
product.setDescription(dto.getDescription());
String context = dto.getContext();
if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
}
context = context.startsWith("/") ? context : ("/" + context);
String providerDomain = MultitenantUtils.getTenantDomain(provider);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
// Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
product.setContext(context);
context = checkAndSetVersionParam(context);
product.setContextTemplate(context);
List<String> apiProductTags = dto.getTags();
Set<String> tagsToReturn = new HashSet<>(apiProductTags);
product.addTags(tagsToReturn);
if (dto.isEnableSchemaValidation() != null) {
product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
}
product.setEnableStore(true);
if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
product.setResponseCache(APIConstants.ENABLED);
} else {
product.setResponseCache(APIConstants.DISABLED);
}
if (dto.getCacheTimeout() != null) {
product.setCacheTimeout(dto.getCacheTimeout());
} else {
product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
}
if (dto.getBusinessInformation() != null) {
product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
}
Set<Tier> apiTiers = new HashSet<>();
List<String> tiersFromDTO = dto.getPolicies();
if (dto.getVisibility() != null) {
product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
}
if (dto.getVisibleRoles() != null) {
String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
product.setVisibleRoles(visibleRoles);
}
if (dto.getVisibleTenants() != null) {
String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
product.setVisibleTenants(visibleTenants);
}
List<String> accessControlRoles = dto.getAccessControlRoles();
if (accessControlRoles == null || accessControlRoles.isEmpty()) {
product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
product.setAccessControlRoles("null");
} else {
product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
}
for (String tier : tiersFromDTO) {
apiTiers.add(new Tier(tier));
}
product.setAvailableTiers(apiTiers);
product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
product.setGatewayVendor(dto.getGatewayVendor());
if (dto.getSubscriptionAvailability() != null) {
product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
}
List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
if (additionalProperties != null) {
for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
if (property.isDisplay()) {
product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
} else {
product.addProperty(property.getName(), property.getValue());
}
}
}
if (dto.getSubscriptionAvailableTenants() != null) {
product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
}
String transports = StringUtils.join(dto.getTransport(), ',');
product.setTransports(transports);
List<APIProductResource> productResources = new ArrayList<APIProductResource>();
Set<String> verbResourceCombo = new HashSet<>();
for (ProductAPIDTO res : dto.getApis()) {
List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
}
URITemplate template = new URITemplate();
template.setHTTPVerb(resourceItem.getVerb());
template.setHttpVerbs(resourceItem.getVerb());
template.setResourceURI(resourceItem.getTarget());
template.setUriTemplate(resourceItem.getTarget());
template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
APIProductResource resource = new APIProductResource();
resource.setApiId(res.getApiId());
resource.setUriTemplate(template);
productResources.add(resource);
}
}
Set<Scope> scopes = getScopes(dto);
product.setScopes(scopes);
APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
CORSConfiguration corsConfiguration;
if (apiCorsConfigurationDTO != null) {
corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
} else {
corsConfiguration = APIUtil.getDefaultCorsConfiguration();
}
product.setCorsConfiguration(corsConfiguration);
product.setProductResources(productResources);
product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
product.setAuthorizationHeader(dto.getAuthorizationHeader());
// attach api categories to API model
setAPICategoriesToModel(dto, product, provider);
return product;
}
use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method createAuditApi.
/**
* Send API Definition to Security Audit for the first time
* @param collectionId Collection ID in which the Definition should be sent to
* @param apiToken API Token to access Security Audit
* @param apiIdentifier API Identifier object
* @param apiDefinition API Definition of API
* @param baseUrl Base URL to communicate with Security Audit
* @param isDebugEnabled Boolean whether debug is enabled
* @param organization Organization
* @return String UUID of API in Security Audit
* @throws IOException In the event of any problems in the request
* @throws APIManagementException In the event of unexpected response
* @throws ParseException In the event of any parse errors from the response
*/
private String createAuditApi(String collectionId, String apiToken, APIIdentifier apiIdentifier, String apiDefinition, String baseUrl, boolean isDebugEnabled, String organization) throws IOException, APIManagementException, ParseException {
HttpURLConnection httpConn;
OutputStream outputStream;
PrintWriter writer;
String auditUuid = null;
URL url = new URL(baseUrl);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
// indicates POST method
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty(APIConstants.HEADER_CONTENT_TYPE, APIConstants.MULTIPART_CONTENT_TYPE + APIConstants.MULTIPART_FORM_BOUNDARY);
httpConn.setRequestProperty(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
httpConn.setRequestProperty(APIConstants.HEADER_API_TOKEN, apiToken);
httpConn.setRequestProperty(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);
// Name property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"name\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiIdentifier.getApiName()).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
// Specfile property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"specfile\"; filename=\"swagger.json\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.HEADER_CONTENT_TYPE + ": " + APIConstants.APPLICATION_JSON_MEDIA_TYPE).append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiDefinition).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
// CollectionID property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"cid\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(collectionId).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY + "--").append(APIConstants.MULTIPART_LINE_FEED);
writer.close();
// Checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
if (isDebugEnabled) {
log.debug("HTTP status " + status);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder responseString = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
reader.close();
httpConn.disconnect();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
auditUuid = (String) ((JSONObject) responseJson.get(APIConstants.DESC)).get(APIConstants.ID);
ApiMgtDAO.getInstance().addAuditApiMapping(apiIdentifier, auditUuid, organization);
} else {
if (httpConn.getErrorStream() != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder responseString = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
reader.close();
httpConn.disconnect();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
String errorMessage = httpConn.getResponseMessage();
if (responseJson.containsKey("message")) {
errorMessage = (String) responseJson.get("message");
}
throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + errorMessage);
} else {
throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + httpConn.getResponseMessage());
}
}
return auditUuid;
}
use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.
the class TemplateBuilderUtil method retrieveGatewayAPIDto.
public static GatewayAPIDTO retrieveGatewayAPIDto(API api, Environment environment, String tenantDomain, APIDTO apidto, String extractedFolderPath) throws APIManagementException, XMLStreamException, APITemplateException {
List<ClientCertificateDTO> clientCertificatesDTOList = ImportUtils.retrieveClientCertificates(extractedFolderPath);
List<SoapToRestMediationDto> soapToRestInMediationDtoList = ImportUtils.retrieveSoapToRestFlowMediations(extractedFolderPath, ImportUtils.IN);
List<SoapToRestMediationDto> soapToRestOutMediationDtoList = ImportUtils.retrieveSoapToRestFlowMediations(extractedFolderPath, ImportUtils.OUT);
JSONObject originalProperties = api.getAdditionalProperties();
// add new property for entires that has a __display suffix
JSONObject modifiedProperties = getModifiedProperties(originalProperties);
api.setAdditionalProperties(modifiedProperties);
APITemplateBuilder apiTemplateBuilder = TemplateBuilderUtil.getAPITemplateBuilder(api, tenantDomain, clientCertificatesDTOList, soapToRestInMediationDtoList, soapToRestOutMediationDtoList);
GatewayAPIDTO gatewaAPIDto = createAPIGatewayDTOtoPublishAPI(environment, api, apiTemplateBuilder, tenantDomain, extractedFolderPath, apidto, clientCertificatesDTOList);
// Reset the additional properties to the original values
if (originalProperties != null) {
api.setAdditionalProperties(originalProperties);
}
return gatewaAPIDto;
}
use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.
the class RestApiUtil method handleMigrationSpecificPermissionViolations.
/**
* Handle if any cross tenant access permission violations detected. Cross tenant resources (apis/apps) can be
* retrieved only by super tenant admin user, only while a migration process(2.6.0 to 3.0.0). APIM server has to be
* started with the system property 'migrationMode=true' if a migration related exports are to be done.
*
* @param targetTenantDomain Tenant domain of which resources are requested
* @param username Logged in user name
* @throws ForbiddenException
*/
public static void handleMigrationSpecificPermissionViolations(String targetTenantDomain, String username) throws ForbiddenException {
boolean isCrossTenantAccess = !targetTenantDomain.equals(MultitenantUtils.getTenantDomain(username));
if (!isCrossTenantAccess) {
return;
}
String superAdminRole = null;
try {
superAdminRole = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminRoleName();
} catch (UserStoreException e) {
RestApiUtil.handleInternalServerError("Error in getting super admin role name", e, log);
}
// check whether logged in user is a super tenant user
String superTenantDomain = null;
try {
superTenantDomain = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getSuperTenantDomain();
} catch (UserStoreException e) {
RestApiUtil.handleInternalServerError("Error in getting the super tenant domain", e, log);
}
boolean isSuperTenantUser = RestApiCommonUtil.getLoggedInUserTenantDomain().equals(superTenantDomain);
if (!isSuperTenantUser) {
String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a super " + "tenant user";
log.error(errorMsg);
ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
throw new ForbiddenException(errorDTO);
}
// check whether the user has super tenant admin role
boolean isSuperAdminRoleNameExist = false;
try {
isSuperAdminRoleNameExist = APIUtil.isUserInRole(username, superAdminRole);
} catch (UserStoreException | APIManagementException e) {
RestApiUtil.handleInternalServerError("Error in checking whether the user has admin role", e, log);
}
if (!isSuperAdminRoleNameExist) {
String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a " + "super tenant admin";
log.error(errorMsg);
ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
throw new ForbiddenException(errorDTO);
}
}
use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.
the class SettingsMappingUtil method fromSettingstoDTO.
public SettingsDTO fromSettingstoDTO(Boolean isUserAvailable, Boolean moneatizationEnabled, boolean recommendationEnabled, boolean anonymousEnabled, String organization) throws APIManagementException {
SettingsDTO settingsDTO = new SettingsDTO();
settingsDTO.setScopes(GetScopeList());
settingsDTO.setApplicationSharingEnabled(APIUtil.isMultiGroupAppSharingEnabled());
settingsDTO.setRecommendationEnabled(recommendationEnabled);
settingsDTO.setMapExistingAuthApps(APIUtil.isMapExistingAuthAppsEnabled());
settingsDTO.setMonetizationEnabled(moneatizationEnabled);
SettingsIdentityProviderDTO identityProviderDTO = new SettingsIdentityProviderDTO();
identityProviderDTO.setExternal(APIUtil.getIdentityProviderConfig() != null);
settingsDTO.setIdentityProvider(identityProviderDTO);
settingsDTO.setIsAnonymousModeEnabled(anonymousEnabled);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
boolean enableChangePassword = Boolean.parseBoolean(config.getFirstProperty(APIConstants.ENABLE_CHANGE_PASSWORD));
settingsDTO.setIsPasswordChangeEnabled(enableChangePassword);
String username = RestApiCommonUtil.getLoggedInUsername();
String tenantDomain = MultitenantUtils.getTenantDomain(username);
int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
String userStorePasswordPattern = null;
String passwordPolicyPattern = null;
int passwordPolicyMinLength = -1;
int passwordPolicyMaxLength = -1;
try {
// Get password pattern from the UserStoreManager configuration
RealmConfiguration realmConfiguration = null;
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
UserStoreManager userStoreManager = null;
userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
realmConfiguration = userStoreManager.getRealmConfiguration();
}
if (realmConfiguration != null) {
String passwordJavaRegEx = realmConfiguration.getUserStoreProperty(APIConstants.PASSWORD_JAVA_REGEX_PROPERTY);
if (passwordJavaRegEx != null && !passwordJavaRegEx.trim().isEmpty()) {
userStorePasswordPattern = passwordJavaRegEx;
}
}
// Get password pattern from the Password policy
Property passwordPolicyEnabledProperty = FrameworkUtils.getResidentIdpConfiguration(APIConstants.IS_PASSWORD_POLICY_ENABLED_PROPERTY, tenantDomain);
boolean isPasswordPolicyEnabled = Boolean.parseBoolean(passwordPolicyEnabledProperty.getValue());
if (isPasswordPolicyEnabled) {
passwordPolicyPattern = FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_PATTERN_PROPERTY, tenantDomain).getValue();
passwordPolicyMinLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MIN_LENGTH_PROPERTY, tenantDomain).getValue());
passwordPolicyMaxLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MAX_LENGTH_PROPERTY, tenantDomain).getValue());
}
} catch (UserStoreException e) {
String errorMessage = "Error occurred in getting userRealm for the tenant: " + tenantId;
throw new APIManagementException(errorMessage, e);
} catch (FrameworkException e) {
String errorMessage = "Error occurred in getting Resident Idp Configurations for tenant: " + tenantId;
throw new APIManagementException(errorMessage, e);
}
settingsDTO.setUserStorePasswordPattern(userStorePasswordPattern);
settingsDTO.setPasswordPolicyPattern(passwordPolicyPattern);
settingsDTO.setPasswordPolicyMinLength(passwordPolicyMinLength);
settingsDTO.setPasswordPolicyMaxLength(passwordPolicyMaxLength);
if (isUserAvailable) {
settingsDTO.setGrantTypes(APIUtil.getGrantTypes());
Map<String, Environment> environments = APIUtil.getEnvironments(organization);
if (environments.isEmpty()) {
settingsDTO.apiGatewayEndpoint("http://localhost:8280, https://localhost:8243");
} else {
for (Map.Entry<String, Environment> entry : environments.entrySet()) {
Environment environment = environments.get(entry.getKey());
if (environment.isDefault()) {
settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
break;
}
}
if (settingsDTO.getApiGatewayEndpoint() == null) {
Map.Entry<String, Environment> entry = environments.entrySet().iterator().next();
Environment environment = environments.get(entry.getKey());
settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
}
}
}
return settingsDTO;
}
Aggregations