org.wso2.carbon.apimgt.impl.APIConstants Java Examples

The following examples show how to use org.wso2.carbon.apimgt.impl.APIConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOAuthConfigurationFromAPIMConfig () throws Exception {
    String property = "AuthorizationHeader";
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    APIManagerConfigurationService apiManagerConfigurationService =
            Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService())
            .thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.OAUTH_CONFIGS + property))
            .thenReturn("APIM_AUTH");

    String authHeader = getOAuthConfigurationFromAPIMConfig(property);
    Assert.assertEquals("APIM_AUTH", authHeader);
}
 
Example #2
Source File: AbstractKeyValidationHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private boolean validateSubscriptionDetails(String context, String version, String consumerKey, String keyManager,
        APIKeyValidationInfoDTO infoDTO) throws APIManagementException {
    boolean defaultVersionInvoked = false;
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int apiOwnerTenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    // Check if the api version has been prefixed with _default_
    if (version != null && version.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
        defaultVersionInvoked = true;
        // Remove the prefix from the version.
        version = version.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
    }

    validateSubscriptionDetails(infoDTO, context, version, consumerKey, keyManager, defaultVersionInvoked);
    return infoDTO.isAuthorized();
}
 
Example #3
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Remove x-wso2-examples from all the paths from the swagger.
 *
 * @param swaggerString Swagger as String
 */
public String removeExamplesFromSwagger(String swaggerString) throws APIManagementException {
    try {
        SwaggerParser swaggerParser = new SwaggerParser();
        Swagger swagger = swaggerParser.parse(swaggerString);
        swagger.getPaths().values().forEach(path -> {
            path.getOperations().forEach(operation -> {
                if (operation.getVendorExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
                    operation.getVendorExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
                }
            });
        });
        return Yaml.pretty().writeValueAsString(swagger);
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while removing examples from OpenAPI definition", e,
                ExceptionCodes.ERROR_REMOVING_EXAMPLES);
    }
}
 
Example #4
Source File: DefaultMonetizationImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Update info about monetization usage publish job
 *
 * @param monetizationUsagePublishInfo
 * @return boolean always return true if there is no exception
 * @throws MonetizationException
 */
@Override
public boolean publishMonetizationUsageRecords(MonetizationUsagePublishInfo monetizationUsagePublishInfo)
        throws MonetizationException {

    APIAdmin apiAdmin = new APIAdminImpl();
    monetizationUsagePublishInfo.setState(APIConstants.Monetization.COMPLETED);
    monetizationUsagePublishInfo.setStatus(APIConstants.Monetization.SUCCESSFULL);
    DateFormat df = new SimpleDateFormat(APIConstants.Monetization.USAGE_PUBLISH_TIME_FORMAT);
    Date dateobj = new Date();
    //get the time in UTC format
    df.setTimeZone(TimeZone.getTimeZone(APIConstants.Monetization.USAGE_PUBLISH_TIME_ZONE));
    String currentDate = df.format(dateobj);
    long currentTimestamp = apiAdmin.getTimestamp(currentDate);
    monetizationUsagePublishInfo.setLastPublishTime(currentTimestamp);
    try {
        apiAdmin.updateMonetizationUsagePublishInfo(monetizationUsagePublishInfo);
    } catch (APIManagementException e) {
        throw new MonetizationException("Failed to update the monetization usage publish info", e);
    }
    return true;
}
 
Example #5
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgThrottleOutWhenDomainBasedThrottlingAccessRateIsExceeded() throws XMLStreamException,
        ThrottleException {
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REMOTE_ADDR", IP);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REMOTE_HOST", domain);
    //Set domain based throttling limits to be 1/60000
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "DOMAIN", domain, 1,
            60000, "true"),THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "DOMAIN", domain, 1,
            60000, "true"),THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    //First request should continue as the access rates are not exceeded yet (Access rate = 1 per 60000ms )
    Assert.assertTrue(apiThrottleHandler.handleRequest(messageContext));
    //Second request should throttle out as the access rate is exceeded
    Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
 
