org.apache.ranger.plugin.model.RangerPolicy Java Examples

The following examples show how to use org.apache.ranger.plugin.model.RangerPolicy. 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: RangerPolicyEnginePerformanceTest.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void policyEngineTest() throws InterruptedException {
	List<RangerAccessRequest> requests = requestsCache.getUnchecked(concurrency);
	ServicePolicies servicePolicies = servicePoliciesCache.getUnchecked(numberOfPolicies);
	RangerPluginContext pluginContext = new RangerPluginContext(new RangerPluginConfig("hive", null, "perf-test", "cl1", "on-prem", RangerPolicyFactory.createPolicyEngineOption()));
	final RangerPolicyEngineImpl rangerPolicyEngine = new RangerPolicyEngineImpl(servicePolicies, pluginContext, null);

	for (int iterations = 0; iterations < WARM_UP__ITERATIONS; iterations++) {
		// using return value of 'isAccessAllowed' with a cheap operation: System#identityHashCode so JIT wont remove it as dead code
		System.identityHashCode(rangerPolicyEngine.evaluatePolicies(requests.get(iterations % concurrency), RangerPolicy.POLICY_TYPE_ACCESS, null));
		PerfDataRecorder.clearStatistics();
	}

	final CountDownLatch latch = new CountDownLatch(concurrency);
	for (int i = 0; i < concurrency; i++) {
		final RangerAccessRequest rangerAccessRequest = requests.get(i);
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.identityHashCode(rangerPolicyEngine.evaluatePolicies(rangerAccessRequest, RangerPolicy.POLICY_TYPE_ACCESS, null));
				latch.countDown();
			}
		}, String.format("Client #%s", i)).start();
	}
	latch.await();
}
 
Example #2
Source File: TestPublicAPIsv2.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test18getPolicyByName() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	RangerPolicy rangerPolicy = rangerPolicy();
	RangerService rangerService = rangerService();
	String serviceName = rangerService.getName();
	String policyName = rangerPolicy.getName();
	List<RangerPolicy> policies = new ArrayList<RangerPolicy>();
	policies.add(rangerPolicy);
	Mockito.when(serviceREST.getPolicies((SearchFilter) Mockito.any())).thenReturn(policies);
	RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicyByName(serviceName, policyName, request);
	Assert.assertNotNull(dbRangerPolicy);
	Assert.assertEquals(dbRangerPolicy, rangerPolicy);
	Assert.assertEquals(dbRangerPolicy.getId(),
			rangerPolicy.getId());
	Assert.assertEquals(dbRangerPolicy.getName(),
			rangerPolicy.getName());
	Mockito.verify(serviceREST).getPolicies((SearchFilter) Mockito.any());
}
 
Example #3
Source File: RangerPolicyRepository.java    From ranger with Apache License 2.0 6 votes vote down vote up
private boolean isPolicyNeedsPruning(RangerPolicy policy, final String componentType) {

        normalizeAndPrunePolicyItems(policy.getPolicyItems(), componentType);
        normalizeAndPrunePolicyItems(policy.getDenyPolicyItems(), componentType);
        normalizeAndPrunePolicyItems(policy.getAllowExceptions(), componentType);
        normalizeAndPrunePolicyItems(policy.getDenyExceptions(), componentType);
        normalizeAndPrunePolicyItems(policy.getDataMaskPolicyItems(), componentType);
        normalizeAndPrunePolicyItems(policy.getRowFilterPolicyItems(), componentType);

        if (!policy.getIsAuditEnabled() &&
                CollectionUtils.isEmpty(policy.getPolicyItems()) &&
                CollectionUtils.isEmpty(policy.getDenyPolicyItems()) &&
                CollectionUtils.isEmpty(policy.getAllowExceptions()) &&
                CollectionUtils.isEmpty(policy.getDenyExceptions()) &&
                CollectionUtils.isEmpty(policy.getDataMaskPolicyItems()) &&
                CollectionUtils.isEmpty(policy.getRowFilterPolicyItems())) {
            return true;
        } else {
            return false;
        }
    }
 
