use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class PreAuthenticationInterceptor method handleMessage.
@Override
@MethodStats
public void handleMessage(Message message) throws Fault {
String path = (String) message.get(Message.PATH_INFO);
if (path.contains(APIConstants.RestApiConstants.REST_API_OLD_VERSION)) {
path = path.replace("/" + APIConstants.RestApiConstants.REST_API_OLD_VERSION, "");
}
String httpMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
Dictionary<URITemplate, List<String>> allowedResourcePathsMap;
// If Authorization headers are present anonymous URI check will be skipped
ArrayList authHeaders = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS))).get(RestApiConstants.AUTH_HEADER_NAME);
if (authHeaders != null)
return;
// Check if the accessing URI is allowed and then authorization is skipped
try {
allowedResourcePathsMap = RestApiUtil.getAllowedURIsToMethodsMap();
Enumeration<URITemplate> uriTemplateSet = allowedResourcePathsMap.keys();
ArrayList requestedTenantDomain = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS))).get(RestApiConstants.HEADER_X_WSO2_TENANT);
String tenantDomain = null;
if (requestedTenantDomain != null) {
tenantDomain = RestApiUtil.getRequestedTenantDomain(requestedTenantDomain.get(0).toString());
}
if (StringUtils.isEmpty(tenantDomain)) {
tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
}
while (uriTemplateSet.hasMoreElements()) {
URITemplate uriTemplate = uriTemplateSet.nextElement();
if (uriTemplate.matches(path, new HashMap<String, String>())) {
List<String> allowedVerbs = allowedResourcePathsMap.get(uriTemplate);
if (allowedVerbs.contains(httpMethod)) {
if (StringUtils.startsWith((String) message.get(Message.BASE_PATH), "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT)) {
// Authentication will be skipped for /swagger.yaml, /settings, /tenants resources of
// the devportal REST API
boolean doSkipAuthentication = StringUtils.equals(path, "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT + RestApiConstants.RESOURCE_PATH_SWAGGER) || StringUtils.equals(path, "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT + RestApiConstants.REST_API_DEVELOPER_PORTAL_RESOURCE_PATH_SETTINGS) || StringUtils.equals(path, "/" + RestApiConstants.REST_API_DEVELOPER_PORTAL_CONTEXT + RestApiConstants.REST_API_DEVELOPER_PORTAL_RESOURCE_PATH_TENANTS);
if (!doSkipAuthentication) {
message.put(RestApiConstants.AUTHENTICATION_REQUIRED, !RestApiUtil.isDevPortalAnonymousEnabled(tenantDomain));
} else {
message.put(RestApiConstants.AUTHENTICATION_REQUIRED, false);
}
} else {
message.put(RestApiConstants.AUTHENTICATION_REQUIRED, false);
}
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
return;
}
}
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Unable to retrieve/process allowed URIs for REST API", e, logger);
}
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class BasicAuthenticationInterceptor method validateUserRolesWithRESTAPIScopes.
/**
* This method validates the user roles against the roles of the REST API scopes defined for the current resource.
*
* @param resourceScopeList Scope list of the current resource
* @param restAPIScopes RESTAPIScopes mapping for the current tenant
* @param userRoles Role list for the user
* @param username Username
* @param path Path Info
* @param verb HTTP Request Method
* @param inMessage cxf Message to set the matched user scopes for the resource
* @return whether user role validation against REST API scope roles is success or not.
*/
private boolean validateUserRolesWithRESTAPIScopes(List<Scope> resourceScopeList, Map<String, String> restAPIScopes, String[] userRoles, String username, String path, String verb, Message inMessage) {
// Holds the REST API scope list which the user will get successfully validated against with
List<Scope> validatedUserScopes = new ArrayList<>();
// iterate the non empty scope list of the URITemplate of the invoking resource
for (Scope scope : resourceScopeList) {
// get the configured roles list string of the requested resource
String resourceRolesString = restAPIScopes.get(scope.getKey());
if (StringUtils.isNotBlank(resourceRolesString)) {
// split role list string read using comma separator
List<String> resourceRoleList = Arrays.asList(resourceRolesString.split("\\s*,\\s*"));
// check if the roles related to the API resource contains any of the role of the user
for (String role : userRoles) {
if (resourceRoleList.contains(role)) {
// Role validation is success. Add the current scope to the validated user scope list and
// skip role check iteration of current scope and move to next resource scope.
validatedUserScopes.add(scope);
if (log.isDebugEnabled()) {
log.debug("Basic Authentication: role validation successful for user: " + username + " with scope: " + scope.getKey() + " for resource path: " + path + " and verb " + verb);
log.debug("Added scope: " + scope.getKey() + " to validated user scope list");
}
break;
}
}
} else {
// No role for the requested resource scope. Add it to the validated user scope list.
validatedUserScopes.add(scope);
if (log.isDebugEnabled()) {
log.debug("Role validation skipped. No REST API scope to role mapping defined for resource scope: " + scope.getKey() + " Treated as anonymous scope.");
}
}
}
List<String> scopes = new ArrayList<>();
validatedUserScopes.forEach(scope -> scopes.add(scope.getKey()));
// Add the validated user scope list to the cxf message
inMessage.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, scopes.toArray(new String[0]));
if (!validatedUserScopes.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Successfully validated REST API Scopes for the user " + username);
}
return true;
}
// none of the resource scopes were matched against the user role set
log.error("Insufficient privileges. Role validation failed for user: " + username + " to access resource path: " + path + " and verb " + verb);
return false;
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class AbstractOAuthAuthenticator method validateScopes.
/**
* @param message CXF message to be validate
* @param tokenInfo Token information associated with incoming request
* @return return true if we found matching scope in resource and token information
* else false(means scope validation failed).
*/
@MethodStats
public boolean validateScopes(Message message, OAuthTokenInfo tokenInfo) {
String basePath = (String) message.get(Message.BASE_PATH);
// path is obtained from Message.REQUEST_URI instead of Message.PATH_INFO, as Message.PATH_INFO contains
// decoded values of request parameters
String path = (String) message.get(Message.REQUEST_URI);
String verb = (String) message.get(Message.HTTP_REQUEST_METHOD);
String resource = path.substring(basePath.length() - 1);
String[] scopes = tokenInfo.getScopes();
String version = (String) message.get(RestApiConstants.API_VERSION);
// get all the URI templates of the REST API from the base path
Set<URITemplate> uriTemplates = RestApiUtil.getURITemplatesForBasePath(basePath + version);
if (uriTemplates.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("No matching scopes found for request with path: " + basePath + ". Skipping scope validation.");
}
return true;
}
for (Object template : uriTemplates.toArray()) {
org.wso2.uri.template.URITemplate templateToValidate = null;
Map<String, String> var = new HashMap<String, String>();
// check scopes with what we have
String templateString = ((URITemplate) template).getUriTemplate();
try {
templateToValidate = new org.wso2.uri.template.URITemplate(templateString);
} catch (URITemplateException e) {
log.error("Error while creating URI Template object to validate request. Template pattern: " + templateString, e);
}
if (templateToValidate != null && templateToValidate.matches(resource, var) && scopes != null && verb != null && verb.equalsIgnoreCase(((URITemplate) template).getHTTPVerb())) {
for (String scope : scopes) {
Scope scp = ((URITemplate) template).getScope();
if (scp != null) {
if (scope.equalsIgnoreCase(scp.getKey())) {
// we found scopes matches
if (log.isDebugEnabled()) {
log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scp.getKey() + " for resource path: " + path + " and verb " + verb);
}
return true;
}
} else if (!((URITemplate) template).retrieveAllScopes().isEmpty()) {
List<Scope> scopesList = ((URITemplate) template).retrieveAllScopes();
for (Scope scpObj : scopesList) {
if (scope.equalsIgnoreCase(scpObj.getKey())) {
// we found scopes matches
if (log.isDebugEnabled()) {
log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scpObj.getKey() + " for resource path: " + path + " and verb " + verb);
}
return true;
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Scope not defined in swagger for matching resource " + resource + " and verb " + verb + " . So consider as anonymous permission and let request to continue.");
}
return true;
}
}
}
}
return false;
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class ResourceConfigContext method getContext.
public VelocityContext getContext() {
VelocityContext context = super.getContext();
if (api != null) {
context.put("resources", api.getUriTemplates());
context.put("apiType", api.getType());
context.put("faultSequence", faultSeqExt != null ? faultSeqExt : api.getFaultSequence());
} else if (apiProduct != null) {
// Here we aggregate duplicate resourceURIs of an API and populate httpVerbs set in the uri template
List<APIProductResource> productResources = new ArrayList<>(apiProduct.getProductResources());
List<APIProductResource> aggregateResources = new ArrayList<>();
List<String> uriTemplateNames = new ArrayList<String>();
for (APIProductResource productResource : productResources) {
URITemplate uriTemplate = productResource.getUriTemplate();
String productResourceKey = productResource.getApiIdentifier() + ":" + uriTemplate.getUriTemplate();
if (uriTemplateNames.contains(productResourceKey)) {
for (APIProductResource resource : aggregateResources) {
String resourceKey = resource.getApiIdentifier() + ":" + resource.getUriTemplate().getUriTemplate();
if (resourceKey.equals(productResourceKey)) {
resource.getUriTemplate().setHttpVerbs(uriTemplate.getHTTPVerb());
}
}
} else {
uriTemplate.setHttpVerbs(uriTemplate.getHTTPVerb());
aggregateResources.add(productResource);
uriTemplateNames.add(productResourceKey);
}
}
context.put("apiType", apiProduct.getType());
context.put("aggregates", aggregateResources);
}
return context;
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIMappingUtil method fromAPIProducttoDTO.
public static APIProductDTO fromAPIProducttoDTO(APIProduct product) throws APIManagementException {
APIProductDTO productDto = new APIProductDTO();
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
productDto.setName(product.getId().getName());
productDto.setProvider(APIUtil.replaceEmailDomainBack(product.getId().getProviderName()));
productDto.setId(product.getUuid());
productDto.setContext(product.getContext());
productDto.setDescription(product.getDescription());
productDto.setApiType(APIProductDTO.ApiTypeEnum.fromValue(APIConstants.AuditLogConstants.API_PRODUCT));
productDto.setAuthorizationHeader(product.getAuthorizationHeader());
productDto.setGatewayVendor(product.getGatewayVendor());
Set<String> apiTags = product.getTags();
List<String> tagsToReturn = new ArrayList<>(apiTags);
productDto.setTags(tagsToReturn);
productDto.setEnableSchemaValidation(product.isEnabledSchemaValidation());
productDto.setIsRevision(product.isRevision());
productDto.setRevisionedApiProductId(product.getRevisionedApiProductId());
productDto.setRevisionId(product.getRevisionId());
if (APIConstants.ENABLED.equals(product.getResponseCache())) {
productDto.setResponseCachingEnabled(Boolean.TRUE);
} else {
productDto.setResponseCachingEnabled(Boolean.FALSE);
}
productDto.setCacheTimeout(product.getCacheTimeout());
APIProductBusinessInformationDTO businessInformation = new APIProductBusinessInformationDTO();
businessInformation.setBusinessOwner(product.getBusinessOwner());
businessInformation.setBusinessOwnerEmail(product.getBusinessOwnerEmail());
businessInformation.setTechnicalOwner(product.getTechnicalOwner());
businessInformation.setTechnicalOwnerEmail(product.getTechnicalOwnerEmail());
productDto.setBusinessInformation(businessInformation);
APICorsConfigurationDTO apiCorsConfigurationDTO = new APICorsConfigurationDTO();
CORSConfiguration corsConfiguration = product.getCorsConfiguration();
if (corsConfiguration == null) {
corsConfiguration = APIUtil.getDefaultCorsConfiguration();
}
apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAccessControlAllowOrigins());
apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAccessControlAllowHeaders());
apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAccessControlAllowMethods());
apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isCorsConfigurationEnabled());
apiCorsConfigurationDTO.setAccessControlAllowCredentials(corsConfiguration.isAccessControlAllowCredentials());
productDto.setCorsConfiguration(apiCorsConfigurationDTO);
productDto.setState(StateEnum.valueOf(product.getState()));
productDto.setWorkflowStatus(product.getWorkflowStatus());
// Aggregate API resources to each relevant API.
Map<String, ProductAPIDTO> aggregatedAPIs = new HashMap<String, ProductAPIDTO>();
List<APIProductResource> resources = product.getProductResources();
for (APIProductResource apiProductResource : resources) {
String uuid = apiProductResource.getApiId();
if (aggregatedAPIs.containsKey(uuid)) {
ProductAPIDTO productAPI = aggregatedAPIs.get(uuid);
URITemplate template = apiProductResource.getUriTemplate();
List<APIOperationsDTO> operations = productAPI.getOperations();
APIOperationsDTO operation = getOperationFromURITemplate(template);
operations.add(operation);
} else {
ProductAPIDTO productAPI = new ProductAPIDTO();
productAPI.setApiId(uuid);
productAPI.setName(apiProductResource.getApiName());
productAPI.setVersion(apiProductResource.getApiIdentifier().getVersion());
List<APIOperationsDTO> operations = new ArrayList<APIOperationsDTO>();
URITemplate template = apiProductResource.getUriTemplate();
APIOperationsDTO operation = getOperationFromURITemplate(template);
operations.add(operation);
productAPI.setOperations(operations);
aggregatedAPIs.put(uuid, productAPI);
}
}
productDto.setApis(new ArrayList<>(aggregatedAPIs.values()));
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(product.getId().getProviderName()));
String apiSwaggerDefinition = apiProvider.getOpenAPIDefinition(product.getId(), tenantDomain);
List<ScopeDTO> scopeDTOS = getScopesFromSwagger(apiSwaggerDefinition);
productDto.setScopes(getAPIScopesFromScopeDTOs(scopeDTOS));
String subscriptionAvailability = product.getSubscriptionAvailability();
if (subscriptionAvailability != null) {
productDto.setSubscriptionAvailability(mapSubscriptionAvailabilityFromAPIProducttoDTO(subscriptionAvailability));
}
if (product.getSubscriptionAvailableTenants() != null) {
productDto.setSubscriptionAvailableTenants(Arrays.asList(product.getSubscriptionAvailableTenants().split(",")));
}
Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = product.getAvailableTiers();
List<String> tiersToReturn = new ArrayList<>();
for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
tiersToReturn.add(tier.getName());
}
productDto.setPolicies(tiersToReturn);
productDto.setApiThrottlingPolicy(product.getProductLevelPolicy());
if (product.getVisibility() != null) {
productDto.setVisibility(mapVisibilityFromAPIProducttoDTO(product.getVisibility()));
}
if (product.getVisibleRoles() != null) {
productDto.setVisibleRoles(Arrays.asList(product.getVisibleRoles().split(",")));
}
if (product.getVisibleTenants() != null) {
productDto.setVisibleTenants(Arrays.asList(product.getVisibleTenants().split(",")));
}
productDto.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY.equals(product.getAccessControl()) ? APIProductDTO.AccessControlEnum.RESTRICTED : APIProductDTO.AccessControlEnum.NONE);
if (product.getAccessControlRoles() != null) {
productDto.setAccessControlRoles(Arrays.asList(product.getAccessControlRoles().split(",")));
}
if (StringUtils.isEmpty(product.getTransports())) {
List<String> transports = new ArrayList<>();
transports.add(APIConstants.HTTPS_PROTOCOL);
productDto.setTransport(transports);
} else {
productDto.setTransport(Arrays.asList(product.getTransports().split(",")));
}
if (product.getAdditionalProperties() != null) {
JSONObject additionalProperties = product.getAdditionalProperties();
List<APIInfoAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = new HashMap<>();
for (Object propertyKey : additionalProperties.keySet()) {
APIInfoAdditionalPropertiesDTO additionalPropertiesDTO = new APIInfoAdditionalPropertiesDTO();
APIInfoAdditionalPropertiesMapDTO apiInfoAdditionalPropertiesMapDTO = new APIInfoAdditionalPropertiesMapDTO();
String key = (String) propertyKey;
int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
apiInfoAdditionalPropertiesMapDTO.setValue((String) additionalProperties.get(key));
if (index > 0) {
additionalPropertiesDTO.setName(key.substring(0, index));
apiInfoAdditionalPropertiesMapDTO.setName(key.substring(0, index));
additionalPropertiesDTO.setDisplay(true);
} else {
additionalPropertiesDTO.setName(key);
apiInfoAdditionalPropertiesMapDTO.setName(key);
additionalPropertiesDTO.setDisplay(false);
}
apiInfoAdditionalPropertiesMapDTO.setDisplay(false);
additionalPropertiesMap.put(key, apiInfoAdditionalPropertiesMapDTO);
additionalPropertiesList.add(additionalPropertiesDTO);
}
productDto.setAdditionalPropertiesMap(additionalPropertiesMap);
productDto.setAdditionalProperties(additionalPropertiesList);
}
if (product.getApiSecurity() != null) {
productDto.setSecurityScheme(Arrays.asList(product.getApiSecurity().split(",")));
}
List<APICategory> apiCategories = product.getApiCategories();
List<String> categoryNameList = new ArrayList<>();
if (apiCategories != null && !apiCategories.isEmpty()) {
for (APICategory category : apiCategories) {
categoryNameList.add(category.getName());
}
}
productDto.setCategories(categoryNameList);
if (null != product.getLastUpdated()) {
Date lastUpdateDate = product.getLastUpdated();
Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
productDto.setLastUpdatedTime(String.valueOf(timeStamp));
}
if (null != product.getCreatedTime()) {
Date createdTime = product.getCreatedTime();
Timestamp timeStamp = new Timestamp(createdTime.getTime());
productDto.setCreatedTime(String.valueOf(timeStamp));
}
return productDto;
}
Aggregations