Example #6
Source File: FileBasedApplicationImportExportManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an archive of the contained application details.
 *
 * @param sourceDirectory Directory which contains source file
 * @param archiveLocation Directory to generate the zip archive
 * @param archiveName     Name of the zip archive
 * @return path to the created archive file
 * @throws APIManagementException if an error occurs while creating an archive from app details
 */
public String createArchiveFromExportedAppArtifacts(String sourceDirectory, String archiveLocation,
                                                    String archiveName) throws APIManagementException {
    String archivedFilePath;
    try {
        archiveDirectory(sourceDirectory, archiveLocation, archiveName);
    } catch (IOException e) {
        // cleanup the archive root directory
        try {
            FileUtils.deleteDirectory(new File(path));
        } catch (IOException e1) {
            log.warn("Unable to remove directory " + path);
        }
        String errorMsg = "Error while archiving directory " + sourceDirectory;
        throw new APIManagementException(errorMsg);
    }
    archivedFilePath = archiveLocation + File.separator + archiveName + APIConstants.ZIP_FILE_EXTENSION;
    return archivedFilePath;
}
 
Example #7
Source File: KeyManagerUserOperationListener.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * To get the fully qualified username with the user store domain.
 *
 * @param username         Name of the User.
 * @param userStoreManager User store manager, which the user is belong to.
 * @return fully qualified username.
 */
private String getUserName(String username, UserStoreManager userStoreManager) {

    String userStoreDomain = getUserStoreDomainName(userStoreManager);
    String tenantDomain = getTenantDomain();

    username = UserCoreUtil.addDomainToName(username, userStoreDomain);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain) ||
            (!MultitenantUtils.isEmailUserName() &&
            username.indexOf(APIConstants.EMAIL_DOMAIN_SEPARATOR) > 0)) {
        username = UserCoreUtil.addTenantDomainToEntry(username, tenantDomain);
    }

    //If the username is not case sensitive
    if (!isUserStoreInUsernameCaseSensitive(username)) {
        username = username.toLowerCase();
    }
    return username;
}
 