Example #4
Source File: TestServiceDBStore.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test32getServicePolicies() throws Exception {
	SearchFilter filter = new SearchFilter();
	filter.setParam(SearchFilter.POLICY_NAME, "policyName");
	filter.setParam(SearchFilter.SERVICE_NAME, "serviceName");

	XXService xService = xService();
	XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
	Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
	Mockito.when(xServiceDao.getById(Id)).thenReturn(xService);

	thrown.expect(Exception.class);
	List<RangerPolicy> dbRangerPolicy = serviceDBStore.getServicePolicies(
			Id, filter);
       Assert.assertFalse(dbRangerPolicy.isEmpty());
	Mockito.verify(daoManager).getXXService();
}
 
Example #5
Source File: RangerServiceSolr.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public List<RangerPolicy> getDefaultRangerPolicies() throws Exception {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> RangerServiceSolr.getDefaultRangerPolicies()");
	}

	List<RangerPolicy> ret = super.getDefaultRangerPolicies();
	for (RangerPolicy defaultPolicy : ret) {
		if (defaultPolicy.getName().contains("all") && StringUtils.isNotBlank(lookUpUser)) {
			RangerPolicyItem policyItemForLookupUser = new RangerPolicyItem();
			policyItemForLookupUser.setUsers(Collections.singletonList(lookUpUser));
			policyItemForLookupUser.setAccesses(Collections.singletonList(new RangerPolicyItemAccess(ACCESS_TYPE_QUERY)));
			policyItemForLookupUser.setDelegateAdmin(false);
			defaultPolicy.getPolicyItems().add(policyItemForLookupUser);
		}
	}

	if (LOG.isDebugEnabled()) {
           LOG.debug("<== RangerServiceSolr.getDefaultRangerPolicies()");
       }
	return ret;
}
 
Example #6
Source File: PerfTestEngine.java    From ranger with Apache License 2.0 6 votes vote down vote up
public RangerAccessResult execute(final RangerAccessRequest request) {

		if (LOG.isDebugEnabled()) {
			LOG.debug("==> execute(" + request + ")");
		}

		RangerAccessResult ret = null;

		if (policyEvaluationEngine != null) {

			ret = policyEvaluationEngine.evaluatePolicies(request, RangerPolicy.POLICY_TYPE_ACCESS, null);

			if (LOG.isDebugEnabled()) {
				LOG.debug("Executed request = {" + request + "}, result={" + ret + "}");
			}
		} else {
			LOG.error("Error executing request: PolicyEngine is null!");
		}

		if (LOG.isDebugEnabled()) {
			LOG.debug("<== execute(" + request + ") : " + ret);
		}

		return ret;
	}
 
Example #7
Source File: TestRangerPolicyServiceBase.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test1mapViewToEntityBean() {
	XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
	XXService xService = Mockito.mock(XXService.class);
	RangerPolicy rangerPolicy = rangerPolicy();
	XXPolicy policy = policy();
	int OPERATION_CONTEXT = 0;

	Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
	Mockito.when(xServiceDao.findByName(rangerPolicy.getService()))
			.thenReturn(xService);

	XXPolicy dbPolicy = policyService.mapViewToEntityBean(rangerPolicy,
			policy, OPERATION_CONTEXT);
	Assert.assertNotNull(dbPolicy);
	Assert.assertEquals(dbPolicy.getId(), policy.getId());
	Assert.assertEquals(dbPolicy.getGuid(), policy.getGuid());
	Assert.assertEquals(dbPolicy.getName(), policy.getName());
	Assert.assertEquals(dbPolicy.getAddedByUserId(),
			policy.getAddedByUserId());
	Assert.assertEquals(dbPolicy.getIsEnabled(), policy.getIsEnabled());
	Assert.assertEquals(dbPolicy.getVersion(), policy.getVersion());
	Assert.assertEquals(dbPolicy.getDescription(), policy.getDescription());

	Mockito.verify(daoManager).getXXService();
}
 
