ranger-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mad...@apache.org
Subject incubator-ranger git commit: RANGER-360: added delegated-admin enforcement logic in Ranger REST APIs
Date Fri, 10 Apr 2015 05:14:12 GMT
Repository: incubator-ranger
Updated Branches:
  refs/heads/master d6797e40a -> 57625ff7a


RANGER-360: added delegated-admin enforcement logic in Ranger REST APIs


Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/57625ff7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/57625ff7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/57625ff7

Branch: refs/heads/master
Commit: 57625ff7a4ae92482cdf99b3e6b3d9c7b3ee108f
Parents: d6797e4
Author: Madhan Neethiraj <madhan@apache.org>
Authored: Thu Apr 9 01:20:16 2015 -0700
Committer: Madhan Neethiraj <madhan@apache.org>
Committed: Thu Apr 9 22:07:28 2015 -0700

----------------------------------------------------------------------
 .../policyengine/RangerAccessRequest.java       |   4 +
 .../policyengine/RangerAccessRequestImpl.java   |  22 +-
 .../plugin/policyengine/RangerPolicyDb.java     | 103 +++++++++
 .../policyengine/RangerPolicyDbCache.java       |  54 +++++
 .../plugin/policyengine/RangerPolicyEngine.java |   6 +-
 .../policyengine/RangerPolicyEngineImpl.java    |  44 ++--
 .../RangerPolicyEvaluatorFacade.java            |   7 +
 .../policyengine/RangerPolicyRepository.java    |   2 +-
 .../RangerDefaultPolicyEvaluator.java           | 152 +++++++++++--
 .../RangerOptimizedPolicyEvaluator.java         |  12 +-
 .../policyevaluator/RangerPolicyEvaluator.java  |   6 +
 .../RangerDefaultResourceMatcher.java           |   6 +-
 .../RangerPathResourceMatcher.java              |   6 +-
 .../ranger/plugin/util/PolicyRefresher.java     |  14 +-
 .../plugin/policyengine/TestPolicyDb.java       | 117 ++++++++++
 .../plugin/policyengine/TestPolicyEngine.java   |  14 +-
 .../policyengine/test_policydb_hdfs.json        | 218 +++++++++++++++++++
 .../authorization/hbase/TestPolicyEngine.java   |   6 +-
 .../org/apache/ranger/biz/RangerBizUtil.java    |  17 ++
 .../org/apache/ranger/rest/ServiceREST.java     | 112 +++++++++-
 20 files changed, 846 insertions(+), 76 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java