Example #8
Source File: SearchResultMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static DocumentSearchResultDTO fromDocumentationToProductDocumentResultDTO(Documentation document,
                                                                                  APIProduct apiProduct) {

    DocumentSearchResultDTO docResultDTO = new DocumentSearchResultDTO();
    docResultDTO.setId(document.getId());
    docResultDTO.setName(document.getName());
    docResultDTO.setDocType(DocumentSearchResultDTO.DocTypeEnum.valueOf(document.getType().toString()));
    docResultDTO.setType(SearchResultDTO.TypeEnum.DOC);
    docResultDTO.associatedType(APIConstants.AuditLogConstants.API_PRODUCT);
    docResultDTO.setSummary(document.getSummary());
    docResultDTO.setVisibility(DocumentSearchResultDTO.VisibilityEnum.valueOf(document.getVisibility().toString()));
    docResultDTO.setSourceType(DocumentSearchResultDTO.SourceTypeEnum.valueOf(document.getSourceType().toString()));
    docResultDTO.setOtherTypeName(document.getOtherTypeName());
    APIProductIdentifier apiId = apiProduct.getId();
    docResultDTO.setApiName(apiId.getName());
    docResultDTO.setApiVersion(apiId.getVersion());
    docResultDTO.setApiProvider(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
    docResultDTO.setApiUUID(apiProduct.getUuid());
    return docResultDTO;
}
 
Example #9
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private static void setScopes(final OpenAPI destOpenAPI, final Set<Scope> aggregatedScopes) {
    Map<String, SecurityScheme> securitySchemes;
    SecurityScheme securityScheme;
    OAuthFlow oAuthFlow;
    Scopes scopes = new Scopes();
    if (destOpenAPI.getComponents() != null &&
            (securitySchemes = destOpenAPI.getComponents().getSecuritySchemes()) != null &&
            (securityScheme = securitySchemes.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY)) != null &&
            (oAuthFlow = securityScheme.getFlows().getImplicit()) != null) {

        Map<String, String> scopeBindings = new HashMap<>();

        for (Scope scope : aggregatedScopes) {
            scopes.addString(scope.getKey(), scope.getDescription());
            scopeBindings.put(scope.getKey(), scope.getRoles());
        }

        oAuthFlow.setScopes(scopes);

        Map<String, Object> extensions = new HashMap<>();
        extensions.put(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
        oAuthFlow.setExtensions(extensions);
    }
}
 
Example #10
Source File: GatewayUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static Map<String, Set<IPRange>> generateIpRangeMap(List<IPRange> ipRangeList) {

        Map<String, Set<IPRange>> ipRangeMap = new HashMap<>();
        for (IPRange ipRange : ipRangeList) {
            Set<IPRange> tenantWiseIpRangeList;
            if (!ipRangeMap.containsKey(ipRange.getTenantDomain())) {
                tenantWiseIpRangeList = new HashSet<>();
            } else {
                tenantWiseIpRangeList = ipRangeMap.get(ipRange.getTenantDomain());
            }
            if (APIConstants.BLOCK_CONDITION_IP_RANGE.equals(ipRange.getType())) {
                convertIpRangeBigIntValue(ipRange);
            }
            tenantWiseIpRangeList.add(ipRange);
            ipRangeMap.put(ipRange.getTenantDomain(), tenantWiseIpRangeList);
        }
        return ipRangeMap;
    }
 
Example #11
Source File: ImportApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This extracts information for creating an APIKey from an OAuthApplication
 * @param type Type of the OAuthApp(SANDBOX or PRODUCTION)
 * @param keyManagerName
 * @param oAuthApplicationInfo OAuth Application information
 * @return An APIKey containing keys from OAuthApplication
 */
private APIKey getAPIKeyFromOauthApp(String type, String keyManagerName,
                                     OAuthApplicationInfo oAuthApplicationInfo){
    APIKey apiKey = new APIKey();
    apiKey.setType(type);
    apiKey.setConsumerKey(oAuthApplicationInfo.getClientId());
    apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
    apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(GRANT_TYPES));
    apiKey.setKeyManager(keyManagerName);
    if (apiKey.getGrantTypes().contains(GRANT_TYPE_IMPLICIT) && apiKey.getGrantTypes().contains(GRANT_TYPE_CODE)){
        apiKey.setCallbackUrl((String) oAuthApplicationInfo.getParameter(REDIRECT_URIS));
    }

    long validityPeriod = OAuthServerConfiguration.getInstance().getApplicationAccessTokenValidityPeriodInSeconds();
    apiKey.setValidityPeriod(validityPeriod);
    apiKey.setTokenScope(DEFAULT_TOKEN_SCOPE);
    apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
    return apiKey;
}
 
Example #12
Source File: InMemoryAPIDeployer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * UnDeploy an API in the gateway using the uneployAPI method in gateway admin
 *
 * @param apiId        - UUID of the API
 * @param gatewayLabel - Label of the Gateway
 * @return True if API artifact retrieved from the storage and successfully undeployed without any error. else false
 */