Example #8
Source File: RangerGaianAuthorizer.java    From egeria with Apache License 2.0 6 votes vote down vote up
private boolean addCellValueTransformerAndCheckIfTransformed(QueryContext queryContext, String columnName) {

        logger.logDetail("==> addCellValueTransformerAndCheckIfTransformed(queryContext=" + queryContext + ", " + columnName + ")");
        String columnTransformer = columnName;
        List<String> columnTransformers = queryContext.getColumnTransformers();
        RangerAccessResult result = getRangerDataMaskResult(queryContext, columnName);
        boolean isDataMaskEnabled = isDataMaskEnabled(result);

        if (isDataMaskEnabled) {
            String transformer = getTransformer(result);
            String maskType = result.getMaskType();

            if (StringUtils.equalsIgnoreCase(maskType, RangerPolicy.MASK_TYPE_NULL)) {
                columnTransformer = NULL_MASK_TYPE;
            } else if (StringUtils.equalsIgnoreCase(maskType, RangerPolicy.MASK_TYPE_CUSTOM)) {
                columnTransformer = getCustomMaskType(columnName, result);
            } else if (StringUtils.isNotEmpty(transformer)) {
                columnTransformer = transformer.replace("{col}", columnName);
            }
        }

        columnTransformers.add(columnTransformer);
        logger.logDetail("<== addCellValueTransformerAndCheckIfTransformed(queryContext=" + queryContext + ", " + columnName + "): " + isDataMaskEnabled);

        return isDataMaskEnabled;
    }
 
Example #9
Source File: TestServiceREST.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test23getServicePoliciesByName() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	RangerPolicy rangerPolicy = rangerPolicy();

	List<RangerPolicy> ret  = Mockito.mock(List.class);
	SearchFilter filter = new SearchFilter();
	filter.setParam(SearchFilter.POLICY_NAME, "policyName");
	filter.setParam(SearchFilter.SERVICE_NAME, "serviceName");
	Mockito.when(
			searchUtil.getSearchFilter(request, policyService.sortFields))
			.thenReturn(filter);

	Mockito.when(
			svcStore.getServicePolicies(rangerPolicy.getName(),
					filter)).thenReturn(ret);

	RangerPolicyList dbRangerPolicy = serviceREST.getServicePoliciesByName(
			rangerPolicy.getName(), request);
	Assert.assertNotNull(dbRangerPolicy);
}
 
Example #10
Source File: TestPublicAPIsv2.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test26getPolicies() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	RangerPolicyList policyList = Mockito.mock(RangerPolicyList.class);
	List<RangerPolicy> rangerPolicies = new ArrayList<RangerPolicy>();
	RangerPolicy rangerpolicy1 = rangerPolicy();
	RangerPolicy rangerpolicy2 = rangerPolicy1();
	rangerPolicies.add(rangerpolicy1);
	rangerPolicies.add(rangerpolicy2);
	Mockito.when(serviceREST.getPolicies(request)).thenReturn(policyList);
	Mockito.when(policyList.getPolicies()).thenReturn(rangerPolicies);
	List<RangerPolicy> dbRangerPolicies = publicAPIsv2.getPolicies(request);
	Assert.assertNotNull(dbRangerPolicies);
	Assert.assertEquals(dbRangerPolicies.size(), rangerPolicies.size());
	Mockito.verify(serviceREST).getPolicies(request);
}
 
