Search in sources :

Example 6 with CarbonContext

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));
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Matchers.anyString(org.mockito.Matchers.anyString) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) CarbonContext(org.wso2.carbon.context.CarbonContext) UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 7 with CarbonContext

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]);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Attribute(org.opensaml.saml.saml2.core.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) XSAnyImpl(org.opensaml.core.xml.schema.impl.XSAnyImpl) AttributedStringImpl(org.opensaml.soap.wssecurity.impl.AttributedStringImpl) NameID(org.opensaml.saml.saml2.core.NameID) AuthenticatorsConfiguration(org.wso2.carbon.core.security.AuthenticatorsConfiguration) Assertion(org.opensaml.saml.saml2.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Subject(org.opensaml.saml.saml2.core.Subject) Response(org.opensaml.saml.saml2.core.Response) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 8 with CarbonContext

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;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) RealmService(org.wso2.carbon.user.core.service.RealmService) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Throttle(org.apache.synapse.commons.throttle.core.Throttle)

Example 9 with CarbonContext

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();
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) RealmService(org.wso2.carbon.user.core.service.RealmService) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 10 with CarbonContext

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();
}
Also used : CacheManager(javax.cache.CacheManager) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Cache(javax.cache.Cache) Before(org.junit.Before)

Aggregations

PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)28 RealmService (org.wso2.carbon.user.core.service.RealmService)15 CarbonContext (org.wso2.carbon.context.CarbonContext)9 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 UserRealm (org.wso2.carbon.user.core.UserRealm)6 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)6 ArrayList (java.util.ArrayList)5 Registry (org.wso2.carbon.registry.core.Registry)5 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 List (java.util.List)3 Log (org.apache.commons.logging.Log)3 LogFactory (org.apache.commons.logging.LogFactory)3 OAuthTokenInfo (org.wso2.carbon.apimgt.api.OAuthTokenInfo)3 APIConstants (org.wso2.carbon.apimgt.impl.APIConstants)3 APIUtil (org.wso2.carbon.apimgt.impl.utils.APIUtil)3 ServiceReferenceHolder (org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder)3 RestApiConstants (org.wso2.carbon.apimgt.rest.api.common.RestApiConstants)3