public boolean unDeployAPI(String apiId, String gatewayLabel) {

    if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled() &&
            gatewayArtifactSynchronizerProperties.getGatewayLabels().contains(gatewayLabel)) {
        if (artifactRetriever != null) {
            try {
                String gatewayRuntimeArtifact = artifactRetriever
                        .retrieveArtifact(apiId, gatewayLabel,
                                APIConstants.GatewayArtifactSynchronizer.GATEWAY_INSTRUCTION_REMOVE);
                if (gatewayRuntimeArtifact != null) {
                    GatewayAPIDTO gatewayAPIDTO = new Gson().fromJson(gatewayRuntimeArtifact, GatewayAPIDTO.class);
                    apiGatewayAdmin.unDeployAPI(gatewayAPIDTO);
                    return true;
                } else {
                    log.error("Error retrieving artifacts for API " + apiId + ". Storage returned null");
                }
            } catch (AxisFault | ArtifactSynchronizerException e) {
                log.error("Error undeploying " + apiId + " in Gateway", e);
            }
        } else {
            log.error("Artifact retriever not found");
        }
    }
    return false;
}
 
Example #13
Source File: SubscriptionsNotifier.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean publishEvent(Event event) throws NotifierException {
    try {
        SubscriptionEvent subEvent = (SubscriptionEvent) event;
        byte[] bytesEncoded = Base64.encodeBase64(new Gson().toJson(subEvent).getBytes());
        Object[] objects = new Object[]{subEvent.getType(), subEvent.getTimeStamp(), new String(bytesEncoded)};
        org.wso2.carbon.databridge.commons.Event payload = new org.wso2.carbon.databridge.commons.Event(
                APIConstants.NOTIFICATION_STREAM_ID, System.currentTimeMillis(),
                null, null, objects);
        APIUtil.publishEventToEventHub( null, payload);
        return true;
    } catch (Exception e) {
        throw new NotifierException(e);
    }
}
 
Example #14
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Remove legacy scope from swagger
 *
 * @param openAPI
 */
private void updateLegacyScopesFromSwagger(OpenAPI openAPI, SwaggerData swaggerData) {

    Map<String, Object> extensions = openAPI.getExtensions();
    if (extensions != null && extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY)) {
        extensions.remove(APIConstants.SWAGGER_X_WSO2_SECURITY);
    }
}
 
Example #15
Source File: DataProcessAndPublishingAgentTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnableQueryParamCondition() throws Exception {
    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnabled(true);
    throttleProperties.setEnableQueryParamConditions(true);
    DataProcessAndPublishingAgent dataProcessAndPublishingAgent = new DataProcessAndPublishingAgentWrapper
            (throttleProperties);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext
            .class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(NhttpConstants.REST_URL_POSTFIX)).thenReturn("?a=1&b=2");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--PizzaShackAPI");
    TreeMap headers = new TreeMap();
    headers.put(APIMgtGatewayConstants.X_FORWARDED_FOR, "192.168.1.1");
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS))
            .thenReturn(headers);
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setContentAware(false);
    ArrayList<VerbInfoDTO> list = new ArrayList<VerbInfoDTO>();
    list.add(verbInfoDTO);
    Mockito.when(messageContext.getProperty(APIConstants.VERB_INFO_DTO)).thenReturn(list);
    dataProcessAndPublishingAgent.setDataReference(applicationLevelThrottleKey, applicationLevelTier,
            apiLevelThrottleKey, null, subscriptionLevelThrottleKey, subscriptionLevelTier,
            resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant,
            apiTenant, appId, messageContext, authenticationContext);
    dataProcessAndPublishingAgent.run();
}
 
Example #16
Source File: ApplicationUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * check whether current logged in user is the owner of the application
 *
 * @param application Application object
 * @param username    loged in user
 * @return true if current logged in consumer is the owner of the specified application
 */
public static boolean isUserOwnerOfApplication(Application application, String username) {
    if (application.getSubscriber().getName().equals(username)) {
        return true;
    } else if (application.getSubscriber().getName().toLowerCase().equals(username.toLowerCase())) {
        APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance()
                .getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String comparisonConfig = configuration
                .getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS);
        return (StringUtils.isNotEmpty(comparisonConfig) && Boolean.valueOf(comparisonConfig));
    }
    return false;
}
 