Example #11
Source File: AssetREST.java    From ranger with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/resources")
@Produces({ "application/xml", "application/json" })
public VXResource createXResource(VXResource vXResource) {
	if(logger.isDebugEnabled()) {
		logger.debug("==> AssetREST.createXResource(" + vXResource + ")");
	}

	RangerService service = serviceREST.getService(vXResource.getAssetId());
	RangerPolicy  policy  = serviceUtil.toRangerPolicy(vXResource, service);

	RangerPolicy createdPolicy = serviceREST.createPolicy(policy, null);

	VXResource ret = serviceUtil.toVXResource(createdPolicy, service);

	if(logger.isDebugEnabled()) {
		logger.debug("<== AssetREST.createXResource(" + vXResource + "): " + ret);
	}

	return ret;
}
 
Example #12
Source File: RangerPolicyValidator.java    From ranger with Apache License 2.0 6 votes vote down vote up
boolean isValidResources(RangerPolicy policy, final List<ValidationFailureDetails> failures, Action action,
		boolean isAdmin, final RangerServiceDef serviceDef) {
	
	if(LOG.isDebugEnabled()) {
		LOG.debug(String.format("==> RangerPolicyValidator.isValidResources(%s, %s, %s, %s, %s)", policy, failures, action, isAdmin, serviceDef));
	}
	
	boolean valid = true;
	Map<String, RangerPolicyResource> resourceMap = policy.getResources();
	if (resourceMap != null) { // following checks can't be done meaningfully otherwise
		valid = isPolicyResourceUnique(policy, failures, action) && valid;
		if (serviceDef != null) { // following checks can't be done meaningfully otherwise
			valid = isValidResourceNames(policy, failures, serviceDef) && valid;
			valid = isValidResourceValues(resourceMap, failures, serviceDef) && valid;
			valid = isValidResourceFlags(resourceMap, failures, serviceDef.getResources(), serviceDef.getName(), policy.getName(), isAdmin) && valid;
		}
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug(String.format("<== RangerPolicyValidator.isValidResources(%s, %s, %s, %s, %s): %s", policy, failures, action, isAdmin, serviceDef, valid));
	}
	return valid;
}
 
Example #13
Source File: RangerBaseService.java    From ranger with Apache License 2.0 6 votes vote down vote up
private RangerPolicy.RangerPolicyItem createDefaultPolicyItem(Map<String, RangerPolicy.RangerPolicyResource> policyResources) throws Exception {

		if (LOG.isDebugEnabled()) {
			LOG.debug("==> RangerBaseService.createDefaultPolicyItem()");
		}

		RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();

		policyItem.setUsers(getUserList());
		policyItem.setGroups(getGroupList());
		List<RangerPolicy.RangerPolicyItemAccess> accesses = getAllowedAccesses(policyResources);
		policyItem.setAccesses(accesses);

		policyItem.setDelegateAdmin(true);

		if (LOG.isDebugEnabled()) {
			LOG.debug("<== RangerBaseService.createDefaultPolicyItem(): " + policyItem );
		}
		return policyItem;
	}
 
Example #14
Source File: RangerOptimizedPolicyEvaluator.java    From ranger with Apache License 2.0 6 votes vote down vote up
private void preprocessPolicyItems(List<? extends RangerPolicy.RangerPolicyItem> policyItems) {
    if(CollectionUtils.isNotEmpty(policyItems)) {
     for (RangerPolicy.RangerPolicyItem item : policyItems) {
         delegateAdmin = delegateAdmin || item.getDelegateAdmin();

         List<RangerPolicy.RangerPolicyItemAccess> policyItemAccesses = item.getAccesses();
         for(RangerPolicy.RangerPolicyItemAccess policyItemAccess : policyItemAccesses) {

             if (policyItemAccess.getIsAllowed()) {
                 String accessType = policyItemAccess.getType();
                 accessPerms.add(accessType);
             }
         }

         roles.addAll(item.getRoles());
         groups.addAll(item.getGroups());
         users.addAll(item.getUsers());

     }
    }
}
 