index 511896e..82a18fc 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java
@@ -28,6 +28,10 @@ public interface RangerAccessRequest {
 
 	String getAccessType();
 
+	boolean isAccessTypeAny();
+
+	boolean isAccessTypeDelegatedAdmin();
+
 	String getUser();
 
 	Set<String> getUserGroups();

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java
index 8ee6b77..e1326ea 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java
@@ -25,6 +25,7 @@ import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.ranger.authorization.utils.StringUtil;
 
 
@@ -41,6 +42,9 @@ public class RangerAccessRequestImpl implements RangerAccessRequest {
 	private String               sessionId       = null;
 	private Map<String, Object>  context         = null;
 
+	private boolean isAccessTypeAny            = false;
+	private boolean isAccessTypeDelegatedAdmin = false;
+
 	public RangerAccessRequestImpl() {
 		this(null, null, null, null);
 	}
@@ -116,12 +120,28 @@ public class RangerAccessRequestImpl implements RangerAccessRequest {
 		return context;
 	}
 
+	@Override
+	public boolean isAccessTypeAny() {
+		return isAccessTypeAny;
+	}
+
+	@Override
+	public boolean isAccessTypeDelegatedAdmin() {
+		return isAccessTypeDelegatedAdmin;
+	}
+
 	public void setResource(RangerAccessResource resource) {
 		this.resource = resource;
 	}
 
 	public void setAccessType(String accessType) {
-		this.accessType = accessType;
+		if (StringUtils.isEmpty(accessType)) {
+			accessType = RangerPolicyEngine.ANY_ACCESS;
+		}
+
+		this.accessType            = accessType;
+		isAccessTypeAny            = StringUtils.equals(accessType, RangerPolicyEngine.ANY_ACCESS);
+		isAccessTypeDelegatedAdmin = StringUtils.equals(accessType, RangerPolicyEngine.ADMIN_ACCESS);
 	}
 
 	public void setUser(String user) {

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDb.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDb.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDb.java
new file mode 100644
index 0000000..2f39d1d
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDb.java
@@ -0,0 +1,103 @@
+package org.apache.ranger.plugin.policyengine;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerServiceDef;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
+import org.apache.ranger.plugin.policyevaluator.RangerOptimizedPolicyEvaluator;
+import org.apache.ranger.plugin.policyevaluator.RangerPolicyEvaluator;
+import org.apache.ranger.plugin.util.ServicePolicies;
+
+
+public class RangerPolicyDb {
+	private static final Log LOG = LogFactory.getLog(RangerPolicyDb.class);
+
+	private final ServicePolicies             servicePolicies;
+	private final List<RangerPolicyEvaluator> policyEvaluators;
+
+	public RangerPolicyDb(ServicePolicies servicePolicies) {
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("==> RangerPolicyDb(" + servicePolicies + ")");
+		}
+
+		this.servicePolicies  = servicePolicies;
+		this.policyEvaluators = new ArrayList<RangerPolicyEvaluator>();
+
+		RangerServiceDef   serviceDef = servicePolicies.getServiceDef();
+		List<RangerPolicy> policies   = servicePolicies.getPolicies();
+
+		if(serviceDef != null && policies != null) {
+			for (RangerPolicy policy : policies) {
+				if (!policy.getIsEnabled()) {
+					continue;
+				}
+
+				RangerPolicyEvaluator evaluator = new RangerOptimizedPolicyEvaluator();
+
+				if (evaluator != null) {
+					evaluator.init(policy, serviceDef);
+
+					policyEvaluators.add(evaluator);
+				}
+			}
+		}
+
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("<== RangerPolicyDb(" + servicePolicies + ")");
+		}
+	}
+
+	public String getServiceName() {
+		return servicePolicies.getServiceName();
+	}
+
+	public long getPolicyVersion() {
+		Long policyVersion = servicePolicies.getPolicyVersion();
+
+		return policyVersion != null ? policyVersion.longValue() : -1;
+	}
+
+	public boolean isAccessAllowed(Map<String, RangerPolicyResource> resources, String user, Set<String> userGroups, String accessType) {
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("==> RangerPolicyDb.isAccessAllowed(" + resources + ", " + user + ", " + userGroups + ", " + accessType + ")");
+		}
+
+		boolean ret = false;
+
+		for(RangerPolicyEvaluator evaluator : policyEvaluators) {
+			ret = evaluator.isAccessAllowed(resources, user, userGroups, accessType);
+
+			if(ret) {
+				break;
+			}
+		}
+
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("<== RangerPolicyDb.isAccessAllowed(" + resources + ", " + user + ", " + userGroups + ", " + accessType + "): " + ret);
+		}
+
+		return ret;
+	}
+
+	public List<RangerPolicy> getAllowedPolicies(String user, Set<String> userGroups, String accessType) {
+		List<RangerPolicy> ret = new ArrayList<RangerPolicy>();
+
+		for(RangerPolicyEvaluator evaluator : policyEvaluators) {
+			RangerPolicy policy = evaluator.getPolicy();
+
+			boolean isAccessAllowed = isAccessAllowed(policy.getResources(), user, userGroups, accessType);
+
+			if(isAccessAllowed) {
+				ret.add(policy);
+			}
+		}
+
+		return ret;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDbCache.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDbCache.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDbCache.java
new file mode 100644
index 0000000..3b3cb96
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyDbCache.java
@@ -0,0 +1,54 @@
+package org.apache.ranger.plugin.policyengine;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.plugin.store.ServiceStore;
+import org.apache.ranger.plugin.util.ServicePolicies;
+
+public class RangerPolicyDbCache {
+	private static final Log LOG = LogFactory.getLog(RangerPolicyDbCache.class);
+
+	private static final RangerPolicyDbCache sInstance = new RangerPolicyDbCache();
+
+	private final Map<String, RangerPolicyDb> policyDbCache = Collections.synchronizedMap(new HashMap<String, RangerPolicyDb>());
+
+	public static RangerPolicyDbCache getInstance() {
+		return sInstance;
+	}
+
+	public RangerPolicyDb getPolicyDb(String serviceName, ServiceStore svcStore) {
+		RangerPolicyDb ret = null;
+
+		if(serviceName != null) {
+			ret = policyDbCache.get(serviceName);
+
+			long policyVersion = ret != null ? ret.getPolicyVersion() : -1;
+
+			if(svcStore != null) {
+				try {
+					ServicePolicies policies = svcStore.getServicePoliciesIfUpdated(serviceName, policyVersion);
+
+					if(policies != null) {
+						if(ret == null) {
+							ret = new RangerPolicyDb(policies);
+
+							policyDbCache.put(serviceName, ret);
+						} else if(policies.getPolicyVersion() != null && !policies.getPolicyVersion().equals(policyVersion)) {
+							ret = new RangerPolicyDb(policies);
+
+							policyDbCache.put(serviceName, ret);
+						}
+					}
+				} catch(Exception excp) {
+					LOG.error("getPolicyDbForService(" + serviceName + "): failed to get latest policies from service-store", excp);
+				}
+			}
+		}
+
+		return ret;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngine.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngine.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngine.java
index 2802d90..da83838 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngine.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngine.java
@@ -24,8 +24,8 @@ import java.util.List;
 
 import org.apache.ranger.plugin.audit.RangerAuditHandler;
 import org.apache.ranger.plugin.contextenricher.RangerContextEnricher;
-import org.apache.ranger.plugin.model.RangerPolicy;
 import org.apache.ranger.plugin.model.RangerServiceDef;
+import org.apache.ranger.plugin.util.ServicePolicies;
 
 public interface RangerPolicyEngine {
 	public static final String GROUP_PUBLIC   = "public";
@@ -39,7 +39,9 @@ public interface RangerPolicyEngine {
 
 	List<RangerContextEnricher> getContextEnrichers();
 
-	void setPolicies(String serviceName, RangerServiceDef serviceDef, List<RangerPolicy> policies);
+	void setPolicies(ServicePolicies policies);
+
+	ServicePolicies getPolicies();
 
 	void setDefaultAuditHandler(RangerAuditHandler auditHandler);
 

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngineImpl.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngineImpl.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngineImpl.java
index 5e9ca0c..f09ad70 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngineImpl.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEngineImpl.java
@@ -26,6 +26,7 @@ import org.apache.ranger.plugin.contextenricher.RangerContextEnricher;
 import org.apache.ranger.plugin.model.RangerPolicy;
 import org.apache.ranger.plugin.model.RangerServiceDef;
 import org.apache.ranger.plugin.policyevaluator.RangerPolicyEvaluator;
+import org.apache.ranger.plugin.util.ServicePolicies;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -35,7 +36,7 @@ import java.util.List;
 public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 	private static final Log LOG = LogFactory.getLog(RangerPolicyEngineImpl.class);
 
-	private String                 serviceName         = null;
+	private ServicePolicies        servicePolicies     = null;
 	private RangerPolicyRepository policyRepository    = null;
 	private RangerAuditHandler     defaultAuditHandler = null;
 
@@ -51,25 +52,31 @@ public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 
 	@Override
 	public String getServiceName() {
-		return serviceName;
+		RangerPolicyRepository policyRepository = this.policyRepository;
+
+		return policyRepository == null ? null : policyRepository.getServiceName();
 	}
 
 	@Override
 	public RangerServiceDef getServiceDef() {
-		RangerPolicyRepository policyRepository = getPolicyRepository();
+		RangerPolicyRepository policyRepository = this.policyRepository;
 
 		return policyRepository == null ? null : policyRepository.getServiceDef();
 	}
 
 	@Override
 	public List<RangerContextEnricher> getContextEnrichers() {
-		RangerPolicyRepository policyRepository = getPolicyRepository();
+		RangerPolicyRepository policyRepository = this.policyRepository;
 
 		return policyRepository == null ? null : policyRepository.getContextEnrichers();
 	}
 
 	@Override
-	public void setPolicies(String serviceName, RangerServiceDef serviceDef, List<RangerPolicy> policies) {
+	public void setPolicies(ServicePolicies servicePolicies) {
+		String             serviceName = servicePolicies != null ? servicePolicies.getServiceName() : null;
+		RangerServiceDef   serviceDef  = servicePolicies != null ? servicePolicies.getServiceDef() : null;
+		List<RangerPolicy> policies    = servicePolicies != null ? servicePolicies.getPolicies() : null;
+		
 		if(LOG.isDebugEnabled()) {
 			LOG.debug("==> RangerPolicyEngineImpl.setPolicies(" + serviceName + ", " + serviceDef + ", policies.count=" + (policies == null ? 0 : policies.size()) + ")");
 		}
@@ -78,8 +85,8 @@ public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 			RangerPolicyRepository policyRepository = new RangerPolicyRepository(serviceName);
 			policyRepository.init(serviceDef, policies);
 
-			this.serviceName = serviceName;
-			setPolicyRepository(policyRepository);
+			this.servicePolicies  = servicePolicies;
+			this.policyRepository = policyRepository;
 		} else {
 			LOG.error("RangerPolicyEngineImpl.setPolicies ->Invalid arguments: serviceName, serviceDef, or policies is null");
 		}
@@ -90,6 +97,11 @@ public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 	}
 
 	@Override
+	public ServicePolicies getPolicies() {
+		return servicePolicies;
+	}
+
+	@Override
 	public void setDefaultAuditHandler(RangerAuditHandler auditHandler) {
 		this.defaultAuditHandler = auditHandler;
 	}
@@ -101,9 +113,9 @@ public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 
 	@Override
 	public RangerAccessResult createAccessResult(RangerAccessRequest request) {
-		RangerPolicyRepository policyRepository = getPolicyRepository();
+		RangerPolicyRepository policyRepository = this.policyRepository;
 
-		return new RangerAccessResult(serviceName, policyRepository == null ? null : policyRepository.getServiceDef(), request);
+		return new RangerAccessResult(this.getServiceName(), policyRepository == null ? null : policyRepository.getServiceDef(), request);
 	}
 
 	@Override
@@ -167,7 +179,7 @@ public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 			LOG.debug("==> RangerPolicyEngineImpl.isAccessAllowedNoAudit(" + request + ")");
 		}
 
-		RangerPolicyRepository policyRepository = getPolicyRepository();
+		RangerPolicyRepository policyRepository = this.policyRepository;
 
 		RangerAccessResult ret = createAccessResult(request);
 
@@ -200,14 +212,6 @@ public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 		return ret;
 	}
 
-	private RangerPolicyRepository getPolicyRepository() {
-		return this.policyRepository;
-	}
-
-	private void setPolicyRepository(RangerPolicyRepository policyRepository) {
-		this.policyRepository = policyRepository;
-	}
-
 	@Override
 	public String toString( ) {
 		StringBuilder sb = new StringBuilder();
@@ -218,11 +222,11 @@ public class RangerPolicyEngineImpl implements RangerPolicyEngine {
 	}
 
 	public StringBuilder toString(StringBuilder sb) {
-		RangerPolicyRepository policyRepository = getPolicyRepository();
+		RangerPolicyRepository policyRepository = this.policyRepository;
 
 		sb.append("RangerPolicyEngineImpl={");
 
-		sb.append("serviceName={").append(serviceName).append("} ");
+		sb.append("serviceName={").append(this.getServiceName()).append("} ");
 		sb.append(policyRepository);
 
 		sb.append("}");

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEvaluatorFacade.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEvaluatorFacade.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEvaluatorFacade.java
index 755f553..862cd1a 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEvaluatorFacade.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyEvaluatorFacade.java
@@ -26,12 +26,14 @@ import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
 import org.apache.ranger.plugin.conditionevaluator.RangerConditionEvaluator;
 import org.apache.ranger.plugin.model.RangerPolicy;
 import org.apache.ranger.plugin.model.RangerServiceDef;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
 import org.apache.ranger.plugin.policyevaluator.RangerCachedPolicyEvaluator;
 import org.apache.ranger.plugin.policyevaluator.RangerDefaultPolicyEvaluator;
 import org.apache.ranger.plugin.policyevaluator.RangerOptimizedPolicyEvaluator;
 import org.apache.ranger.plugin.policyevaluator.RangerPolicyEvaluator;
 
 import java.util.Map;
+import java.util.Set;
 
 public class RangerPolicyEvaluatorFacade implements RangerPolicyEvaluator, Comparable<RangerPolicyEvaluatorFacade> {
     private static final Log LOG = LogFactory.getLog(RangerPolicyEvaluatorFacade.class);
@@ -96,6 +98,11 @@ public class RangerPolicyEvaluatorFacade implements RangerPolicyEvaluator, Compa
     }
 
     @Override
+    public boolean isAccessAllowed(Map<String, RangerPolicyResource> resources, String user, Set<String> userGroups, String accessType) {
+        return delegate.isAccessAllowed(resources, user, userGroups, accessType);
+    }
+
+    @Override
     public int compareTo(RangerPolicyEvaluatorFacade other) {
         if(LOG.isDebugEnabled()) {
             LOG.debug("==> RangerPolicyEvaluatorFacade.compareTo()");

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyRepository.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyRepository.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyRepository.java
index 154c6ea..b1d37ca 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyRepository.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerPolicyRepository.java
@@ -50,7 +50,7 @@ public class RangerPolicyRepository {
         super();
         this.serviceName = serviceName;
     }
-    String getRepositoryName() {
+    String getServiceName() {
         return serviceName;
     }
     List<RangerPolicyEvaluatorFacade> getPolicyEvaluators() {

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
index 3cdc5ea..052bb88 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
@@ -207,7 +207,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
 		return evaluator;
 	}
 
-	@Override
+    @Override
     public void evaluate(RangerAccessRequest request, RangerAccessResult result) {
         if (LOG.isDebugEnabled()) {
             LOG.debug("==> RangerDefaultPolicyEvaluator.evaluate(" + request + ", " + result + ")");
@@ -215,13 +215,6 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
         RangerPolicy policy = getPolicy();
 
         if (policy != null && request != null && result != null) {
-
-            String accessType = request.getAccessType();
-            if (StringUtils.isEmpty(accessType)) {
-                accessType = RangerPolicyEngine.ANY_ACCESS;
-            }
-            boolean isAnyAccess = StringUtils.equals(accessType, RangerPolicyEngine.ANY_ACCESS);
-
             boolean isMatchAttempted = false;
             boolean matchResult = false;
             boolean isHeadMatchAttempted = false;
@@ -236,7 +229,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
 
                 // Try head match only if match was not found and ANY access was requested
                 if (!matchResult) {
-                    if (isAnyAccess && !isHeadMatchAttempted) {
+                    if (request.isAccessTypeAny() && !isHeadMatchAttempted) {
                         headMatchResult = matchResourceHead(request.getResource());
                         isHeadMatchAttempted = true;
                     }
@@ -260,7 +253,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
                 // Try Head Match only if no match was found so far AND a head match was not attempted as part of evaluating
                 // Audit requirement
                 if (!matchResult) {
-                    if (isAnyAccess && !isHeadMatchAttempted) {
+                    if (request.isAccessTypeAny() && !isHeadMatchAttempted) {
                         headMatchResult = matchResourceHead(request.getResource());
 	                    isHeadMatchAttempted = true;
                     }
@@ -281,12 +274,6 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
         if(LOG.isDebugEnabled()) {
             LOG.debug("==> RangerDefaultPolicyEvaluator.evaluatePolicyItemsForAccess(" + request + ", " + result + ")");
         }
-        String accessType = request.getAccessType();
-        if (StringUtils.isEmpty(accessType)) {
-            accessType = RangerPolicyEngine.ANY_ACCESS;
-        }
-        boolean isAnyAccess = StringUtils.equals(accessType, RangerPolicyEngine.ANY_ACCESS);
-        boolean isAdminAccess = StringUtils.equals(accessType, RangerPolicyEngine.ADMIN_ACCESS);
 
         for (RangerPolicy.RangerPolicyItem policyItem : getPolicy().getPolicyItems()) {
 
@@ -298,7 +285,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
             // This is only for Grant and Revoke access requests sent by the component. For those cases
             // Our plugin will fill in the accessType as ADMIN_ACCESS.
 
-            if (isAdminAccess) {
+            if (request.isAccessTypeDelegatedAdmin()) {
                 if (policyItem.getDelegateAdmin()) {
                     result.setIsAllowed(true);
                     result.setPolicyId(getPolicy().getId());
@@ -312,7 +299,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
             }
 
             boolean accessAllowed = false;
-            if (isAnyAccess) {
+            if (request.isAccessTypeAny()) {
                 for (RangerPolicy.RangerPolicyItemAccess access : policyItem.getAccesses()) {
                     if (access.getIsAllowed()) {
                         accessAllowed = true;
@@ -320,7 +307,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
                     }
                 }
             } else {
-                RangerPolicy.RangerPolicyItemAccess access = getAccess(policyItem, accessType);
+                RangerPolicy.RangerPolicyItemAccess access = getAccess(policyItem, request.getAccessType());
 
                 if (access != null && access.getIsAllowed()) {
                     accessAllowed = true;
@@ -392,6 +379,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
 		return ret;
 	}
 
+	@Override
 	public boolean isSingleAndExactMatch(RangerAccessResource resource) {
 		if(LOG.isDebugEnabled()) {
 			LOG.debug("==> RangerDefaultPolicyEvaluator.isSingleAndExactMatch(" + resource + ")");
@@ -441,6 +429,22 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
 		return ret;
 	}
 
+	@Override
+	public boolean isAccessAllowed(Map<String, RangerPolicyResource> resources, String user, Set<String> userGroups, String accessType) {
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("==> RangerDefaultPolicyEvaluator.isAccessAllowed(" + resources + ", " + user + ", " + userGroups + ", " + accessType + ")");
+		}
+
+		boolean ret = isAccessAllowedNoCustomConditionEval(user, userGroups, accessType) && isMatch(resources);
+		
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("<== RangerDefaultPolicyEvaluator.isAccessAllowed(" + resources + ", " + user + ", " + userGroups + ", " + accessType + "): " + ret);
+		}
+
+		return ret;
+	}
+
+
 	protected boolean matchResourceHead(RangerAccessResource resource) {
 		if(LOG.isDebugEnabled()) {
 			LOG.debug("==> RangerDefaultPolicyEvaluator.matchResourceHead(" + resource + ")");
@@ -638,6 +642,116 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
 		return ret;
 	}
 
+	protected boolean isMatch(Map<String, RangerPolicyResource> resources) {
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("==> RangerDefaultPolicyEvaluator.isMatch(" + resources + ")");
+		}
+
+		boolean ret = false;
+
+		RangerServiceDef serviceDef = getServiceDef();
+
+		if(serviceDef != null && serviceDef.getResources() != null) {
+			Collection<String> resourceKeys = resources == null ? null : resources.keySet();
+			Collection<String> policyKeys   = matchers == null ? null : matchers.keySet();
+
+			boolean keysMatch = CollectionUtils.isEmpty(resourceKeys) || (policyKeys != null && policyKeys.containsAll(resourceKeys));
+
+			if(keysMatch) {
+				for(RangerResourceDef resourceDef : serviceDef.getResources()) {
+					String                resourceName   = resourceDef.getName();
+					RangerPolicyResource  resourceValues = resources == null ? null : resources.get(resourceName);
+					RangerResourceMatcher matcher        = matchers == null ? null : matchers.get(resourceName);
+
+					// when no value exists for a resourceName, consider it a match only if: policy doesn't have a matcher OR matcher allows no-value resource
+					if(resourceValues == null || CollectionUtils.isEmpty(resourceValues.getValues())) {
+						ret = matcher == null || matcher.isMatch(null);
+					} else if(matcher != null) {
+						for(String resourceValue : resourceValues.getValues()) {
+							ret = matcher.isMatch(resourceValue);
+
+							if(! ret) {
+								break;
+							}
+						}
+					}
+
+					if(! ret) {
+						break;
+					}
+				}
+			} else {
+				if(LOG.isDebugEnabled()) {
+					LOG.debug("isMatch(): keysMatch=false. resourceKeys=" + resourceKeys + "; policyKeys=" + policyKeys);
+				}
+			}
+		}
+
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("<== RangerDefaultPolicyEvaluator.isMatch(" + resources + "): " + ret);
+		}
+
+		return ret;
+	}
+
+	protected boolean isAccessAllowedNoCustomConditionEval(String user, Set<String> userGroups, String accessType) {
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("==> RangerDefaultPolicyEvaluator.isAccessAllowedNoCustomConditionEval(" + user + ", " + userGroups + ", " + accessType + ")");
+		}
+
+		boolean ret = false;
+
+		if (StringUtils.isEmpty(accessType)) {
+			accessType = RangerPolicyEngine.ANY_ACCESS;
+		}
+
+		boolean isAnyAccess   = StringUtils.equals(accessType, RangerPolicyEngine.ANY_ACCESS);
+		boolean isAdminAccess = StringUtils.equals(accessType, RangerPolicyEngine.ADMIN_ACCESS);
+
+		for (RangerPolicy.RangerPolicyItem policyItem : getPolicy().getPolicyItems()) {
+			if (isAdminAccess) {
+				if(! policyItem.getDelegateAdmin()) {
+					continue;
+				}
+			} else if (CollectionUtils.isEmpty(policyItem.getAccesses())) {
+				continue;
+			} else if (isAnyAccess) {
+				boolean accessAllowed = false;
+
+				for (RangerPolicy.RangerPolicyItemAccess access : policyItem.getAccesses()) {
+					if (access.getIsAllowed()) {
+						accessAllowed = true;
+						break;
+					}
+				}
+
+				if(! accessAllowed) {
+					continue;
+				}
+			} else {
+				RangerPolicy.RangerPolicyItemAccess access = getAccess(policyItem, accessType);
+				if (access == null || !access.getIsAllowed()) {
+					continue;
+				}
+			}
+
+			boolean isUserGroupMatch = matchUserGroup(policyItem, user, userGroups);
+
+			if (!isUserGroupMatch) {
+				continue;
+			}
+
+			ret = true;
+			break;
+		}
+
+		if(LOG.isDebugEnabled()) {
+			LOG.debug("<== RangerDefaultPolicyEvaluator.isAccessAllowedNoCustomConditionEval(" + user + ", " + userGroups + ", " + accessType + "): " + ret);
+		}
+
+		return ret;
+	}
+
 	public StringBuilder toString(StringBuilder sb) {
 		sb.append("RangerDefaultPolicyEvaluator={");
 

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerOptimizedPolicyEvaluator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerOptimizedPolicyEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerOptimizedPolicyEvaluator.java
index af24247..7ddd155 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerOptimizedPolicyEvaluator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerOptimizedPolicyEvaluator.java
@@ -20,7 +20,6 @@
 package org.apache.ranger.plugin.policyevaluator;
 
 import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.ranger.plugin.model.RangerPolicy;
@@ -198,22 +197,17 @@ public class RangerOptimizedPolicyEvaluator extends RangerDefaultPolicyEvaluator
         }
         return priorityLevel;
     }
-    @Override
+
+	@Override
     protected void evaluatePolicyItemsForAccess(RangerAccessRequest request, RangerAccessResult result) {
         if(LOG.isDebugEnabled()) {
             LOG.debug("==> RangerOptimizedPolicyEvaluator.evaluatePolicyItemsForAccess()");
         }
-        String accessType = request.getAccessType();
-        if (StringUtils.isEmpty(accessType)) {
-            accessType = RangerPolicyEngine.ANY_ACCESS;
-        }
-        boolean isAnyAccess = StringUtils.equals(accessType, RangerPolicyEngine.ANY_ACCESS);
-        boolean isAdminAccess = StringUtils.equals(accessType, RangerPolicyEngine.ADMIN_ACCESS);
 
         if (hasPublicGroup || users.contains(request.getUser()) || CollectionUtils.containsAny(groups, request.getUserGroups())) {
             // No need to reject based on users and groups
 
-            if (isAnyAccess || (isAdminAccess && delegateAdmin) || hasAllPerms || accessPerms.contains(accessType)) {
+            if (request.isAccessTypeAny() || (request.isAccessTypeDelegatedAdmin() && delegateAdmin) || hasAllPerms || accessPerms.contains(request.getAccessType())) {
                 // No need to reject based on aggregated access permissions
                 super.evaluatePolicyItemsForAccess(request, result);
             }

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyEvaluator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyEvaluator.java
index 35164b2..18ec248 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyEvaluator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyEvaluator.java
@@ -20,7 +20,11 @@
 package org.apache.ranger.plugin.policyevaluator;
 
 
+import java.util.Map;
+import java.util.Set;
+
 import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
 import org.apache.ranger.plugin.model.RangerServiceDef;
 import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
 import org.apache.ranger.plugin.policyengine.RangerAccessResult;
@@ -38,4 +42,6 @@ public interface RangerPolicyEvaluator {
 	boolean isMatch(RangerAccessResource resource);
 
 	boolean isSingleAndExactMatch(RangerAccessResource resource);
+
+	boolean isAccessAllowed(Map<String, RangerPolicyResource> resources, String user, Set<String> userGroups, String accessType);
 }

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerDefaultResourceMatcher.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerDefaultResourceMatcher.java b/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerDefaultResourceMatcher.java
index 8f9aea8..007fc42 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerDefaultResourceMatcher.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerDefaultResourceMatcher.java
@@ -37,7 +37,9 @@ public class RangerDefaultResourceMatcher extends RangerAbstractResourceMatcher
 
 		boolean ret = false;
 
-		if(resource != null) {
+		if(resource == null || isMatchAny) {
+			ret = isMatchAny;
+		} else {
 			if(optIgnoreCase) {
 				resource = resource.toLowerCase();
 			}
@@ -49,8 +51,6 @@ public class RangerDefaultResourceMatcher extends RangerAbstractResourceMatcher
 					break;
 				}
 			}
-		} else {
-			ret = isMatchAny;
 		}
 
 		if(policyIsExcludes) {

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerPathResourceMatcher.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerPathResourceMatcher.java b/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerPathResourceMatcher.java
index 947c1ed..fffdbfc 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerPathResourceMatcher.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/resourcematcher/RangerPathResourceMatcher.java
@@ -62,7 +62,9 @@ public class RangerPathResourceMatcher extends RangerAbstractResourceMatcher {
 
 		boolean ret = false;
 
-		if(resource != null) {
+		if(resource == null || isMatchAny) {
+			ret = isMatchAny;
+		} else {
 			if(optIgnoreCase) {
 				resource = resource.toLowerCase();
 			}
@@ -86,8 +88,6 @@ public class RangerPathResourceMatcher extends RangerAbstractResourceMatcher {
 					break;
 				}
 			}
-		} else {
-			ret = isMatchAny;
 		}
 
 		if(policyIsExcludes) {

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/main/java/org/apache/ranger/plugin/util/PolicyRefresher.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/util/PolicyRefresher.java b/agents-common/src/main/java/org/apache/ranger/plugin/util/PolicyRefresher.java
index b6acc43..04bc798 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/util/PolicyRefresher.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/util/PolicyRefresher.java
@@ -157,17 +157,17 @@ public class PolicyRefresher extends Thread {
 
 		        	if(!StringUtils.equals(serviceName, svcPolicies.getServiceName())) {
 		        		LOG.warn("PolicyRefresher(serviceName=" + serviceName + "): ignoring unexpected serviceName '" + svcPolicies.getServiceName() + "' in service-store");
+
+		        		svcPolicies.setServiceName(serviceName);
 		        	}
 
-		        	if(LOG.isDebugEnabled()) {
-						LOG.debug("PolicyRefresher(serviceName=" + serviceName + "): found updated version. lastKnownVersion=" + lastKnownVersion + "; newVersion=" + newVersion);
-					}
+					LOG.info("PolicyRefresher(serviceName=" + serviceName + "): found updated version. lastKnownVersion=" + lastKnownVersion + "; newVersion=" + newVersion);
 
 					saveToCache(svcPolicies);
 
-		        	lastKnownVersion = svcPolicies.getPolicyVersion() == null ? -1 : svcPolicies.getPolicyVersion().longValue();
+		        	lastKnownVersion = newVersion;
 
-					policyEngine.setPolicies(serviceName, svcPolicies.getServiceDef(), svcPolicies.getPolicies());
+					policyEngine.setPolicies(svcPolicies);
 				} else {
 					if(LOG.isDebugEnabled()) {
 						LOG.debug("PolicyRefresher(serviceName=" + serviceName + ").run(): no update found. lastKnownVersion=" + lastKnownVersion);
@@ -212,11 +212,13 @@ public class PolicyRefresher extends Thread {
 			        if(policies != null) {
 			        	if(!StringUtils.equals(serviceName, policies.getServiceName())) {
 			        		LOG.warn("ignoring unexpected serviceName '" + policies.getServiceName() + "' in cache file '" + cacheFile.getAbsolutePath() + "'");
+
+			        		policies.setServiceName(serviceName);
 			        	}
 
 			        	lastKnownVersion = policies.getPolicyVersion() == null ? -1 : policies.getPolicyVersion().longValue();
 
-			        	policyEngine.setPolicies(serviceName, policies.getServiceDef(), policies.getPolicies());
+			        	policyEngine.setPolicies(policies);
 			        }
 		        } catch (Exception excp) {
 		        	LOG.error("failed to load policies from cache file " + cacheFile.getAbsolutePath(), excp);

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyDb.java
----------------------------------------------------------------------
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyDb.java b/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyDb.java
new file mode 100644
index 0000000..37b8e9c
--- /dev/null
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyDb.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.plugin.policyengine;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
+import org.apache.ranger.plugin.policyengine.TestPolicyDb.PolicyDbTestCase.TestData;
+import org.apache.ranger.plugin.util.ServicePolicies;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class TestPolicyDb {
+	static Gson gsonBuilder  = null;
+
+
+	@BeforeClass
+	public static void setUpBeforeClass() throws Exception {
+		gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z")
+									   .setPrettyPrinting()
+									   .create();
+	}
+
+	@AfterClass
+	public static void tearDownAfterClass() throws Exception {
+	}
+
+	@Test
+	public void testPolicyDb_hdfs() {
+		String[] hdfsTestResourceFiles = { "/policyengine/test_policydb_hdfs.json" };
+
+		runTestsFromResourceFiles(hdfsTestResourceFiles);
+	}
+
+	private void runTestsFromResourceFiles(String[] resourceNames) {
+		for(String resourceName : resourceNames) {
+			InputStream       inStream = this.getClass().getResourceAsStream(resourceName);
+			InputStreamReader reader   = new InputStreamReader(inStream);
+
+			runTests(reader, resourceName);
+		}
+	}
+
+	private void runTests(InputStreamReader reader, String testName) {
+		PolicyDbTestCase testCase = gsonBuilder.fromJson(reader, PolicyDbTestCase.class);
+
+		assertTrue("invalid input: " + testName, testCase != null && testCase.servicePolicies != null && testCase.tests != null && testCase.servicePolicies.getPolicies() != null);
+
+
+		RangerPolicyDb policyDb = new RangerPolicyDb(testCase.servicePolicies);
+
+		for(TestData test : testCase.tests) {
+			boolean expected = test.result;
+
+			if(test.allowedPolicies != null) {
+				List<RangerPolicy> allowedPolicies = policyDb.getAllowedPolicies(test.user, test.userGroups, test.accessType);
+
+				assertEquals("allowed-policy count mismatch!", test.allowedPolicies.size(), allowedPolicies.size());
+				
+				Set<Long> allowedPolicyIds = new HashSet<Long>();
+				for(RangerPolicy allowedPolicy : allowedPolicies) {
+					allowedPolicyIds.add(allowedPolicy.getId());
+				}
+				assertEquals("allowed-policy list mismatch!", test.allowedPolicies, allowedPolicyIds);
+			} else {
+				boolean result = policyDb.isAccessAllowed(test.resources, test.user, test.userGroups, test.accessType);
+
+				assertEquals("isAccessAllowed mismatched! - " + test.name, expected, result);
+			}
+		}
+	}
+
+	static class PolicyDbTestCase {
+		public ServicePolicies servicePolicies;
+		public List<TestData>  tests;
+		
+		class TestData {
+			public String                            name;
+			public Map<String, RangerPolicyResource> resources;
+			public String                            user;
+			public Set<String>                       userGroups;
+			public String                            accessType;
+			public boolean                           result;
+			public Set<Long>                         allowedPolicies;
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyEngine.java
----------------------------------------------------------------------
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyEngine.java b/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyEngine.java
index d9e7bf0..7ebd34e 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyEngine.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyEngine.java
@@ -29,6 +29,7 @@ import java.util.List;
 import org.apache.ranger.plugin.model.RangerPolicy;
 import org.apache.ranger.plugin.model.RangerServiceDef;
 import org.apache.ranger.plugin.policyengine.TestPolicyEngine.PolicyEngineTestCase.TestData;
+import org.apache.ranger.plugin.util.ServicePolicies;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -95,7 +96,12 @@ public class TestPolicyEngine {
 
 		assertTrue("invalid input: " + testName, testCase != null && testCase.serviceDef != null && testCase.policies != null && testCase.tests != null);
 
-		policyEngine.setPolicies(testCase.serviceName, testCase.serviceDef, testCase.policies);
+		ServicePolicies servicePolicies = new ServicePolicies();
+		servicePolicies.setServiceName(testCase.serviceName);;
+		servicePolicies.setServiceDef(testCase.serviceDef);
+		servicePolicies.setPolicies(testCase.policies);
+
+		policyEngine.setPolicies(servicePolicies);
 
 		for(TestData test : testCase.tests) {
 			RangerAccessResult expected = test.result;
@@ -125,7 +131,11 @@ public class TestPolicyEngine {
 		@Override
 		public RangerAccessRequest deserialize(JsonElement jsonObj, Type type,
 				JsonDeserializationContext context) throws JsonParseException {
-			return gsonBuilder.fromJson(jsonObj, RangerAccessRequestImpl.class);
+			RangerAccessRequestImpl ret = gsonBuilder.fromJson(jsonObj, RangerAccessRequestImpl.class);
+
+			ret.setAccessType(ret.getAccessType()); // to force computation of isAccessTypeAny and isAccessTypeDelegatedAdmin
+
+			return ret;
 		}
 	}
 	

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/agents-common/src/test/resources/policyengine/test_policydb_hdfs.json
----------------------------------------------------------------------
diff --git a/agents-common/src/test/resources/policyengine/test_policydb_hdfs.json b/agents-common/src/test/resources/policyengine/test_policydb_hdfs.json
new file mode 100644
index 0000000..8d45eb7
--- /dev/null
+++ b/agents-common/src/test/resources/policyengine/test_policydb_hdfs.json
@@ -0,0 +1,218 @@
+{
+  "servicePolicies":{
+    "serviceName":"hdfsdev",
+    "serviceId":1,
+    "policyVersion":1,
+    "serviceDef":{
+      "name":"hdfs",
+      "id":1,
+      "resources":[
+        {"name":"path","type":"path","level":1,"mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerPathResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"Resource Path","description":"HDFS file or directory path"}
+      ],
+      "accessTypes":[
+        {"name":"read","label":"Read"},
+        {"name":"write","label":"Write"},
+        {"name":"execute","label":"Execute"}
+      ]
+    },
+  
+    "policies":[
+      {"id":1,"name":"entire file system","isEnabled":true,"isAuditEnabled":true,
+       "resources":{"path":{"values":["/*"],"isRecursive":true}},
+       "policyItems":[
+         {"accesses":[],"users":[],"groups":["cluster-admins"],"delegateAdmin":true}
+       ]
+      }
+      ,
+      {"id":11,"name":"/dept1 folder","isEnabled":true,"isAuditEnabled":false,
+       "resources":{"path":{"values":["/dept1/*"],"isRecursive":true}},
+       "policyItems":[
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"write","isAllowed":true},{"type":"execute","isAllowed":true}],"users":[],"groups":["dept1-admins"],"delegateAdmin":true},
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"execute","isAllowed":true}],"users":[],"groups":["dept1-users"],"delegateAdmin":false}
+       ]
+      }
+      ,
+      {"id":12,"name":"/dept1/wiki folder","isEnabled":true,"isAuditEnabled":false,
+       "resources":{"path":{"values":["/dept1/wiki/*"],"isRecursive":true}},
+       "policyItems":[
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"write","isAllowed":true},{"type":"execute","isAllowed":true}],"users":["dept1-webmaster"],"groups":[],"delegateAdmin":false}
+       ]
+      }
+      ,
+      {"id":13,"name":"/dept1/review folder","isEnabled":true,"isAuditEnabled":false,
+       "resources":{"path":{"values":["/dept1/review/*"],"isRecursive":true}},
+       "policyItems":[
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"write","isAllowed":true},{"type":"execute","isAllowed":true}],"users":["dept1-manager"],"groups":[],"delegateAdmin":false}
+       ]
+      }
+      ,
+      {"id":21,"name":"/dept2 folder","isEnabled":true,"isAuditEnabled":false,
+       "resources":{"path":{"values":["/dept2/*"],"isRecursive":true}},
+       "policyItems":[
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"write","isAllowed":true},{"type":"execute","isAllowed":true}],"users":[],"groups":["dept2-admins"],"delegateAdmin":true},
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"execute","isAllowed":true}],"users":[],"groups":["dept2-users"],"delegateAdmin":false}
+       ]
+      }
+      ,
+      {"id":22,"name":"/dept2/wiki folder","isEnabled":true,"isAuditEnabled":false,
+       "resources":{"path":{"values":["/dept2/wiki/*"],"isRecursive":true}},
+       "policyItems":[
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"write","isAllowed":true},{"type":"execute","isAllowed":true}],"users":["dept2-webmaster"],"groups":[],"delegateAdmin":false}
+       ]
+      }
+      ,
+      {"id":23,"name":"/dept2/review folder","isEnabled":true,"isAuditEnabled":false,
+       "resources":{"path":{"values":["/dept2/review/*"],"isRecursive":true}},
+       "policyItems":[
+         {"accesses":[{"type":"read","isAllowed":true},{"type":"write","isAllowed":true},{"type":"execute","isAllowed":true}],"users":["dept2-manager"],"groups":[],"delegateAdmin":false}
+       ]
+      }
+    ]
+  },
+  "tests":[
+    {"name":"ALLOW '_admin access on any path' for g=cluster-admins",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"testuser","userGroups":["cluster-admins","users"],"accessType":"_admin",
+     "result":true
+    }
+    ,
+    {"name":"DENY 'read access on any path' for g=cluster-admins",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"testuser","userGroups":["cluster-admins","users"],"accessType":"read",
+     "result":false
+    }
+    ,
+    {"name":"DENY 'write access on any path' for g=cluster-admins",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"testuser","userGroups":["cluster-admins","users"],"accessType":"write",
+     "result":false
+    }
+    ,
+    {"name":"DENY 'execute access on any path' for g=cluster-admins",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"testuser","userGroups":["cluster-admins","users"],"accessType":"execute",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on any path' for g=dept1-admins",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"testuser","userGroups":["dept1-admins","users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on any path' for u=dept1-webmaster",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"dept1-webmaster","userGroups":["users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on any path' for u=dept1-manager",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"dept1-manager","userGroups":["users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on any path' for g=dept2-admins",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"testuser","userGroups":["dept2-admins","users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on any path' for u=dept2-webmaster",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"dept2-webmaster","userGroups":["users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on any path' for u=dept2-manager",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"dept2-manager","userGroups":["users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on any path' for g=public",
+     "resources":{"path":{"values":["/dept1/*","/dept2/*","/dept3/*","/dept4/*"]}},"user":"testuser","userGroups":["public","users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+
+    {"name":"ALLOW '_admin access on path under /dept1' for g=dept1-admins",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept1-admins","users"],"accessType":"_admin",
+     "result":true
+    }
+    ,
+    {"name":"ALLOW 'read access on path under /dept1' for g=dept1-admins",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept1-admins","users"],"accessType":"read",
+     "result":true
+    }
+    ,
+    {"name":"ALLOW 'write access on path under /dept1' for g=dept1-admins",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept1-admins","users"],"accessType":"write",
+     "result":true
+    }
+    ,
+    {"name":"ALLOW 'execute access on path under /dept1' for g=dept1-admins",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept1-admins","users"],"accessType":"execute",
+     "result":true
+    }
+    ,
+    {"name":"ALLOW 'read access on path under /dept1' for g=dept1-users",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept1-users","users"],"accessType":"read",
+     "result":true
+    }
+    ,
+    {"name":"DENY 'write access on path under /dept1' for g=dept1-users",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept1-users","users"],"accessType":"write",
+     "result":false
+    }
+    ,
+    {"name":"ALLOW 'execute access on path under /dept1' for g=dept1-users",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept1-users","users"],"accessType":"execute",
+     "result":true
+    }
+    ,
+    {"name":"DENY '_admin access on path under /dept1' for g=dept2-admins",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept2-admins","users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY '_admin access on path under /dept1' for g=dept2-users",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept2-users","users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+    {"name":"DENY 'read access on path under /dept1' for g=dept2-users",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept2-users","users"],"accessType":"read",
+     "result":false
+    }
+    ,
+    {"name":"DENY 'write access on path under /dept1' for g=dept2-users",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept2-users","users"],"accessType":"write",
+     "result":false
+    }
+    ,
+    {"name":"DENY 'execute access on path under /dept1' for g=dept2-users",
+     "resources":{"path":{"values":["/dept1/wiki/*, /dept1/calender"]}},"user":"testuser","userGroups":["dept2-users","users"],"accessType":"execute",
+     "result":false
+    }
+
+    ,
+    {"name":"ALLOW '_admin access on path under /dept2' for g=dept2-admins",
+     "resources":{"path":{"values":["/dept2/wiki/*, /dept2/calender"]}},"user":"testuser","userGroups":["dept2-admins","users"],"accessType":"_admin",
+     "result":true
+    }
+    ,
+    {"name":"DENY '_admin access on path under /dept2' for g=dept1-admins",
+     "resources":{"path":{"values":["/dept2/wiki/*, /dept2/calender"]}},"user":"testuser","userGroups":["dept1-admins","users"],"accessType":"_admin",
+     "result":false
+    }
+    ,
+
+    {"name":"7 '_admin allowed policies' for g=cluster-admins",
+     "user":"testuser","userGroups":["cluster-admins","users"],"accessType":"_admin","allowedPolicies":[1, 11, 12, 13, 21, 22, 23]
+    }
+    ,
+    {"name":"3 '_admin allowed policies' for g=dept1-admins",
+     "user":"testuser","userGroups":["dept1-admins","users"],"accessType":"_admin","allowedPolicies":[11, 12, 13]
+    }
+    ,
+    {"name":"3 '_admin allowed policies' for g=dept2-admins",
+     "user":"testuser","userGroups":["dept2-admins","users"],"accessType":"_admin","allowedPolicies":[21, 22, 23]
+    }
+    ,
+    {"name":"0 '_admin allowed policies' for g=public",
+     "user":"testuser","userGroups":["public","users"],"accessType":"_admin","allowedPolicies":[]
+    }
+  ]
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/TestPolicyEngine.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/TestPolicyEngine.java b/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/TestPolicyEngine.java
index 59e79d0..6ef00a7 100644
--- a/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/TestPolicyEngine.java
+++ b/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/TestPolicyEngine.java
@@ -161,7 +161,11 @@ public class TestPolicyEngine {
 		@Override
 		public RangerAccessRequest deserialize(JsonElement jsonObj, Type type,
 				JsonDeserializationContext context) throws JsonParseException {
-			return gsonBuilder.fromJson(jsonObj, RangerAccessRequestImpl.class);
+			RangerAccessRequestImpl ret = gsonBuilder.fromJson(jsonObj, RangerAccessRequestImpl.class);
+
+			ret.setAccessType(ret.getAccessType()); // to force computation of isAccessTypeAny and isAccessTypeDelegatedAdmin
+
+			return ret;
 		}
 	}
 	

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
index fbb6917..d408611 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
@@ -535,6 +535,23 @@ public class RangerBizUtil {
 	}
 
 	/**
+	 * return username of currently logged in user
+	 * 
+	 * @return
+	 */
+	public String getCurrentUserLoginId() {
+		String ret = null;
+
+		UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
+		if (currentUserSession != null) {
+			ret = currentUserSession.getLoginId();
+		}
+
+		return ret;
+	}
+
+	/**
 	 * returns current user's userID from active user sessions
 	 * 
 	 * @return

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/57625ff7/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
index d9f7015..8b3834e 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
@@ -65,6 +65,8 @@ import org.apache.ranger.plugin.model.validation.RangerValidatorFactory;
 import org.apache.ranger.plugin.model.validation.RangerValidator.Action;
 import org.apache.ranger.plugin.model.RangerService;
 import org.apache.ranger.plugin.model.RangerServiceDef;
+import org.apache.ranger.plugin.policyengine.RangerPolicyDb;
+import org.apache.ranger.plugin.policyengine.RangerPolicyDbCache;
 import org.apache.ranger.plugin.policyengine.RangerPolicyEngine;
 import org.apache.ranger.plugin.policyengine.RangerAccessResource;
 import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl;
@@ -842,7 +844,6 @@ public class ServiceREST {
 		return ret;
 	}
 
-
 	@POST
 	@Path("/policies")
 	@Produces({ "application/json", "application/xml" })
@@ -854,12 +855,19 @@ public class ServiceREST {
 		RangerPolicy ret = null;
 		
 		try {
-//			RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore);
-//			validator.validate(policy, Action.CREATE, bizUtil.isAdmin());
+			// RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore);
+			// validator.validate(policy, Action.CREATE, bizUtil.isAdmin());
+
+			ensureAdminAccess(policy.getService(), policy.getResources());
+
 			ret = svcStore.createPolicy(policy);
 		} catch(Exception excp) {
 			LOG.error("createPolicy(" + policy + ") failed", excp);
 
+			if(excp instanceof WebApplicationException) {
+				throw (WebApplicationException)excp;
+			}
+
 			throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
 		}
 
@@ -881,8 +889,11 @@ public class ServiceREST {
 		RangerPolicy ret = null;
 
 		try {
-//			RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore);
-//			validator.validate(policy, Action.UPDATE, bizUtil.isAdmin());
+			// RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore);
+			// validator.validate(policy, Action.UPDATE, bizUtil.isAdmin());
+
+			ensureAdminAccess(policy.getService(), policy.getResources());
+
 			ret = svcStore.updatePolicy(policy);
 		} catch(Exception excp) {
 			LOG.error("updatePolicy(" + policy + ") failed", excp);
@@ -906,8 +917,13 @@ public class ServiceREST {
 		}
 
 		try {
-			RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore);
-			validator.validate(id, Action.DELETE);
+			// RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore);
+			// validator.validate(id, Action.DELETE);
+
+			RangerPolicy policy = svcStore.getPolicy(id);
+
+			ensureAdminAccess(policy.getService(), policy.getResources());
+
 			svcStore.deletePolicy(id);
 		} catch(Exception excp) {
 			LOG.error("deletePolicy(" + id + ") failed", excp);
@@ -932,6 +948,10 @@ public class ServiceREST {
 
 		try {
 			ret = svcStore.getPolicy(id);
+
+			if(ret != null) {
+				ensureAdminAccess(ret.getService(), ret.getResources());
+			}
 		} catch(Exception excp) {
 			LOG.error("getPolicy(" + id + ") failed", excp);
 
@@ -963,6 +983,8 @@ public class ServiceREST {
 
 		try {
 			ret = svcStore.getPaginatedPolicies(filter);
+
+			applyAdminAccessFilter(ret);
 		} catch (Exception excp) {
 			LOG.error("getPolicies() failed", excp);
 
@@ -984,6 +1006,8 @@ public class ServiceREST {
 
 		try {
 			ret = svcStore.getPolicies(filter);
+
+			applyAdminAccessFilter(ret);
 		} catch(Exception excp) {
 			LOG.error("getPolicies() failed", excp);
 
@@ -1008,9 +1032,11 @@ public class ServiceREST {
 		Long ret = null;
 
 		try {
-			List<RangerPolicy> services = getPolicies(request).getPolicies();
+			List<RangerPolicy> policies = getPolicies(request).getPolicies();
+
+			applyAdminAccessFilter(policies);
 			
-			ret = new Long(services == null ? 0 : services.size());
+			ret = new Long(policies == null ? 0 : policies.size());
 		} catch(Exception excp) {
 			LOG.error("countPolicies() failed", excp);
 
@@ -1039,6 +1065,8 @@ public class ServiceREST {
 
 		try {
 			ret = svcStore.getPaginatedServicePolicies(serviceId, filter);
+
+			applyAdminAccessFilter(ret);
 		} catch (Exception excp) {
 			LOG.error("getServicePolicies(" + serviceId + ") failed", excp);
 
@@ -1071,6 +1099,8 @@ public class ServiceREST {
 
 		try {
 			ret = svcStore.getPaginatedServicePolicies(serviceName, filter);
+
+			applyAdminAccessFilter(ret);
 		} catch (Exception excp) {
 			LOG.error("getServicePolicies(" + serviceName + ") failed", excp);
 
@@ -1426,4 +1456,68 @@ public class ServiceREST {
 		return svcStore.getPolicyForVersionNumber(policyId, versionNo);
 	}
 
+	private void applyAdminAccessFilter(RangerPolicyList policies) {
+		if(policies != null && !CollectionUtils.isEmpty(policies.getList())) {
+			applyAdminAccessFilter(policies.getPolicies());
+		}
+	}
+
+	private void applyAdminAccessFilter(List<RangerPolicy> policies) {
+		boolean isAdmin = bizUtil.isAdmin();
+
+		if(!isAdmin && !CollectionUtils.isEmpty(policies)) {
+			String                      userName   = bizUtil.getCurrentUserLoginId();
+			Set<String>                 userGroups = userMgr.getGroupsForUser(userName);
+			Map<String, RangerPolicyDb> policyDbs  = new HashMap<String, RangerPolicyDb>();
+
+			for(int i = 0; i < policies.size(); i++) {
+				RangerPolicy   policy      = policies.get(i);
+				String         serviceName = policy.getService();
+				RangerPolicyDb policyDb    = policyDbs.get(serviceName);
+
+				if(policyDb == null) {
+					policyDb = RangerPolicyDbCache.getInstance().getPolicyDb(policy.getService(), svcStore);
+
+					if(policyDb != null) {
+						policyDbs.put(serviceName, policyDb);
+					}
+				}
+
+				boolean hasAdminAccess = hasAdminAccess(serviceName, policy.getResources(), policyDb, userName, userGroups);
+
+				if(!hasAdminAccess) {
+					policies.remove(i);
+					i--;
+				}
+			}
+		}
+	}
+	
+	private void ensureAdminAccess(String serviceName, Map<String, RangerPolicyResource> resources) {
+		boolean isAdmin = bizUtil.isAdmin();
+
+		if(!isAdmin) {
+			RangerPolicyDb policyDb   = RangerPolicyDbCache.getInstance().getPolicyDb(serviceName, svcStore);
+			String         userName   = bizUtil.getCurrentUserLoginId();
+			Set<String>    userGroups = userMgr.getGroupsForUser(userName);
+
+			boolean isAllowed = hasAdminAccess(serviceName, resources, policyDb, userName, userGroups);
+
+			if(!isAllowed) {
+				throw restErrorUtil.createRESTException(HttpServletResponse.SC_UNAUTHORIZED,
+						"User '" + userName + "' does not have delegated-admin privilege on given resources", true);
+			}
+		}
+	}
+
+	private boolean hasAdminAccess(String serviceName, Map<String, RangerPolicyResource> resources, RangerPolicyDb policyDb, String userName, Set<String> userGroups) {
+		boolean isAllowed = false;
+
+		if(policyDb != null) {
+			isAllowed = policyDb.isAccessAllowed(resources, userName, userGroups, RangerPolicyEngine.ADMIN_ACCESS);
+		}
+
+		return isAllowed;
+	}
+
 }


Mime
View raw message