Example #17
Source File: ApplicationMappingUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static ApplicationDTO fromApplicationtoDTO (Application application) {
    ApplicationDTO applicationDTO = new ApplicationDTO();
    applicationDTO.setApplicationId(application.getUUID());
    applicationDTO.setThrottlingPolicy(application.getTier());
    applicationDTO.setDescription(application.getDescription());
    Map<String,String> applicationAttributes = application.getApplicationAttributes();
    applicationDTO.setAttributes(applicationAttributes);
    applicationDTO.setName(application.getName());
    applicationDTO.setStatus(application.getStatus());
    applicationDTO.setOwner(application.getOwner());

    if (StringUtils.isNotEmpty(application.getGroupId())) {
        applicationDTO.setGroups(Arrays.asList(application.getGroupId().split(",")));
    }
    applicationDTO.setTokenType(ApplicationDTO.TokenTypeEnum.OAUTH);
    applicationDTO.setSubscriptionCount(application.getSubscriptionCount());
    if (StringUtils.isNotEmpty(application.getTokenType()) && !APIConstants.DEFAULT_TOKEN_TYPE
            .equals(application.getTokenType())) {
        applicationDTO.setTokenType(ApplicationDTO.TokenTypeEnum.valueOf(application.getTokenType()));
    }

    //todo: Uncomment when this is implemented
    /*List<ApplicationKeyDTO> applicationKeyDTOs = new ArrayList<>();
    for(APIKey apiKey : application.getKeys()) {
        ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil.fromApplicationKeyToDTO(apiKey);
        applicationKeyDTOs.add(applicationKeyDTO);
    }
    applicationDTO.setKeys(applicationKeyDTOs);*/
    return applicationDTO;
}
 
Example #18
Source File: SecurityConfigContextTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurityConfigContextPerEndpointProductionType() throws Exception {

    String json = "{\"endpoint_security\":{\n" +
            "  \"production\":{\n" +
            "    \"enabled\":true,\n" +
            "    \"type\":\"BASIC\",\n" +
            "    \"username\":\"admin\",\n" +
            "    \"password\":\"admin123#QA\"\n" +
            "  }\n" +
            "  }\n" +
            "}";
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    api.setEndpointConfig(json);
    ConfigContext configcontext = new APIConfigContext(api);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext =
            new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, EndpointSecurityModel> endpointSecurityModelMap =
            (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
    EndpointSecurityModel production = endpointSecurityModelMap.get("production");
    Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
    Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("basic"));
    Assert.assertTrue("Property username does not match.", "admin".equals(production.getUsername()));
    Assert.assertTrue("Property base64value does not match. ",
            new String(Base64.encodeBase64("admin:admin123#QA".getBytes()))
                    .equalsIgnoreCase(production.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.",
            "admin--TestAPI1.0.0--production".equalsIgnoreCase(production.getAlias()));
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ",
            velocityContext.get("isSecureVaultEnabled").equals(true));
    EndpointSecurityModel sandbox = endpointSecurityModelMap.get("sandbox");
    Assert.assertFalse("Property enabled cannot be true.", sandbox.isEnabled());
}
 
Example #19
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMediationSequenceUuidCustomSequence() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);

    Collection collection = Mockito.mock(Collection.class);
    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "custom" + RegistryConstants.PATH_SEPARATOR;

    Mockito.when(registry.get(eq(path))).thenReturn(collection);

    String[] childPaths = {"test"};
    Mockito.when(collection.getChildren()).thenReturn(childPaths);

    String expectedUUID = UUID.randomUUID().toString();

    InputStream sampleSequence = new FileInputStream(Thread.currentThread().getContextClassLoader().
            getResource("sampleSequence.xml").getFile());

    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(registry.get(eq("test"))).thenReturn(resource);
    Mockito.when(resource.getContentStream()).thenReturn(sampleSequence);
    Mockito.when(resource.getUUID()).thenReturn(expectedUUID);


    String actualUUID = APIUtil.getMediationSequenceUuid("sample", 1, "custom", apiIdentifier);

    Assert.assertEquals(expectedUUID, actualUUID);
    sampleSequence.close();
}
 