Example #15
Source File: RangerPolicyRetriever.java    From ranger with Apache License 2.0 6 votes vote down vote up
public List<RangerPolicy> getServicePolicies(Long serviceId) {
	List<RangerPolicy> ret = null;

	if(serviceId != null) {
		XXService xService = getXXService(serviceId);

		if(xService != null) {
			ret = getServicePolicies(xService);
		} else {
			if(LOG.isDebugEnabled()) {
				LOG.debug("RangerPolicyRetriever.getServicePolicies(serviceId=" + serviceId + "): service not found");
			}
		}
	}

	return ret;
}
 
Example #16
Source File: TestRangerValidator.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public final void test_getPoliciesForResourceSignature() throws Exception {
	// return null if store returns null or throws an exception
	String hexSignature = "aSignature";
	String serviceName = "service-name";
	boolean isPolicyEnabled = true;
	when(_store.getPoliciesByResourceSignature(serviceName, hexSignature, isPolicyEnabled)).thenReturn(null);
	Assert.assertNull(_validator.getPoliciesForResourceSignature(serviceName, hexSignature));
	when(_store.getPoliciesByResourceSignature(serviceName, hexSignature, isPolicyEnabled)).thenThrow(new Exception());
	Assert.assertNull(_validator.getPoliciesForResourceSignature(serviceName, hexSignature));

	// what ever store returns should come back
	hexSignature = "anotherSignature";
	List<RangerPolicy> policies = new ArrayList<>();
	RangerPolicy policy1 = mock(RangerPolicy.class);
	policies.add(policy1);
	RangerPolicy policy2 = mock(RangerPolicy.class);
	policies.add(policy2);
	when(_store.getPoliciesByResourceSignature(serviceName, hexSignature, isPolicyEnabled)).thenReturn(policies);
	List<RangerPolicy> result = _validator.getPoliciesForResourceSignature(serviceName, hexSignature);
	Assert.assertTrue(result.contains(policy1) && result.contains(policy2));
}
 
Example #17
Source File: PublicAPIsv2.java    From ranger with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/api/service/{servicename}/policy/{policyname}")
@Produces({ "application/json", "application/xml" })
public RangerPolicy updatePolicyByName(RangerPolicy policy,
                                               @PathParam("servicename") String serviceName,
                                               @PathParam("policyname") String policyName,
                                               @Context HttpServletRequest request) {
	if (policy.getService() == null || !policy.getService().equals(serviceName)) {
		throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "service name mismatch", true);
	}
	RangerPolicy oldPolicy = getPolicyByName(serviceName, policyName, request);

	// ignore policy.id - if specified. Retrieve using the given serviceName+policyName and use id from the retrieved object
	policy.setId(oldPolicy.getId());
	if(StringUtils.isEmpty(policy.getGuid())) {
		policy.setGuid(oldPolicy.getGuid());
	}
	if(StringUtils.isEmpty(policy.getName())) {
		policy.setName(StringUtils.trim(oldPolicy.getName()));
	}

	return serviceREST.updatePolicy(policy);
}
 
Example #18
Source File: RangerResourceACLs.java    From ranger with Apache License 2.0 6 votes vote down vote up
public void setGroupAccessInfo(String groupName, String accessType, Integer access, RangerPolicy policy) {
	Map<String, AccessResult> groupAccessInfo = groupACLs.get(groupName);

	if (groupAccessInfo == null) {
		groupAccessInfo = new HashMap<>();

		groupACLs.put(groupName, groupAccessInfo);
	}

	AccessResult accessResult = groupAccessInfo.get(accessType);

	if (accessResult == null) {
		accessResult = new AccessResult(access, policy);

		groupAccessInfo.put(accessType, accessResult);
	} else {
		accessResult.setResult(access);
		accessResult.setPolicy(policy);
	}
}
 
