Search in sources :

Example 81 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class ApiMgtDAO method getClientOfApplication.

private Map<String, OAuthApplicationInfo> getClientOfApplication(String tenntDomain, int applicationID, String keyType) throws APIManagementException {
    String sqlQuery = SQLConstants.GET_CLIENT_OF_APPLICATION_SQL;
    Map<String, OAuthApplicationInfo> keyTypeWiseOAuthApps = new HashMap<>();
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        ps = connection.prepareStatement(sqlQuery);
        ps.setInt(1, applicationID);
        ps.setString(2, keyType);
        rs = ps.executeQuery();
        while (rs.next()) {
            String consumerKey = rs.getString("CONSUMER_KEY");
            String keyManagerName = rs.getString("KEY_MANAGER");
            if (consumerKey != null) {
                KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenntDomain, keyManagerName);
                if (keyManager != null) {
                    OAuthApplicationInfo oAuthApplication = keyManager.retrieveApplication(consumerKey);
                    keyTypeWiseOAuthApps.put(keyManagerName, oAuthApplication);
                }
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get  client of application. SQL error", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, connection, rs);
    }
    return keyTypeWiseOAuthApps;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 82 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validateSubscriptionDetails.

private APIKeyValidationInfoDTO validateSubscriptionDetails(APIKeyValidationInfoDTO infoDTO, String context, String version, String consumerKey, String keyManager, boolean defaultVersionInvoked) {
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int tenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    API api = null;
    ApplicationKeyMapping key = null;
    Application app = null;
    Subscription sub = null;
    SubscriptionDataStore datastore = SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(apiTenantDomain);
    // TODO add a check to see whether datastore is initialized an load data using rest api if it is not loaded
    if (datastore != null) {
        api = datastore.getApiByContextAndVersion(context, version);
        if (api != null) {
            key = datastore.getKeyMappingByKeyAndKeyManager(consumerKey, keyManager);
            if (key != null) {
                app = datastore.getApplicationById(key.getApplicationId());
                if (app != null) {
                    sub = datastore.getSubscriptionById(app.getId(), api.getApiId());
                    if (sub != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("All information is retrieved from the inmemory data store.");
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Valid subscription not found for appId " + app.getId() + " and apiId " + api.getApiId());
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Application not found in the datastore for id " + key.getApplicationId());
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Application keymapping not found in the datastore for id consumerKey " + consumerKey);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("API not found in the datastore for " + context + ":" + version);
            }
        }
    } else {
        log.error("Subscription datastore is not initialized for tenant domain " + apiTenantDomain);
    }
    if (api != null && app != null && key != null && sub != null) {
        validate(infoDTO, apiTenantDomain, tenantId, datastore, api, key, app, sub, keyManager);
    } else if (!infoDTO.isAuthorized() && infoDTO.getValidationStatus() == 0) {
        // Scenario where validation failed and message is not set
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
    } else {
        infoDTO.setAuthorized(false);
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
    }
    return infoDTO;
}
Also used : API(org.wso2.carbon.apimgt.keymgt.model.entity.API) SubscriptionDataStore(org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore) Subscription(org.wso2.carbon.apimgt.keymgt.model.entity.Subscription) Application(org.wso2.carbon.apimgt.keymgt.model.entity.Application) ApplicationKeyMapping(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationKeyMapping)

Example 83 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class ApplicationKeyMappingsApiServiceImpl method applicationKeyMappingsGet.

@Override
public Response applicationKeyMappingsGet(String xWSO2Tenant, String consumerKey, String keymanager, MessageContext messageContext) throws APIManagementException {
    SubscriptionValidationDAO subscriptionValidationDAO = new SubscriptionValidationDAO();
    xWSO2Tenant = SubscriptionValidationDataUtil.validateTenantDomain(xWSO2Tenant, messageContext);
    if (StringUtils.isNotEmpty(consumerKey)) {
        ApplicationKeyMapping keyMapping = subscriptionValidationDAO.getApplicationKeyMapping(consumerKey, keymanager, xWSO2Tenant);
        List<ApplicationKeyMapping> applicationKeyMappings = new ArrayList<>();
        if (keyMapping != null) {
            applicationKeyMappings.add(keyMapping);
        }
        return Response.ok().entity(SubscriptionValidationDataUtil.fromApplicationKeyMappingToApplicationKeyMappingListDTO(applicationKeyMappings)).build();
    }
    if (StringUtils.isNotEmpty(xWSO2Tenant)) {
        return Response.ok().entity(SubscriptionValidationDataUtil.fromApplicationKeyMappingToApplicationKeyMappingListDTO(subscriptionValidationDAO.getAllApplicationKeyMappings(xWSO2Tenant))).build();
    }
    return null;
}
Also used : ArrayList(java.util.ArrayList) ApplicationKeyMapping(org.wso2.carbon.apimgt.api.model.subscription.ApplicationKeyMapping) SubscriptionValidationDAO(org.wso2.carbon.apimgt.impl.dao.SubscriptionValidationDAO)

Example 84 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method deleteAPIFromDB.

/**
 * Deletes API from the database and delete local scopes and resource scope attachments from KM.
 *
 * @param api API to delete
 * @throws APIManagementException if fails to delete the API
 */
private void deleteAPIFromDB(API api) throws APIManagementException {
    APIIdentifier apiIdentifier = api.getId();
    int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    // Get local scopes for the given API which are not already assigned for different versions of the same API
    Set<String> localScopeKeysToDelete = apiMgtDAO.getUnversionedLocalScopeKeysForAPI(api.getUuid(), tenantId);
    // Get the URI Templates for the given API to detach the resources scopes from
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    // Detach all the resource scopes from the API resources in KM
    Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
    for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
        KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
        if (keyManager != null) {
            try {
                keyManager.detachResourceScopes(api, uriTemplates);
                if (log.isDebugEnabled()) {
                    log.debug("Resource scopes are successfully detached for the API : " + apiIdentifier + " from Key Manager :" + keyManagerDtoEntry.getKey() + ".");
                }
                // remove the local scopes from the KM
                for (String localScope : localScopeKeysToDelete) {
                    keyManager.deleteScope(localScope);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Local scopes are successfully deleted for the API : " + apiIdentifier + " from Key Manager : " + keyManagerDtoEntry.getKey() + ".");
                }
            } catch (APIManagementException e) {
                log.error("Error while Detach and Delete Scope from Key Manager " + keyManagerDtoEntry.getKey(), e);
            }
        }
    }
    deleteScopes(localScopeKeysToDelete, tenantId);
    apiMgtDAO.deleteAPI(api.getUuid());
    if (log.isDebugEnabled()) {
        log.debug("API : " + apiIdentifier + " is successfully deleted from the database and Key Manager.");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 85 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method deleteAPI.

public void deleteAPI(String apiUuid, String organization) throws APIManagementException {
    boolean isError = false;
    int apiId = -1;
    API api = null;
    // get api object by uuid
    try {
        api = getAPIbyUUID(apiUuid, organization);
    } catch (APIManagementException e) {
        log.error("Error while getting API by uuid for deleting API " + apiUuid + " on organization " + organization);
        log.debug("Following steps will be skipped while deleting API " + apiUuid + "on organization " + organization + " due to api being null. " + "deleting Resource Registration from key managers, deleting on external API stores, " + "event publishing to gateways, logging audit message, extracting API details for " + "the recommendation system. ");
        isError = true;
    }
    // get api id from db
    try {
        apiId = apiMgtDAO.getAPIID(apiUuid);
    } catch (APIManagementException e) {
        log.error("Error while getting API ID from DB for deleting API " + apiUuid + " on organization " + organization, e);
        log.debug("Following steps will be skipped while deleting the API " + apiUuid + " on organization " + organization + "due to api id being null. cleanup workflow tasks of the API, " + "delete event publishing to gateways");
        isError = true;
    }
    // DB delete operations
    if (!isError && api != null) {
        try {
            deleteAPIRevisions(apiUuid, organization);
            deleteAPIFromDB(api);
            if (log.isDebugEnabled()) {
                String logMessage = "API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + " successfully removed from the database.";
                log.debug(logMessage);
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operations on DB for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Deleting Resource Registration from key managers
    if (api != null && api.getId() != null && api.getId().toString() != null) {
        Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
        for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
            KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
            if (keyManager != null) {
                try {
                    keyManager.deleteRegisteredResourceByAPIId(api.getId().toString());
                    log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the Key Manager " + keyManagerDtoEntry.getKey());
                } catch (APIManagementException e) {
                    log.error("Error while deleting Resource Registration for API " + apiUuid + " on organization " + organization + " in Key Manager " + keyManagerDtoEntry.getKey(), e);
                }
            }
        }
    }
    try {
        GatewayArtifactsMgtDAO.getInstance().deleteGatewayArtifacts(apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the gateway artifacts.");
    } catch (APIManagementException e) {
        log.error("Error while executing API delete operation on gateway artifacts for API " + apiUuid, e);
        isError = true;
    }
    try {
        apiPersistenceInstance.deleteAPI(new Organization(organization), apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the persistence instance.");
    } catch (APIPersistenceException e) {
        log.error("Error while executing API delete operation on persistence instance for API " + apiUuid + " on organization " + organization, e);
        isError = true;
    }
    // Deleting on external API stores
    if (api != null) {
        // gatewayType check is required when API Management is deployed on
        // other servers to avoid synapse
        // Check if there are already published external APIStores.If yes,removing APIs from them.
        Set<APIStore> apiStoreSet;
        try {
            apiStoreSet = getPublishedExternalAPIStores(apiUuid);
            WSO2APIPublisher wso2APIPublisher = new WSO2APIPublisher();
            if (apiStoreSet != null && !apiStoreSet.isEmpty()) {
                for (APIStore store : apiStoreSet) {
                    wso2APIPublisher.deleteFromStore(api.getId(), APIUtil.getExternalAPIStore(store.getName(), tenantId));
                }
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operation on external API stores for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    if (apiId != -1) {
        try {
            cleanUpPendingAPIStateChangeTask(apiId, false);
        } catch (WorkflowException | APIManagementException e) {
            log.error("Error while executing API delete operation on cleanup workflow tasks for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Delete event publishing to gateways
    if (api != null && apiId != -1) {
        APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_DELETE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
        APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    } else {
        log.debug("Event has not published to gateways due to API id has failed to retrieve from DB for API " + apiUuid + " on organization " + organization);
    }
    // Logging audit message for API delete
    if (api != null) {
        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    }
    // Extracting API details for the recommendation system
    if (api != null && recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.DELETE_API);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // if one of the above has failed throw an error
    if (isError) {
        throw new APIManagementException("Error while deleting the API " + apiUuid + " on organization " + organization);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) JSONObject(org.json.simple.JSONObject) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) WSO2APIPublisher(org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)38 Test (org.junit.Test)29 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 HashMap (java.util.HashMap)21 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 FileInputStream (java.io.FileInputStream)16 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)16 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)16 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)16 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)16 Map (java.util.Map)14 API (org.wso2.carbon.apimgt.core.models.API)14 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)13 Scope (org.wso2.carbon.apimgt.core.models.Scope)13 KeyManagerDto (org.wso2.carbon.apimgt.impl.dto.KeyManagerDto)13 TreeMap (java.util.TreeMap)11 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)11