Example #20
Source File: CacheInvalidationServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public void invalidateResourceCache(String apiContext, String apiVersion,
                                    ResourceCacheInvalidationDto[] uriTemplates) {

    boolean isTenantFlowStarted = false;
    int tenantDomainIndex = apiContext.indexOf("/t/");
    String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    if (tenantDomainIndex != -1) {
        String temp = apiContext.substring(tenantDomainIndex + 3, apiContext.length());
        tenantDomain = temp.substring(0, temp.indexOf('/'));
    }

    try {
        isTenantFlowStarted = startTenantFlow(tenantDomain);
        Cache cache = CacheProvider.getResourceCache();
        if (apiContext.contains(APIConstants.POLICY_CACHE_CONTEXT)) {
            if (log.isDebugEnabled()) {
                log.debug("Cleaning cache for policy update for tenant " + tenantDomain);
            }
            cache.removeAll();
        } else {
            String apiCacheKey = APIUtil.getAPIInfoDTOCacheKey(apiContext, apiVersion);
            if (cache.containsKey(apiCacheKey)) {
                cache.remove(apiCacheKey);
            }
            for (ResourceCacheInvalidationDto uriTemplate : uriTemplates) {
                String resourceVerbCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion,
                        uriTemplate.getResourceURLContext(), uriTemplate.getHttpVerb());
                if (cache.containsKey(resourceVerbCacheKey)) {
                    cache.remove(resourceVerbCacheKey);
                }
            }
        }

    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
}
 
Example #21
Source File: WebsocketUtilTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    System.setProperty("carbon.home", "jhkjn");
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com");
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL))
            .thenReturn(apiKeyValidationURL);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED))
            .thenReturn("true");
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.REMOVE_OAUTH_HEADERS_FROM_MESSAGE))
            .thenReturn("true");
    cacheManager = Mockito.mock(CacheManager.class);
    PowerMockito.mockStatic(Caching.class);
    PowerMockito.when(Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)).thenReturn(cacheManager);
    gwKeyCache = Mockito.mock(Cache.class);
    gwTokenCache = Mockito.mock(Cache.class);
    Mockito.when(cacheManager.getCache(APIConstants.GATEWAY_KEY_CACHE_NAME)).thenReturn(gwKeyCache);
    Mockito.when(cacheManager.getCache(APIConstants.GATEWAY_TOKEN_CACHE_NAME)).thenReturn(gwTokenCache);
}
 
Example #22
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Returns shared status of the mediation policy
 *
 * @param policyName   mediation sequence name
 * @param resourcePath registry resource path
 * @return true, if the mediation policy is a shared resource(global policy)
 */
private static boolean getSharedStatus(String resourcePath, String policyName) {

    if (null != resourcePath && resourcePath.contains(APIConstants.API_CUSTOM_SEQUENCE_LOCATION)) {
        return true;
    }
    return false;
}
 
Example #23
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether tenant is allowed to subscribe
 *
 * @param apiTenant                  Tenant of the API creator
 * @param subscriptionAvailability   Subscription availability
 * @param subscriptionAllowedTenants Subscription allowed tenants
 * @return subscriptionAllowed
 */
private static boolean isSubscriptionAvailable(String apiTenant, String subscriptionAvailability,
                                               String subscriptionAllowedTenants) {

    String userTenant = RestApiUtil.getLoggedInUserTenantDomain();
    boolean subscriptionAllowed = false;
    if (!userTenant.equals(apiTenant)) {
        if (APIConstants.SUBSCRIPTION_TO_ALL_TENANTS.equals(subscriptionAvailability)) {
            subscriptionAllowed = true;
        } else if (APIConstants.SUBSCRIPTION_TO_SPECIFIC_TENANTS.equals(subscriptionAvailability)) {
            String allowedTenants[] = null;
            if (subscriptionAllowedTenants != null) {
                allowedTenants = subscriptionAllowedTenants.split(",");
                if (allowedTenants != null) {
                    for (String tenant : allowedTenants) {
                        if (tenant != null && tenant.trim().equals(userTenant)) {
                            subscriptionAllowed = true;
                            break;
                        }
                    }
                }
            }
        }
    } else {
        subscriptionAllowed = true;
    }
    return subscriptionAllowed;
}
 