Example #19
Source File: RangerPolicyRetriever.java    From ranger with Apache License 2.0 6 votes vote down vote up
private void getPolicyLabels(RangerPolicy ret) {
	List<String> xPolicyLabels = new ArrayList<String>();
	if (iterPolicyLabels != null) {
		while (iterPolicyLabels.hasNext()) {
			XXPolicyLabelMap xPolicyLabel = iterPolicyLabels.next();
			if (xPolicyLabel.getPolicyId().equals(ret.getId())) {
				String policyLabel = lookupCache.getPolicyLabelName(xPolicyLabel.getPolicyLabelId());
				if (policyLabel != null) {
					xPolicyLabels.add(policyLabel);
				}
				ret.setPolicyLabels(xPolicyLabels);
			} else {
				if (iterPolicyLabels.hasPrevious()) {
					iterPolicyLabels.previous();
				}
				break;
			}
		}
	}
}
 
Example #20
Source File: RangerServiceDefHelper.java    From ranger with Apache License 2.0 5 votes vote down vote up
public Set<List<RangerResourceDef>> getResourceHierarchies(Integer policyType) {
	if(policyType == null) {
		policyType = RangerPolicy.POLICY_TYPE_ACCESS;
	}

	Set<List<RangerResourceDef>> ret = _hierarchies.get(policyType);

	if(ret == null) {
		ret = EMPTY_RESOURCE_HIERARCHY;
	}

	return ret;
}
 
Example #21
Source File: ServiceRESTUtil.java    From ranger with Apache License 2.0 5 votes vote down vote up
static void addPolicyItemForUser(RangerPolicy.RangerPolicyItem[] items, int typeOfItems, String user, RangerPolicy.RangerPolicyItem policyItem) {

		if (items[typeOfItems] == null) {
			RangerPolicy.RangerPolicyItem newItem = new RangerPolicy.RangerPolicyItem();
			newItem.getUsers().add(user);

			items[typeOfItems] = newItem;
		}

		addAccesses(items[typeOfItems], policyItem.getAccesses());

		if (policyItem.getDelegateAdmin()) {
			items[typeOfItems].setDelegateAdmin(Boolean.TRUE);
		}
	}
 
Example #22
Source File: RangerDefaultResourceMatcherTest.java    From ranger with Apache License 2.0 5 votes vote down vote up
MatcherWrapper(String policyValue, boolean exclude) {
    RangerPolicy.RangerPolicyResource policyResource = new RangerPolicy.RangerPolicyResource();
    policyResource.setIsExcludes(exclude);
    policyResource.setValues(Lists.newArrayList(policyValue));
    setPolicyResource(policyResource);

    if (policyValue.contains(WILDCARD_ASTERISK)) {
        this.optWildCard = true;
    }
    this.optIgnoreCase = false;
    init();
}
 
Example #23
Source File: TestPublicAPIsv2.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Test
public void test25deletePolicyByName() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	RangerPolicy rangerPolicy = rangerPolicy();
	String policyName = rangerPolicy.getName();
	RangerService rangerService = rangerService();
	String serviceName = rangerService.getName();
	List<RangerPolicy> policies = new ArrayList<RangerPolicy>();
	policies.add(rangerPolicy);
	Mockito.when(serviceREST.getPolicies((SearchFilter) Mockito.any())).thenReturn(policies);
	Mockito.doNothing().when(serviceREST).deletePolicy(Id);
	publicAPIsv2.deletePolicyByName(serviceName, policyName, request);
	Mockito.verify(serviceREST).getPolicies((SearchFilter) Mockito.any());
	Mockito.verify(serviceREST).deletePolicy(Id);
}
 
Example #24
Source File: TestRangerPolicyService.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Test
public void test2ValidateForUpdate() {
	RangerPolicy rangerPolicy = rangerPolicy();
	XXPolicy policy = policy();
	policyService.validateForUpdate(rangerPolicy, policy);

	Assert.assertNotNull(rangerPolicy);
}
 
