use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class RegistryPersistenceImplTestCase method testRegistrySelectionForTenantUserCrossTenatAccess.
@Test
public void testRegistrySelectionForTenantUserCrossTenatAccess() throws Exception {
RegistryService registryService = Mockito.mock(RegistryService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(tenantManager.getTenantId(TENANT_DOMAIN)).thenReturn(TENANT_ID);
Mockito.when(tenantManager.getTenantId(SUPER_TENANT_DOMAIN)).thenReturn(SUPER_TENANT_ID);
PowerMockito.mockStatic(CarbonContext.class);
CarbonContext context = Mockito.mock(CarbonContext.class);
PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(context);
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
PrivilegedCarbonContext privilegedContext = Mockito.mock(PrivilegedCarbonContext.class);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedContext);
PowerMockito.mockStatic(GovernanceUtils.class);
GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
List<GovernanceArtifact> artifacts = new ArrayList<GovernanceArtifact>();
artifacts.add(artifact);
PowerMockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.any(String.class), Mockito.any(Registry.class), Mockito.any(String.class), Mockito.any(Boolean.class))).thenReturn(artifacts);
PowerMockito.mockStatic(RegistryPersistenceUtil.class);
ServiceReferenceHolder serviceRefHolder = Mockito.mock(ServiceReferenceHolder.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceRefHolder);
RealmService realmService = Mockito.mock(RealmService.class);
PowerMockito.when(serviceRefHolder.getRealmService()).thenReturn(realmService);
UserRealm realm = Mockito.mock(UserRealm.class);
PowerMockito.when(realmService.getTenantUserRealm(TENANT_ID)).thenReturn(realm);
PowerMockito.doNothing().when(RegistryPersistenceUtil.class, "loadloadTenantAPIRXT", Mockito.any(String.class), Mockito.any(Integer.class));
Mockito.when(context.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(context.getTenantId()).thenReturn(TENANT_ID);
APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(tenantManager, registryService);
// return null artifact because we are not testing artifact related params. this is only to get the registry obj
GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(Mockito.any(Registry.class), Mockito.any(String.class))).thenReturn(artifactManager);
Mockito.when(artifactManager.getGenericArtifact(Mockito.any(String.class))).thenReturn(null);
// trigger registry object creation. access super tenant api
UserContext ctx = new UserContext("user", new Organization(TENANT_DOMAIN), null, null);
apiPersistenceInstance.searchAPIsForDevPortal(new Organization(SUPER_TENANT_DOMAIN), "", 0, 10, ctx);
// check whether super tenant's system registy is accessed
Mockito.verify(registryService, times(1)).getGovernanceSystemRegistry((SUPER_TENANT_ID));
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class SAMLGroupIDExtractorImplTest method getGroupingIdentifierListTestCase.
@Test
public void getGroupingIdentifierListTestCase() throws ParserConfigurationException, IOException, SAXException, UnmarshallingException, UserStoreException {
String claim = "http://wso2.org/claims/organization";
String organizationValue = "organization";
SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();
Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
Mockito.when(documentBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilder);
Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).thenReturn(document);
Mockito.when(document.getDocumentElement()).thenReturn(element);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
Response response = Mockito.mock(Response.class);
List<Assertion> assertion = new ArrayList();
Subject subject = Mockito.mock(Subject.class);
NameID nameID = Mockito.mock(NameID.class);
Assertion assertion1 = Mockito.mock(Assertion.class);
assertion.add(assertion1);
Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
Mockito.when(response.getAssertions()).thenReturn(assertion);
Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
Mockito.when(subject.getNameID()).thenReturn(nameID);
Mockito.when(nameID.getValue()).thenReturn("user");
System.setProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION, "true");
APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).thenReturn("http://wso2.org/claims/organization");
System.setProperty("carbon.home", "");
PrivilegedCarbonContext carbonContext;
carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()).thenReturn(-1234);
PowerMockito.doNothing().when(carbonContext).setTenantDomain("carbon.super", true);
AttributeStatement mockAttributeStatement = PowerMockito.mock(AttributeStatement.class);
List<AttributeStatement> attributeStatementList = Collections.singletonList(mockAttributeStatement);
PowerMockito.when(assertion1.getAttributeStatements()).thenReturn(attributeStatementList);
Attribute mockAttribute = PowerMockito.mock(Attribute.class);
List<Attribute> attributesList = Collections.singletonList(mockAttribute);
PowerMockito.when(mockAttributeStatement.getAttributes()).thenReturn(attributesList);
XMLObject rawAttribute = PowerMockito.mock(XMLObject.class);
PowerMockito.when(rawAttribute.toString()).thenReturn(organizationValue);
List<XMLObject> mockedAttributeValues = Collections.singletonList(rawAttribute);
AttributedStringImpl mockedAttributedStringImpl = new AttributedStringImpl("nameSpaceURI", "elementLocalName", "namespacePrefix");
String sampleAttrValue = "MockedAuthParamSampleAttribute";
mockedAttributedStringImpl.setValue(sampleAttrValue);
List<XMLObject> mockedXSSAttributeValues = Collections.singletonList((XMLObject) mockedAttributedStringImpl);
XSAnyImpl mockedXSAnyImpl = Mockito.mock(XSAnyImpl.class);
PowerMockito.when(mockedXSAnyImpl.getTextContent()).thenReturn(sampleAttrValue);
List<XMLObject> mockedXSAnyImplAttributeValues = Collections.singletonList((XMLObject) mockedXSAnyImpl);
List<XMLObject> multiMockedAttributeValues = Arrays.asList(rawAttribute, PowerMockito.mock(XMLObject.class));
AuthenticatorsConfiguration.AuthenticatorConfig mockedAuthenticatorConfig = Mockito.mock(AuthenticatorsConfiguration.AuthenticatorConfig.class);
PowerMockito.when(mockAttribute.getAttributeValues()).thenReturn(mockedAttributeValues, multiMockedAttributeValues, mockedXSSAttributeValues, mockedXSAnyImplAttributeValues);
PowerMockito.mockStatic(AuthenticatorsConfiguration.class);
AuthenticatorsConfiguration mockedAuthenticatorsConfiguration = PowerMockito.mock(AuthenticatorsConfiguration.class);
PowerMockito.when(AuthenticatorsConfiguration.getInstance()).thenReturn(mockedAuthenticatorsConfiguration);
Map<String, String> mockedConfigParameters = new HashMap<String, String>();
mockedConfigParameters.put(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE, claim);
PowerMockito.when(mockedAuthenticatorConfig.getParameters()).thenReturn(mockedConfigParameters);
PowerMockito.when(mockedAuthenticatorsConfiguration.getAuthenticatorConfig(APIConstants.SAML2_SSO_AUTHENTICATOR_NAME)).thenReturn(mockedAuthenticatorConfig);
PowerMockito.when(mockAttribute.getName()).thenReturn(claim);
String[] organizations = samlGroupIDExtractor.getGroupingIdentifierList("test");
Assert.assertEquals(organizationValue, organizations[0]);
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class ApplicationThrottleController method createThrottleContext.
private static ThrottleContext createThrottleContext(MessageContext synCtx, ThrottleDataHolder dataHolder, String applicationId, String policyKeyApplication) {
// Object entryValue = synCtx.getEntry(APPLICATION_THROTTLE_POLICY_KEY);
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
// extract the subscriber username from the auth Context
String subscriber = authContext.getSubscriber();
// get the tenant Domain from the subscriber
String tenantDomain = MultitenantUtils.getTenantDomain(subscriber);
int tenantId;
// get the tenant domain id from the tenant domain name
try {
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
handleException("Unable to Find the tenant ID using tenant: " + tenantDomain, e);
return null;
}
Object entryValue = lookup(policyKeyApplication, tenantId);
if (entryValue == null || !(entryValue instanceof OMElement)) {
handleException("Unable to load throttling policy using key: " + policyKeyApplication);
}
try {
Throttle throttle = ThrottleFactory.createMediatorThrottle(PolicyEngine.getPolicy((OMElement) entryValue));
ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
dataHolder.addThrottleContext(applicationId, context);
return context;
} catch (ThrottleException e) {
handleException("Error processing the throttling policy", e);
}
return null;
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class UserPostSelfRegistrationHandler method executeUserRegistrationWorkflow.
/**
* This method adds new role to the existing user roles
* @param tenantDomain tenant domain extracted from the event
* @param userName username extracted from the event
* @throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException when unable to retrieve
* userStoreManager instance
*/
private void executeUserRegistrationWorkflow(String tenantDomain, String userName) throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException {
try {
// Realm service is used for user management tasks
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
UserStoreManager userStoreManager;
try {
userStoreManager = realmService.getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getUserStoreManager();
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
}
// Start a tenant flow
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
carbonContext.setTenantDomain(tenantDomain);
if (userStoreManager.isExistingUser(userName)) {
List<String> roleList = asList(userStoreManager.getRoleListOfUser(userName));
// User should have selfSignup role. Checking whether the user is in the new role
if (roleList.contains(SELF_SIGNUP_ROLE) && !roleList.contains(SUBSCRIBER_ROLE)) {
WorkflowExecutor userSignUpWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
// initiate a new signup workflow
WorkflowDTO signUpWFDto = new WorkflowDTO();
signUpWFDto.setWorkflowReference(userName);
signUpWFDto.setStatus(WorkflowStatus.CREATED);
signUpWFDto.setCreatedTime(System.currentTimeMillis());
signUpWFDto.setTenantDomain(tenantDomain);
signUpWFDto.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
signUpWFDto.setExternalWorkflowReference(userSignUpWFExecutor.generateUUID());
signUpWFDto.setWorkflowType(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
signUpWFDto.setCallbackUrl(userSignUpWFExecutor.getCallbackURL());
userSignUpWFExecutor.execute(signUpWFDto);
}
}
} catch (UserStoreException | WorkflowException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
} finally {
Utils.clearArbitraryProperties();
PrivilegedCarbonContext.endTenantFlow();
}
}
use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.
the class WorkflowExecutorFactoryTest method init.
@Before
public void init() {
System.setProperty(CARBON_HOME, "");
carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
PowerMockito.when(carbonContext.getTenantDomain()).thenReturn(tenantDomain);
PowerMockito.when(carbonContext.getTenantId()).thenReturn(tenantID);
cache = Mockito.mock(Cache.class);
CacheManager cacheManager = Mockito.mock(CacheManager.class);
PowerMockito.mockStatic(Caching.class);
Mockito.when(Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)).thenReturn(cacheManager);
Mockito.when(cacheManager.getCache(APIConstants.WORKFLOW_CACHE_NAME)).thenReturn(cache);
tenantWorkflowConfigHolder = Mockito.mock(TenantWorkflowConfigHolder.class);
workflowExecutorFactory = WorkflowExecutorFactory.getInstance();
}
Aggregations