Example #24
Source File: ApiKeyGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static String buildBody(JwtTokenInfoDTO jwtTokenInfoDTO) {
    long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    long expireIn;
    if (jwtTokenInfoDTO.getExpirationTime() == -1 ||
            jwtTokenInfoDTO.getExpirationTime() > (Integer.MAX_VALUE-currentTime)) {
        expireIn = -1;
    } else {
        expireIn = currentTime + jwtTokenInfoDTO.getExpirationTime();
    }
    String issuerIdentifier = ServiceReferenceHolder.getInstance().getOauthServerConfiguration()
            .getOpenIDConnectIDTokenIssuerIdentifier();
    JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
    jwtClaimsSetBuilder.claim("sub", APIUtil.getUserNameWithTenantSuffix(jwtTokenInfoDTO.getEndUserName()));
    jwtClaimsSetBuilder.claim("jti", UUID.randomUUID().toString());
    jwtClaimsSetBuilder.claim("iss", issuerIdentifier);
    jwtClaimsSetBuilder.claim("iat", currentTime);
    if (expireIn != -1) {
        jwtClaimsSetBuilder.claim("exp", expireIn);
    }
    jwtClaimsSetBuilder.claim("subscribedAPIs", jwtTokenInfoDTO.getSubscribedApiDTOList());
    jwtClaimsSetBuilder.claim("tierInfo", jwtTokenInfoDTO.getSubscriptionPolicyDTOList());
    jwtClaimsSetBuilder.claim("application", jwtTokenInfoDTO.getApplication());
    jwtClaimsSetBuilder.claim("keytype", jwtTokenInfoDTO.getKeyType());

    if (jwtTokenInfoDTO.getPermittedIP() != null) {
        jwtClaimsSetBuilder.claim(APIConstants.JwtTokenConstants.PERMITTED_IP, jwtTokenInfoDTO.getPermittedIP());
    }
    if (jwtTokenInfoDTO.getPermittedReferer() != null) {
        jwtClaimsSetBuilder.claim(APIConstants.JwtTokenConstants.PERMITTED_REFERER, jwtTokenInfoDTO.getPermittedReferer());
    }

    return jwtClaimsSetBuilder.build().toJSONObject().toJSONString();
}
 
Example #25
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get Application level security types
 *
 * @param security list of security types
 * @return List of api security
 */
private static List<String> getAPISecurity(List<String> security) {
    List<String> apiSecurityList = new ArrayList<>();
    for (String securityType : security) {
        if (APIConstants.APPLICATION_LEVEL_SECURITY.contains(securityType)) {
            apiSecurityList.add(securityType);
        }
    }
    return apiSecurityList;
}
 
Example #26
Source File: OAuthAuthenticator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
protected void initOAuthParams() {
    APIManagerConfiguration config = getApiManagerConfiguration();
    String value = config.getFirstProperty(APIConstants.REMOVE_OAUTH_HEADERS_FROM_MESSAGE);
    if (value != null) {
        removeOAuthHeadersFromOutMessage = Boolean.parseBoolean(value);
    }
    JWTConfigurationDto jwtConfigurationDto = config.getJwtConfigurationDto();
    value = jwtConfigurationDto.getJwtHeader();
    if (value != null) {
        setSecurityContextHeader(value);
    }
}
 