Example #25
Source File: RangerServiceKMS.java    From ranger with Apache License 2.0 5 votes vote down vote up
private RangerPolicy.RangerPolicyItem createDefaultPolicyItem(List<RangerServiceDef.RangerAccessTypeDef> accessTypeDefs, List<String> users) throws Exception {

		if (LOG.isDebugEnabled()) {
			LOG.debug("==> RangerServiceTag.createDefaultPolicyItem()");
		}

		RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();

		policyItem.setUsers(users);

		List<RangerPolicy.RangerPolicyItemAccess> accesses = new ArrayList<RangerPolicy.RangerPolicyItemAccess>();

		for (RangerServiceDef.RangerAccessTypeDef accessTypeDef : accessTypeDefs) {
			RangerPolicy.RangerPolicyItemAccess access = new RangerPolicy.RangerPolicyItemAccess();
			access.setType(accessTypeDef.getName());
			access.setIsAllowed(true);
			accesses.add(access);
		}

		policyItem.setAccesses(accesses);
		policyItem.setDelegateAdmin(true);

		if (LOG.isDebugEnabled()) {
			LOG.debug("<== RangerServiceTag.createDefaultPolicyItem(): " + policyItem );
		}
		return policyItem;
	}
 
Example #26
Source File: RangerPolicyWithAssignedIdService.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
protected RangerPolicy populateViewBean(XXPolicyWithAssignedId xPolicy) {
	RangerPolicyRetriever retriever = new RangerPolicyRetriever(daoMgr);

	RangerPolicy vPolicy = retriever.getPolicy(xPolicy.getId());

	return vPolicy;
}
 
Example #27
Source File: PublicAPIs.java    From ranger with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/api/policy")
@Produces({ "application/json", "application/xml" })
public VXPolicy createPolicy(VXPolicy vXPolicy) {
	
	if(logger.isDebugEnabled()) {
		logger.debug("==> PublicAPIs.createPolicy()");
	}
	
	RangerService service = serviceREST.getServiceByName(vXPolicy.getRepositoryName());
	RangerPolicy  policy  = serviceUtil.toRangerPolicy(vXPolicy,service);

	VXPolicy ret = null;
	if(policy != null) {
		if(logger.isDebugEnabled()) {
			logger.debug("RANGERPOLICY: " + policy.toString());
		}
	
		RangerPolicy  createdPolicy = serviceREST.createPolicy(policy,null);

		ret = serviceUtil.toVXPolicy(createdPolicy, service);
	}
	
	if(logger.isDebugEnabled()) {
		logger.debug("<== PublicAPIs.createPolicy(" + policy + "): " + ret);
	}

	return ret;
}
 
Example #28
Source File: TestPublicAPIs.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Test
public void test9updatePolicy() throws Exception {
	RangerPolicy policy = rangerPolicy();
	RangerService service = rangerService();
	VXPolicy vXPolicy = vXPolicy(policy, service);
	XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class);
	XXPolicy xXPolicy = policy();
	Mockito.when(daoMgr.getXXPolicy()).thenReturn(xXPolicyDao);
	Mockito.when(xXPolicyDao.getById(Id)).thenReturn(xXPolicy);
	Mockito.when(serviceREST.getServiceByName(vXPolicy.getRepositoryName())).thenReturn(service);
	Mockito.when(serviceUtil.toRangerPolicy(vXPolicy,service)).thenReturn(policy);
	Mockito.when(serviceREST.updatePolicy(policy)).thenReturn(policy);
	Mockito.when(serviceUtil.toVXPolicy(policy, service)).thenReturn(vXPolicy);
	VXPolicy dbVXPolicy = publicAPIs.updatePolicy(vXPolicy, Id);
	
	Assert.assertNotNull(dbVXPolicy);
	Assert.assertEquals(dbVXPolicy, vXPolicy);
	Assert.assertEquals(dbVXPolicy.getId(),
			vXPolicy.getId());
	Assert.assertEquals(dbVXPolicy.getRepositoryName(),
			vXPolicy.getRepositoryName());
	Mockito.verify(serviceREST).updatePolicy(policy);
	Mockito.verify(serviceREST).getServiceByName(vXPolicy.getRepositoryName());
	Mockito.verify(serviceUtil).toVXPolicy(policy, service);
	Mockito.verify(serviceUtil).toRangerPolicy(vXPolicy,service);
	Mockito.verify(daoMgr).getXXPolicy();
	Mockito.verify(xXPolicyDao).getById(Id);
}
 
