use of org.wso2.carbon.apimgt.impl.dto.KeyManagerDto in project carbon-apimgt by wso2.
the class DefaultKeyValidationHandler method getAccessTokenInfo.
private AccessTokenInfo getAccessTokenInfo(TokenValidationContext validationContext) throws APIManagementException {
Object cachedAccessTokenInfo = CacheProvider.createIntrospectionCache().get(validationContext.getAccessToken());
if (cachedAccessTokenInfo != null) {
log.debug("AccessToken available in introspection Cache.");
return (AccessTokenInfo) cachedAccessTokenInfo;
}
String electedKeyManager = null;
// Obtaining details about the token.
if (StringUtils.isNotEmpty(validationContext.getTenantDomain())) {
Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(validationContext.getTenantDomain());
KeyManager keyManagerInstance = null;
if (tenantKeyManagers.values().size() == 1) {
log.debug("KeyManager count is 1");
Map.Entry<String, KeyManagerDto> entry = tenantKeyManagers.entrySet().iterator().next();
if (entry != null) {
KeyManagerDto keyManagerDto = entry.getValue();
if (keyManagerDto != null && (validationContext.getKeyManagers().contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || validationContext.getKeyManagers().contains(keyManagerDto.getName()))) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDto.getName() + " Available in API level KM list " + String.join(",", validationContext.getKeyManagers()));
}
if (keyManagerDto.getKeyManager() != null && keyManagerDto.getKeyManager().canHandleToken(validationContext.getAccessToken())) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDto.getName() + " can handle the token");
}
keyManagerInstance = keyManagerDto.getKeyManager();
electedKeyManager = entry.getKey();
}
}
}
} else if (tenantKeyManagers.values().size() > 1) {
log.debug("KeyManager count is > 1");
if (validationContext.getKeyManagers().contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS)) {
if (log.isDebugEnabled()) {
log.debug("API level KeyManagers contains " + APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS);
}
for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
if (keyManagerDtoEntry.getValue().getKeyManager() != null && keyManagerDtoEntry.getValue().getKeyManager().canHandleToken(validationContext.getAccessToken())) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDtoEntry.getValue().getName() + " can handle the token");
}
keyManagerInstance = keyManagerDtoEntry.getValue().getKeyManager();
electedKeyManager = keyManagerDtoEntry.getKey();
break;
}
}
} else {
for (String selectedKeyManager : validationContext.getKeyManagers()) {
KeyManagerDto keyManagerDto = tenantKeyManagers.get(selectedKeyManager);
if (keyManagerDto != null && keyManagerDto.getKeyManager() != null && keyManagerDto.getKeyManager().canHandleToken(validationContext.getAccessToken())) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDto.getName() + " can handle the token");
}
keyManagerInstance = keyManagerDto.getKeyManager();
electedKeyManager = selectedKeyManager;
break;
}
}
}
}
if (keyManagerInstance != null) {
log.debug("KeyManager instance available to validate token.");
AccessTokenInfo tokenInfo = keyManagerInstance.getTokenMetaData(validationContext.getAccessToken());
tokenInfo.setKeyManager(electedKeyManager);
CacheProvider.getGatewayIntrospectCache().put(validationContext.getAccessToken(), tokenInfo);
return tokenInfo;
} else {
AccessTokenInfo tokenInfo = new AccessTokenInfo();
tokenInfo.setTokenValid(false);
tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
log.debug("KeyManager not available to authorize token.");
return tokenInfo;
}
}
return null;
}
use of org.wso2.carbon.apimgt.impl.dto.KeyManagerDto in project carbon-apimgt by wso2.
the class APIProviderImplTest method init.
@Before
public void init() throws Exception {
System.setProperty("carbon.home", APIProviderImplTest.class.getResource("/").getFile());
PowerMockito.mockStatic(ApiMgtDAO.class);
PowerMockito.mockStatic(GatewayArtifactsMgtDAO.class);
PowerMockito.mockStatic(ScopesDAO.class);
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
PowerMockito.mockStatic(RegistryUtils.class);
PowerMockito.mockStatic(GovernanceUtils.class);
PowerMockito.mockStatic(WorkflowExecutorFactory.class);
PowerMockito.mockStatic(LifecycleBeanPopulator.class);
PowerMockito.mockStatic(KeyManagerHolder.class);
PowerMockito.mockStatic(Caching.class);
PowerMockito.mockStatic(PaginationContext.class);
PowerMockito.mockStatic(APIUtil.class);
PowerMockito.mockStatic(APIGatewayManager.class);
PowerMockito.mockStatic(CertificateManagerImpl.class);
PowerMockito.mockStatic(RegistryPersistenceUtil.class);
apimgtDAO = Mockito.mock(ApiMgtDAO.class);
gatewayArtifactsMgtDAO = Mockito.mock(GatewayArtifactsMgtDAO.class);
scopesDAO = Mockito.mock(ScopesDAO.class);
keyManager = Mockito.mock(KeyManager.class);
apiPersistenceInstance = Mockito.mock(APIPersistence.class);
certificateManager = Mockito.mock(CertificateManagerImpl.class);
Mockito.when(keyManager.getResourceByApiId(Mockito.anyString())).thenReturn(null);
Mockito.when(keyManager.registerNewResource(Mockito.any(API.class), Mockito.any(Map.class))).thenReturn(true);
KeyManagerDto keyManagerDto = new KeyManagerDto();
keyManagerDto.setName("default");
keyManagerDto.setKeyManager(keyManager);
keyManagerDto.setIssuer("https://localhost");
Map<String, KeyManagerDto> tenantKeyManagerDtoMap = new HashMap<>();
tenantKeyManagerDtoMap.put("default", keyManagerDto);
PowerMockito.when(KeyManagerHolder.getTenantKeyManagers("carbon.super")).thenReturn(tenantKeyManagerDtoMap);
PowerMockito.when(CertificateManagerImpl.getInstance()).thenReturn(certificateManager);
PowerMockito.when(APIUtil.isAPIManagementEnabled()).thenReturn(false);
PowerMockito.when(APIUtil.replaceEmailDomainBack(Mockito.anyString())).thenReturn("admin");
Mockito.when(APIUtil.replaceEmailDomain(Mockito.anyString())).thenReturn("admin");
PrivilegedCarbonContext prcontext = Mockito.mock(PrivilegedCarbonContext.class);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(prcontext);
PowerMockito.doNothing().when(prcontext).setUsername(Mockito.anyString());
PowerMockito.doNothing().when(prcontext).setTenantDomain(Mockito.anyString(), Mockito.anyBoolean());
artifactManager = Mockito.mock(GenericArtifactManager.class);
registry = Mockito.mock(Registry.class);
PowerMockito.when(APIUtil.getArtifactManager(any(Registry.class), Mockito.anyString())).thenReturn(artifactManager);
artifact = Mockito.mock(GenericArtifact.class);
gatewayManager = Mockito.mock(APIGatewayManager.class);
Mockito.when(APIGatewayManager.getInstance()).thenReturn(gatewayManager);
TestUtils.mockRegistryAndUserRealm(-1234);
TestUtils.mockAPICacheClearence();
TestUtils.mockAPIMConfiguration();
mockDocumentationCreation();
config = Mockito.mock(APIManagerConfiguration.class);
APIManagerConfigurationService apiManagerConfigurationService = new APIManagerConfigurationServiceImpl(config);
ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(apiManagerConfigurationService);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
Mockito.when(config.getApiRecommendationEnvironment()).thenReturn(null);
PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> {
Object[] args = invocation.getArguments();
return (String) args[0];
});
TestUtils.initConfigurationContextService(true);
superTenantDomain = "carbon.super";
}
use of org.wso2.carbon.apimgt.impl.dto.KeyManagerDto in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method init.
@Before
public void init() {
System.setProperty(CARBON_HOME, "");
privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
PowerMockito.mockStatic(GovernanceUtils.class);
paginationContext = Mockito.mock(PaginationContext.class);
PowerMockito.mockStatic(PaginationContext.class);
PowerMockito.when(PaginationContext.getInstance()).thenReturn(paginationContext);
apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
scopesDAO = Mockito.mock(ScopesDAO.class);
registry = Mockito.mock(Registry.class);
genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
registryService = Mockito.mock(RegistryService.class);
tenantManager = Mockito.mock(TenantManager.class);
graphQLSchemaDefinition = Mockito.mock(GraphQLSchemaDefinition.class);
keyManager = Mockito.mock(KeyManager.class);
apiPersistenceInstance = Mockito.mock(APIPersistence.class);
PowerMockito.mockStatic(KeyManagerHolder.class);
KeyManagerDto keyManagerDto = new KeyManagerDto();
keyManagerDto.setName("default");
keyManagerDto.setKeyManager(keyManager);
keyManagerDto.setIssuer("https://localhost");
Map<String, KeyManagerDto> tenantKeyManagerDtoMap = new HashMap<>();
tenantKeyManagerDtoMap.put("default", keyManagerDto);
PowerMockito.when(KeyManagerHolder.getTenantKeyManagers("carbon.super")).thenReturn(tenantKeyManagerDtoMap);
}
use of org.wso2.carbon.apimgt.impl.dto.KeyManagerDto in project carbon-apimgt by wso2.
the class APIProviderImpl method registerOrUpdateResourceInKeyManager.
/**
* Notify the key manager with API update or addition
*
* @param api API
* @param tenantDomain
* @throws APIManagementException when error occurs when register/update API at Key Manager side
*/
private void registerOrUpdateResourceInKeyManager(API api, String tenantDomain) throws APIManagementException {
// get new key manager instance for resource registration.
Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
if (keyManager != null) {
try {
Map registeredResource = keyManager.getResourceByApiId(api.getId().toString());
if (registeredResource == null) {
boolean isNewResourceRegistered = keyManager.registerNewResource(api, null);
if (!isNewResourceRegistered) {
log.warn("APIResource registration is failed while adding the API- " + api.getId().getApiName() + "-" + api.getId().getVersion() + " into Key Manager : " + keyManagerDtoEntry.getKey());
}
} else {
// update APIResource.
String resourceId = (String) registeredResource.get("resourceId");
if (resourceId == null) {
handleException("APIResource update is failed because of empty resourceID.");
}
keyManager.updateRegisteredResource(api, registeredResource);
}
} catch (APIManagementException e) {
log.error("API Resource Registration failed in Key Manager " + keyManagerDtoEntry.getKey(), e);
}
}
}
}
use of org.wso2.carbon.apimgt.impl.dto.KeyManagerDto in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPIResources.
/**
* Update resources of the API including local scopes and resource to scope attachments.
*
* @param api API
* @param tenantId Tenant Id
* @throws APIManagementException If fails to update local scopes of the API.
*/
private void updateAPIResources(API api, int tenantId) throws APIManagementException {
String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
APIIdentifier apiIdentifier = api.getId();
// Get the new URI templates for the API
Set<URITemplate> uriTemplates = api.getUriTemplates();
// Get the existing local scope keys attached for the API
Set<String> oldLocalScopeKeys = apiMgtDAO.getAllLocalScopeKeysForAPI(api.getUuid(), tenantId);
// Get the existing URI templates for the API
Set<URITemplate> oldURITemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
// Get the new local scope keys from URI templates
Set<Scope> newLocalScopes = getScopesToRegisterFromURITemplates(api.getId().getApiName(), api.getOrganization(), uriTemplates);
Set<String> newLocalScopeKeys = newLocalScopes.stream().map(Scope::getKey).collect(Collectors.toSet());
// Get the existing versioned local scope keys attached for the API
Set<String> oldVersionedLocalScopeKeys = apiMgtDAO.getVersionedLocalScopeKeysForAPI(api.getUuid(), tenantId);
// Get the existing versioned local scope keys which needs to be removed (not updated) from the current updating
// API and remove them from the oldLocalScopeKeys set before sending to KM, so that they will not be removed
// from KM and can be still used by other versioned APIs.
Iterator oldLocalScopesItr = oldLocalScopeKeys.iterator();
while (oldLocalScopesItr.hasNext()) {
String oldLocalScopeKey = (String) oldLocalScopesItr.next();
// if the scope is used in versioned APIs and it is not in new local scope key set
if (oldVersionedLocalScopeKeys.contains(oldLocalScopeKey) && !newLocalScopeKeys.contains(oldLocalScopeKey)) {
// remove from old local scope key set which will be send to KM
oldLocalScopesItr.remove();
}
}
apiMgtDAO.updateURITemplates(api, tenantId);
if (log.isDebugEnabled()) {
log.debug("Successfully updated the URI templates of API: " + apiIdentifier + " in the database");
}
// Update the resource scopes of the API in KM.
// Need to remove the old local scopes and register new local scopes and, update the resource scope mappings
// using the updated URI templates of the API.
deleteScopes(oldLocalScopeKeys, tenantId);
addScopes(newLocalScopes, tenantId);
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.updateResourceScopes(api, oldLocalScopeKeys, newLocalScopes, oldURITemplates, uriTemplates);
if (log.isDebugEnabled()) {
log.debug("Successfully updated the resource scopes of API: " + apiIdentifier + " in Key Manager " + keyManagerDtoEntry.getKey() + " .");
}
} catch (APIManagementException e) {
log.error("Error while updating resource to scope attachment in Key Manager " + keyManagerDtoEntry.getKey(), e);
}
}
}
}
Aggregations