Example #27
Source File: TemplateUtilContextTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testTemplateUtilContext() throws Exception {
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    ConfigContext configcontext = new APIConfigContext(api);
    TemplateUtilContext templateUtilContext = new TemplateUtilContext(configcontext);
    String xmlSampleText = "<data>TemplateUtilContextTest Class</data>";
    String xmlEscapedText = "&lt;data&gt;TemplateUtilContextTest Class&lt;/data&gt;";
    String result = templateUtilContext.escapeXml(xmlSampleText);
    Assert.assertTrue("Failed to escape XML tags in the provided string : " + xmlSampleText,
            xmlEscapedText.equalsIgnoreCase(result));
    Assert.assertNotNull(templateUtilContext.getContext().get("util"));
}
 
Example #28
Source File: APIConfigContext.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void setApiProductVelocityContext(APIProduct apiProduct, VelocityContext context) {
    APIProductIdentifier id = apiProduct.getId();
    //set the api name version and context
    context.put("apiName", PRODUCT_PREFIX + "--" + id.getName());
    context.put("apiVersion", "1.0.0");

    // We set the context pattern now to support plugable version strategy
    // context.put("apiContext", api.getContext());
    context.put("apiContext", apiProduct.getContext());

    //the api object will be passed on to the template so it properties can be used to
    // customise how the synapse config is generated.
    context.put("apiObj", apiProduct);

    context.put("apiIsBlocked", Boolean.FALSE);

    String apiSecurity = apiProduct.getApiSecurity();
    if (apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
        context.put("apiIsOauthProtected", Boolean.TRUE);
    } else {
        context.put("apiIsOauthProtected", Boolean.FALSE);
    }
    if (apiProduct.isEnabledSchemaValidation()) {
        context.put("enableSchemaValidation", Boolean.TRUE);
    } else {
        context.put("enableSchemaValidation", Boolean.FALSE);
    }
}
 
Example #29
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddDefaultTenantAdvancedThrottlePoliciesSubLevel() throws Exception {
    int tenantId = 1;
    String tenantDomain = "test.com";

    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    ThrottlePolicyTemplateBuilder templateBuilder = Mockito.mock(ThrottlePolicyTemplateBuilder.class);
    PowerMockito.whenNew(ThrottlePolicyTemplateBuilder.class).withNoArguments().thenReturn(templateBuilder);

    String[] policies = new String[]{APIConstants.DEFAULT_SUB_POLICY_GOLD, APIConstants.DEFAULT_SUB_POLICY_SILVER,
            APIConstants.DEFAULT_SUB_POLICY_BRONZE, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED,
            APIConstants.DEFAULT_SUB_POLICY_UNLIMITED};

    for (String policy : policies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_SUB), eq(tenantId),
                        eq(policy))).thenReturn(false);
        Mockito.when(
                apiMgtDAO.isPolicyDeployed(eq(PolicyConstants.POLICY_LEVEL_SUB), eq(tenantId),
                        eq(policy))).thenReturn(false);
    }

    APIUtil.addDefaultTenantAdvancedThrottlePolicies(tenantDomain, tenantId);
    Mockito.verify(apiMgtDAO, Mockito.times(policies.length)).
            addSubscriptionPolicy(Mockito.any(SubscriptionPolicy.class));
    Mockito.verify(apiMgtDAO, Mockito.times(policies.length)).
            setPolicyDeploymentStatus(eq(PolicyConstants.POLICY_LEVEL_SUB), Mockito.anyString(), eq(tenantId), eq(true));
}
 
Example #30
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This pointcut looks for the system property to enable/ disable timing logs
 *
 * @return true if the property value is given as true
 */
@Pointcut("if()")
public static boolean isConfigEnabled() {
    if (!isSet) {
        String config = System.getProperty(APIConstants.ENABLE_CORRELATION_LOGS);
        if (StringUtils.isNotEmpty(config)) {
            isEnabled = Boolean.parseBoolean(config);
            isSet = true;
        }
    }
    return isEnabled;
}