Example #29
Source File: TestXUserMgr.java    From ranger with Apache License 2.0 5 votes vote down vote up
private RangerPolicy rangerPolicy() {
	List<RangerPolicyItemAccess> accesses = new ArrayList<RangerPolicyItemAccess>();
	List<String> users = new ArrayList<String>();
	List<String> groups = new ArrayList<String>();
	List<String> policyLabels = new ArrayList<String>();
	List<RangerPolicyItemCondition> conditions = new ArrayList<RangerPolicyItemCondition>();
	List<RangerPolicyItem> policyItems = new ArrayList<RangerPolicyItem>();
	RangerPolicyItem rangerPolicyItem = new RangerPolicyItem();
	rangerPolicyItem.setAccesses(accesses);
	rangerPolicyItem.setConditions(conditions);
	rangerPolicyItem.setGroups(groups);
	rangerPolicyItem.setUsers(users);
	rangerPolicyItem.setDelegateAdmin(false);

	policyItems.add(rangerPolicyItem);

	Map<String, RangerPolicyResource> policyResource = new HashMap<String, RangerPolicyResource>();
	RangerPolicyResource rangerPolicyResource = new RangerPolicyResource();
	rangerPolicyResource.setIsExcludes(true);
	rangerPolicyResource.setIsRecursive(true);
	rangerPolicyResource.setValue("1");
	rangerPolicyResource.setValues(users);
	RangerPolicy policy = new RangerPolicy();
	policy.setId(userId);
	policy.setCreateTime(new Date());
	policy.setDescription("policy");
	policy.setGuid("policyguid");
	policy.setIsEnabled(true);
	policy.setName("HDFS_1-1-20150316062453");
	policy.setUpdatedBy("Admin");
	policy.setUpdateTime(new Date());
	policy.setService("HDFS_1-1-20150316062453");
	policy.setIsAuditEnabled(true);
	policy.setPolicyItems(policyItems);
	policy.setResources(policyResource);
	policy.setPolicyLabels(policyLabels);
	return policy;
}
 
Example #30
Source File: TestServiceREST.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Test
public void test19getPolicyFalse() throws Exception {
	RangerPolicy rangerPolicy = rangerPolicy();
	Mockito.when(svcStore.getPolicy(rangerPolicy.getId())).thenReturn(
			rangerPolicy);
	String userName = "admin";

	Set<String> userGroupsList = new HashSet<String>();
	userGroupsList.add("group1");
	userGroupsList.add("group2");

	List<RangerAccessTypeDef> rangerAccessTypeDefList = new ArrayList<RangerServiceDef.RangerAccessTypeDef>();
	RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef();
	rangerAccessTypeDefObj.setLabel("Read");
	rangerAccessTypeDefObj.setName("read");
	rangerAccessTypeDefObj.setRbKeyLabel(null);
	rangerAccessTypeDefList.add(rangerAccessTypeDefObj);
	XXServiceDef xServiceDef = serviceDef();
	XXService xService = xService();
	XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class);
	XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
	Mockito.when(bizUtil.isAdmin()).thenReturn(true);
	Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName);
	Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
	Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService);
	Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao);
	Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef);
	RangerPolicy dbRangerPolicy = serviceREST.getPolicy(rangerPolicy
			.getId());
	Assert.assertNotNull(dbRangerPolicy);
	Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId());
	Mockito.verify(svcStore).getPolicy(rangerPolicy.getId());
}