use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class APIUtil method createAPIArtifactContent.
/**
* Create Governance artifact from given attributes
*
* @param artifact initial governance artifact
* @param api API object with the attributes value
* @return GenericArtifact
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to create API
*/
public static GenericArtifact createAPIArtifactContent(GenericArtifact artifact, API api) throws APIManagementException {
try {
String apiStatus = api.getStatus();
artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, api.getId().getApiName());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, api.getId().getVersion());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, api.getVersionTimestamp());
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, api.getContext());
artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, api.getId().getProviderName());
artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, api.getDescription());
artifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_WADL, api.getWadlUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, api.getThumbnailUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiStatus);
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, api.getTechnicalOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, api.getTechnicalOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, api.getBusinessOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, api.getBusinessOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, api.getVisibility());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, api.getVisibleRoles());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, api.getVisibleTenants());
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED, Boolean.toString(api.isEndpointSecured()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST, Boolean.toString(api.isEndpointAuthDigest()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME, api.getEndpointUTUsername());
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD, api.getEndpointUTPassword());
artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, api.getTransports());
artifact.setAttribute(APIConstants.API_OVERVIEW_INSEQUENCE, api.getInSequence());
artifact.setAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE, api.getOutSequence());
artifact.setAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE, api.getFaultSequence());
artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, api.getResponseCache());
artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(api.getCacheTimeout()));
artifact.setAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL, api.getRedirectURL());
artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT, api.getApiExternalProductionEndpoint());
artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT, api.getApiExternalSandboxEndpoint());
artifact.setAttribute(APIConstants.API_OVERVIEW_OWNER, api.getApiOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY, Boolean.toString(api.isAdvertiseOnly()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG, api.getEndpointConfig());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, api.getSubscriptionAvailability());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, api.getSubscriptionAvailableTenants());
artifact.setAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION, api.getImplementation());
artifact.setAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS, api.getProductionMaxTps());
artifact.setAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS, api.getSandboxMaxTps());
artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, api.getAuthorizationHeader());
artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, api.getApiSecurity());
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA, Boolean.toString(api.isEnabledSchemaValidation()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE, Boolean.toString(api.isEnableStore()));
artifact.setAttribute(APIConstants.API_OVERVIEW_TESTKEY, api.getTestKey());
// Validate if the API has an unsupported context before setting it in the artifact
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
String invalidContext = File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(api.getContextTemplate())) {
throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
}
} else {
String invalidContext = APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(api.getContextTemplate())) {
throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
}
}
// This is to support the pluggable version strategy.
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, api.getContextTemplate());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, api.getType());
StringBuilder policyBuilder = new StringBuilder();
for (Tier tier : api.getAvailableTiers()) {
policyBuilder.append(tier.getName());
policyBuilder.append("||");
}
String policies = policyBuilder.toString();
if (!"".equals(policies)) {
policies = policies.substring(0, policies.length() - 2);
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
}
StringBuilder tiersBuilder = new StringBuilder();
for (Tier tier : api.getAvailableTiers()) {
tiersBuilder.append(tier.getName());
tiersBuilder.append("||");
}
String tiers = tiersBuilder.toString();
if (!"".equals(tiers)) {
tiers = tiers.substring(0, tiers.length() - 2);
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
} else {
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
}
if (APIConstants.PUBLISHED.equals(apiStatus)) {
artifact.setAttribute(APIConstants.API_OVERVIEW_IS_LATEST, "true");
}
String[] keys = artifact.getAttributeKeys();
for (String key : keys) {
if (key.contains("URITemplate")) {
artifact.removeAttribute(key);
}
}
Set<URITemplate> uriTemplateSet = api.getUriTemplates();
int i = 0;
for (URITemplate uriTemplate : uriTemplateSet) {
artifact.addAttribute(APIConstants.API_URI_PATTERN + i, uriTemplate.getUriTemplate());
artifact.addAttribute(APIConstants.API_URI_HTTP_METHOD + i, uriTemplate.getHTTPVerb());
artifact.addAttribute(APIConstants.API_URI_AUTH_TYPE + i, uriTemplate.getAuthType());
i++;
}
artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(api));
artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, APIUtil.getCorsConfigurationJsonFromDto(api.getCorsConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_WEBSUB_SUBSCRIPTION_CONFIGURATION, APIUtil.getWebsubSubscriptionConfigurationJsonFromDto(api.getWebsubSubscriptionConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_WS_URI_MAPPING, APIUtil.getWsUriMappingJsonFromDto(api.getWsUriMapping()));
// attaching api categories to the API
List<APICategory> attachedApiCategories = api.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
// set monetization status (i.e - enabled or disabled)
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(api.getMonetizationStatus()));
// set additional monetization data
if (api.getMonetizationProperties() != null) {
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, api.getMonetizationProperties().toJSONString());
}
if (api.getKeyManagers() != null) {
artifact.setAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS, new Gson().toJson(api.getKeyManagers()));
}
// check in github code to see this method was removed
String apiSecurity = artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY);
if (apiSecurity != null && !apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) && !apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, "");
}
} catch (GovernanceException e) {
String msg = "Failed to create API for : " + api.getId().getApiName();
log.error(msg, e);
throw new APIManagementException(msg, e);
}
return artifact;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class APIDescriptionGenUtil method getTierAttributes.
/**
* The method to extract the tier attributes from each tier level policy definitions
* @param policy Tier level policy
* @return Attributes map
* @throws APIManagementException
*/
public static Map<String, Object> getTierAttributes(OMElement policy) throws APIManagementException {
Map<String, Object> attributesMap = new HashMap<String, Object>();
OMElement attributes = null;
try {
OMElement tier = policy.getFirstChildWithName(APIConstants.POLICY_ELEMENT).getFirstChildWithName(APIConstants.THROTTLE_CONTROL_ELEMENT).getFirstChildWithName(APIConstants.POLICY_ELEMENT).getFirstChildWithName(APIConstants.POLICY_ELEMENT);
if (tier != null) {
attributes = tier.getFirstChildWithName(APIConstants.THROTTLE_ATTRIBUTES_ELEMENT);
}
if (attributes == null) {
return attributesMap;
} else {
for (Iterator childElements = attributes.getChildElements(); childElements.hasNext(); ) {
OMElement element = (OMElement) childElements.next();
String displayName = element.getAttributeValue(new QName(APIConstants.THROTTLE_ATTRIBUTE_DISPLAY_NAME));
String localName = element.getLocalName();
// If displayName not defined,
String attrName = (displayName != null ? displayName : localName);
// use the attribute name
String attrValue = element.getText();
attributesMap.put(attrName, attrValue);
}
}
} catch (NullPointerException e) {
String errorMessage = "Policy could not be parsed correctly based on " + "http://schemas.xmlsoap.org/ws/2004/09/policy specification";
log.error(errorMessage, e);
throw new APIManagementException(errorMessage + e.getMessage());
}
return attributesMap;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class APIKeyValidator method getVerbInfoDTOFromAPIData.
/**
* @param messageContext The message context
* @param context API context of API
* @param apiVersion Version of API
* @param requestPath Incoming request path
* @param httpMethod http method of request
* @return verbInfoDTO which contains throttling tier for given resource and verb+resource key
*/
public VerbInfoDTO getVerbInfoDTOFromAPIData(MessageContext messageContext, String context, String apiVersion, String requestPath, String httpMethod) throws APISecurityException {
String cacheKey = context + ':' + apiVersion;
APIInfoDTO apiInfoDTO = null;
if (isGatewayAPIResourceValidationEnabled) {
apiInfoDTO = (APIInfoDTO) getResourceCache().get(cacheKey);
}
if (apiInfoDTO == null) {
apiInfoDTO = doGetAPIInfo(messageContext, context, apiVersion);
if (isGatewayAPIResourceValidationEnabled) {
getResourceCache().put(cacheKey, apiInfoDTO);
}
}
// Match the case where the direct api context is matched
if ("/".equals(requestPath)) {
String requestCacheKey = context + '/' + apiVersion + requestPath + ':' + httpMethod;
// Get decision from cache.
VerbInfoDTO matchingVerb = null;
if (isGatewayAPIResourceValidationEnabled) {
matchingVerb = (VerbInfoDTO) getResourceCache().get(requestCacheKey);
}
// On a cache hit
if (matchingVerb != null) {
matchingVerb.setRequestKey(requestCacheKey);
return matchingVerb;
} else {
if (apiInfoDTO.getResources() != null) {
for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
String urlPattern = resourceInfoDTO.getUrlPattern();
// If the request patch is '/', it can only be matched with a resource whose url-context is '/*'
if ("/*".equals(urlPattern)) {
for (VerbInfoDTO verbDTO : resourceInfoDTO.getHttpVerbs()) {
if (verbDTO.getHttpVerb().equals(httpMethod)) {
// Store verb in cache
if (isGatewayAPIResourceValidationEnabled) {
getResourceCache().put(requestCacheKey, verbDTO);
}
verbDTO.setRequestKey(requestCacheKey);
return verbDTO;
}
}
}
}
}
}
}
// Remove the ending '/' from request
requestPath = RESTUtils.trimTrailingSlashes(requestPath);
while (requestPath.length() > 1) {
String requestCacheKey = context + '/' + apiVersion + requestPath + ':' + httpMethod;
// Get decision from cache.
VerbInfoDTO matchingVerb = null;
if (isGatewayAPIResourceValidationEnabled) {
matchingVerb = (VerbInfoDTO) getResourceCache().get(requestCacheKey);
}
// On a cache hit
if (matchingVerb != null) {
matchingVerb.setRequestKey(requestCacheKey);
return matchingVerb;
} else // On a cache miss
{
for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
String urlPattern = resourceInfoDTO.getUrlPattern();
if (urlPattern.endsWith("/*")) {
// Remove the ending '/*'
urlPattern = urlPattern.substring(0, urlPattern.length() - 2);
}
// If the urlPattern ends with a '/', remove that as well.
urlPattern = RESTUtils.trimTrailingSlashes(urlPattern);
if (requestPath.endsWith(urlPattern)) {
for (VerbInfoDTO verbDTO : resourceInfoDTO.getHttpVerbs()) {
if (verbDTO.getHttpVerb().equals(httpMethod)) {
// Store verb in cache
if (isGatewayAPIResourceValidationEnabled) {
getResourceCache().put(requestCacheKey, verbDTO);
}
verbDTO.setRequestKey(requestCacheKey);
return verbDTO;
}
}
}
}
}
// Remove the section after the last occurrence of the '/' character
int index = requestPath.lastIndexOf('/');
requestPath = requestPath.substring(0, index <= 0 ? 0 : index);
}
// nothing found. return the highest level of security
return null;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class MutualSSLAuthenticator method setAuthContext.
/**
* To set the authentication context in current message context.
*
* @param messageContext Relevant message context.
* @param x509Certificate SSL certificate.
* @throws APISecurityException API Security Exception.
*/
private void setAuthContext(MessageContext messageContext, X509Certificate x509Certificate) throws APISecurityException {
String subjectDN = x509Certificate.getSubjectDN().getName();
String uniqueIdentifier = (x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN()).replaceAll(",", "#").replaceAll("\"", "'").trim();
String tier = certificates.get(uniqueIdentifier);
if (StringUtils.isEmpty(tier)) {
if (log.isDebugEnabled()) {
log.debug("The client certificate presented is available in gateway, however it was not added against " + "the API " + getAPIIdentifier(messageContext));
}
if (isMandatory) {
log.error("Mutual SSL authentication failure. API is not associated with the certificate");
}
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setUsername(subjectDN);
try {
LdapName ldapDN = new LdapName(subjectDN);
for (Rdn rdn : ldapDN.getRdns()) {
if (APIConstants.CERTIFICATE_COMMON_NAME.equalsIgnoreCase(rdn.getType())) {
authContext.setUsername((String) rdn.getValue());
}
}
} catch (InvalidNameException e) {
log.warn("Cannot get the CN name from certificate:" + e.getMessage() + ". Please make sure the " + "certificate to include a proper common name that follows naming convention.");
authContext.setUsername(subjectDN);
}
authContext.setApiTier(apiLevelPolicy);
APIIdentifier apiIdentifier = getAPIIdentifier(messageContext);
authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
authContext.setStopOnQuotaReach(true);
authContext.setApiKey(uniqueIdentifier + "_" + apiIdentifier.toString());
authContext.setTier(tier);
/* For the mutual SSL based authenticated request, the resource level throttling is not considered, hence
assigning the unlimited tier for that. */
List<VerbInfoDTO> verbInfoList = new ArrayList<>(1);
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setThrottling(APIConstants.UNLIMITED_TIER);
verbInfoList.add(verbInfoDTO);
messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
if (log.isDebugEnabled()) {
log.debug("Auth context for the API " + getAPIIdentifier(messageContext) + ": Username[" + authContext.getUsername() + "APIKey[(" + authContext.getApiKey() + "] Tier[" + authContext.getTier() + "]");
}
APISecurityUtils.setAuthenticationContext(messageContext, authContext, null);
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class APIUtilTest method getUniqueAPI.
private API getUniqueAPI() {
APIIdentifier apiIdentifier = new APIIdentifier(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
API api = new API(apiIdentifier);
api.setStatus(APIConstants.CREATED);
api.setContext(UUID.randomUUID().toString());
Set<String> environments = new HashSet<String>();
environments.add(UUID.randomUUID().toString());
URITemplate uriTemplate = new URITemplate();
uriTemplate.setAuthType("None");
uriTemplate.setHTTPVerb("GET");
uriTemplate.setThrottlingTier("Unlimited");
uriTemplate.setUriTemplate("/*");
Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
uriTemplates.add(uriTemplate);
uriTemplate = new URITemplate();
uriTemplate.setAuthType("None");
uriTemplate.setHTTPVerb("GET");
uriTemplate.setThrottlingTier("Unlimited");
uriTemplate.setUriTemplate("/get");
uriTemplates.add(uriTemplate);
uriTemplate = new URITemplate();
uriTemplate.setAuthType("None");
uriTemplate.setHTTPVerb("POST");
uriTemplate.setThrottlingTier("Unlimited");
uriTemplate.setUriTemplate("/*");
uriTemplates.add(uriTemplate);
uriTemplate = new URITemplate();
uriTemplate.setAuthType("None");
uriTemplate.setHTTPVerb("POST");
uriTemplate.setThrottlingTier("Unlimited");
uriTemplate.setUriTemplate("/post");
uriTemplates.add(uriTemplate);
uriTemplate = new URITemplate();
uriTemplate.setAuthType("None");
uriTemplate.setHTTPVerb("DELETE");
uriTemplate.setThrottlingTier("Unlimited");
uriTemplate.setUriTemplate("/*");
uriTemplates.add(uriTemplate);
uriTemplate = new URITemplate();
uriTemplate.setAuthType("None");
uriTemplate.setHTTPVerb("PUT");
uriTemplate.setThrottlingTier("Unlimited");
uriTemplate.setUriTemplate("/*");
uriTemplates.add(uriTemplate);
uriTemplate = new URITemplate();
uriTemplate.setAuthType("None");
uriTemplate.setHTTPVerb("PUT");
uriTemplate.setThrottlingTier("Unlimited");
uriTemplate.setUriTemplate("/put");
uriTemplates.add(uriTemplate);
api.setUriTemplates(uriTemplates);
api.setEnvironments(environments);
api.setUUID(UUID.randomUUID().toString());
api.setThumbnailUrl(UUID.randomUUID().toString());
api.setVisibility(UUID.randomUUID().toString());
api.setVisibleRoles(UUID.randomUUID().toString());
api.setVisibleTenants(UUID.randomUUID().toString());
api.setTransports(UUID.randomUUID().toString());
api.setInSequence(UUID.randomUUID().toString());
api.setOutSequence(UUID.randomUUID().toString());
api.setFaultSequence(UUID.randomUUID().toString());
api.setDescription(UUID.randomUUID().toString());
api.setRedirectURL(UUID.randomUUID().toString());
api.setBusinessOwner(UUID.randomUUID().toString());
api.setApiOwner(UUID.randomUUID().toString());
api.setAdvertiseOnly(true);
CORSConfiguration corsConfiguration = new CORSConfiguration(true, Arrays.asList("*"), true, Arrays.asList("*"), Arrays.asList("*"));
api.setCorsConfiguration(corsConfiguration);
api.setLastUpdated(new Date());
api.setCreatedTime(new Date().toString());
Set<Tier> tierSet = new HashSet<Tier>();
tierSet.add(new Tier("Unlimited"));
tierSet.add(new Tier("Gold"));
api.addAvailableTiers(tierSet);
Set<String> tags = new HashSet<String>();
tags.add("stuff");
api.addTags(tags);
return api;
}
Aggregations