You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ranger.apache.org by ma...@apache.org on 2015/06/11 07:09:40 UTC
[1/9] incubator-ranger git commit: RANGER-178 Use libraries from
official Solr 5.2 maven repository
Repository: incubator-ranger
Updated Branches:
refs/heads/tag-policy c6133b7e7 -> ea3bcb38e
RANGER-178 Use libraries from official Solr 5.2 maven repository
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/065b431f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/065b431f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/065b431f
Branch: refs/heads/tag-policy
Commit: 065b431ff78b219ebc0ec7997d1c4f3a67298d7e
Parents: 0512610
Author: Don Bosco Durai <bo...@apache.org>
Authored: Mon Jun 8 20:00:06 2015 -0700
Committer: Don Bosco Durai <bo...@apache.org>
Committed: Mon Jun 8 20:00:06 2015 -0700
----------------------------------------------------------------------
pom.xml | 35 +----------------------------------
1 file changed, 1 insertion(+), 34 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/065b431f/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index c9d7536..0cd84f3 100644
--- a/pom.xml
+++ b/pom.xml
@@ -149,7 +149,7 @@
<jersey-client.version>2.6</jersey-client.version>
<junit.version>4.11</junit.version>
<kafka.version>0.8.2.0</kafka.version>
- <!--<kafka.version>0.8.2.2.3.0.0-2208</kafka.version>-->
+ <!-- <kafka.version>0.8.2.2.3.0.0-2208</kafka.version> -->
<mockito.version>1.8.4</mockito.version>
<hamcrest-version>1.3</hamcrest-version>
<knox.gateway.version>0.6.0</knox.gateway.version>
@@ -219,14 +219,6 @@
<module>unixauthnative</module>
</modules>
</profile>
-<!--
- <profile>
- <id>solr-security</id>
- <modules>
- <module>plugin-solr</module>
- </modules>
- </profile>
--->
<profile>
<id>kafka-security</id>
<modules>
@@ -261,31 +253,6 @@
<enabled>false</enabled>
</snapshots>
</repository>
- <repository>
- <id>apache.solr.rc</id>
- <name>Apache Solr RC builds</name>
- <url>https://dist.apache.org/repos/dist/dev/lucene/lucene-solr-5.2.0-RC4-rev1683206/solr/maven</url>
- <releases>
- <enabled>true</enabled>
- </releases>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </repository>
- <repository>
- <id>apache.lucene.rc</id>
- <name>Apache Lucene RC builds</name>
- <url>https://dist.apache.org/repos/dist/dev/lucene/lucene-solr-5.2.0-RC4-rev1683206/lucene/maven</url>
- <releases>
- <enabled>true</enabled>
- </releases>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </repository>
-
-
-
</repositories>
<dependencyManagement>
<dependencies>
[3/9] incubator-ranger git commit: RANGER-540: JPA cache disabled to
support ranger-admin in HA deployment
Posted by ma...@apache.org.
RANGER-540: JPA cache disabled to support ranger-admin in HA deployment
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/4c75d282
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/4c75d282
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/4c75d282
Branch: refs/heads/tag-policy
Commit: 4c75d2822927de4215da2b55523328a1ec3e15e0
Parents: 2c54590
Author: Madhan Neethiraj <ma...@apache.org>
Authored: Mon Jun 8 23:38:56 2015 -0700
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Mon Jun 8 23:38:56 2015 -0700
----------------------------------------------------------------------
security-admin/src/main/resources/META-INF/persistence.xml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/4c75d282/security-admin/src/main/resources/META-INF/persistence.xml
----------------------------------------------------------------------
diff --git a/security-admin/src/main/resources/META-INF/persistence.xml b/security-admin/src/main/resources/META-INF/persistence.xml
index 822bbcf..344e2e9 100644
--- a/security-admin/src/main/resources/META-INF/persistence.xml
+++ b/security-admin/src/main/resources/META-INF/persistence.xml
@@ -34,7 +34,7 @@
<class>org.apache.ranger.entity.XXAuditMap</class>
<class>org.apache.ranger.entity.XXPolicyExportAudit</class>
<class>org.apache.ranger.entity.XXTrxLog</class>
- <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
+ <shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="eclipselink.logging.level" value="WARNING"/>
@@ -42,7 +42,7 @@
</persistence-unit>
<persistence-unit name="loggingPU">
<class>org.apache.ranger.entity.XXAccessAudit</class>
- <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
+ <shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="eclipselink.logging.level" value="WARNING"/>
[8/9] incubator-ranger git commit: RANGER-546: fix to custom
conditions evaluation
Posted by ma...@apache.org.
RANGER-546: fix to custom conditions evaluation
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/c5f61c89
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/c5f61c89
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/c5f61c89
Branch: refs/heads/tag-policy
Commit: c5f61c898244aa436997990df19778766b0db295
Parents: 8900202
Author: Madhan Neethiraj <ma...@apache.org>
Authored: Wed Jun 10 16:00:00 2015 -0700
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Wed Jun 10 21:33:52 2015 -0700
----------------------------------------------------------------------
.../conditionevaluator/RangerSimpleMatcher.java | 10 +-
.../RangerAbstractPolicyEvaluator.java | 15 +-
.../RangerAbstractPolicyItemEvaluator.java | 61 +++
.../RangerDefaultPolicyEvaluator.java | 387 +++----------------
.../RangerDefaultPolicyItemEvaluator.java | 273 +++++++++++++
.../RangerOptimizedPolicyEvaluator.java | 4 +-
.../policyevaluator/RangerPolicyEvaluator.java | 7 +-
.../RangerPolicyItemEvaluator.java | 55 +++
.../plugin/policyengine/TestPolicyEngine.java | 7 +
.../RangerDefaultPolicyEvaluatorTest.java | 256 ------------
.../test_policyengine_conditions.json | 230 +++++++++++
.../policyengine/test_policyengine_hbase.json | 2 +-
12 files changed, 707 insertions(+), 600 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerSimpleMatcher.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerSimpleMatcher.java b/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerSimpleMatcher.java
index 48f806d..d9f6158 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerSimpleMatcher.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerSimpleMatcher.java
@@ -82,15 +82,13 @@ public class RangerSimpleMatcher extends RangerAbstractConditionEvaluator {
LOG.debug("==> RangerSimpleMatcher.isMatched(" + request + ")");
}
- boolean matched = true;
+ boolean matched = false;
+
if (_allowAny) {
- LOG.debug("isMatched: allowAny flag is true. Matched!");
+ matched = true;
} else {
String requestValue = extractValue(request, _contextName);
- if (requestValue == null) {
- LOG.debug("isMatched: couldn't get value from request. Ok. Implicitly matched!");
- } else {
- matched = false;
+ if (StringUtils.isNotBlank(requestValue)) {
for (String policyValue : _values) {
if (FilenameUtils.wildcardMatch(requestValue, policyValue)) {
matched = true;
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyEvaluator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyEvaluator.java
index 85e69f1..178b9d8 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyEvaluator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyEvaluator.java
@@ -20,11 +20,9 @@
package org.apache.ranger.plugin.policyevaluator;
-import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-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.policyengine.RangerPolicyEngineOptions;
@@ -68,6 +66,11 @@ public abstract class RangerAbstractPolicyEvaluator implements RangerPolicyEvalu
}
@Override
+ public boolean isAuditEnabled() {
+ return policy != null && policy.getIsAuditEnabled();
+ }
+
+ @Override
public int compareTo(RangerPolicyEvaluator other) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerAbstractPolicyEvaluator.compareTo()");
@@ -76,13 +79,7 @@ public abstract class RangerAbstractPolicyEvaluator implements RangerPolicyEvalu
int result = Integer.compare(this.getEvalOrder(), other.getEvalOrder());
if (result == 0) {
- Map<String, RangerConditionEvaluator> myConditionEvaluators = this.getConditionEvaluators();
- Map<String, RangerConditionEvaluator> otherConditionEvaluators = other.getConditionEvaluators();
-
- int myConditionEvaluatorCount = myConditionEvaluators == null ? 0 : myConditionEvaluators.size();
- int otherConditionEvaluatorCount = otherConditionEvaluators == null ? 0 : otherConditionEvaluators.size();
-
- result = Integer.compare(myConditionEvaluatorCount, otherConditionEvaluatorCount);
+ result = Integer.compare(getCustomConditionsCount(), other.getCustomConditionsCount());
}
if(LOG.isDebugEnabled()) {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyItemEvaluator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyItemEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyItemEvaluator.java
new file mode 100644
index 0000000..a986ca6
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerAbstractPolicyItemEvaluator.java
@@ -0,0 +1,61 @@
+/*
+ * 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.policyevaluator;
+
+
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.ranger.plugin.conditionevaluator.RangerConditionEvaluator;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerServiceDef;
+import org.apache.ranger.plugin.policyengine.RangerPolicyEngineOptions;
+
+
+public abstract class RangerAbstractPolicyItemEvaluator implements RangerPolicyItemEvaluator {
+ final RangerPolicyEngineOptions options;
+ final RangerServiceDef serviceDef;
+ final RangerPolicy policy;
+ final RangerPolicyItem policyItem;
+ final long policyId;
+
+ List<RangerConditionEvaluator> conditionEvaluators = Collections.<RangerConditionEvaluator>emptyList();
+
+ RangerAbstractPolicyItemEvaluator(RangerServiceDef serviceDef, RangerPolicy policy, RangerPolicyItem policyItem, RangerPolicyEngineOptions options) {
+ this.serviceDef = serviceDef;
+ this.policy = policy;
+ this.policyItem = policyItem;
+ this.options = options;
+ this.policyId = policy != null && policy.getId() != null ? policy.getId() : -1;
+ }
+
+ @Override
+ public List<RangerConditionEvaluator> getConditionEvaluators() {
+ return conditionEvaluators;
+ }
+
+ protected String getServiceType() {
+ return serviceDef != null ? serviceDef.getName() : null;
+ }
+
+ protected boolean getConditionsDisabledOption() {
+ return options != null ? options.disableCustomConditions : false;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/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 9233f8d..030cd87 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
@@ -19,11 +19,12 @@
package org.apache.ranger.plugin.policyevaluator;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -31,31 +32,31 @@ 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.conditionevaluator.RangerConditionEvaluator;
import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
import org.apache.ranger.plugin.model.RangerServiceDef;
import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef;
-import org.apache.ranger.plugin.model.RangerServiceDef.RangerPolicyConditionDef;
import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
import org.apache.ranger.plugin.policyengine.RangerAccessResource;
import org.apache.ranger.plugin.policyengine.RangerAccessResult;
-import org.apache.ranger.plugin.policyengine.RangerPolicyEngine;
import org.apache.ranger.plugin.policyengine.RangerPolicyEngineOptions;
import org.apache.ranger.plugin.policyresourcematcher.RangerDefaultPolicyResourceMatcher;
import org.apache.ranger.plugin.policyresourcematcher.RangerPolicyResourceMatcher;
-import com.google.common.base.Strings;
-
public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator {
private static final Log LOG = LogFactory.getLog(RangerDefaultPolicyEvaluator.class);
- private RangerPolicyResourceMatcher resourceMatcher = null;
- private Map<String, RangerConditionEvaluator> conditionEvaluators = null;
+ private RangerPolicyResourceMatcher resourceMatcher = null;
+ private List<RangerPolicyItemEvaluator> policyItemEvaluators = null;
+ private int customConditionsCount = 0;
+
+ @Override
+ public int getCustomConditionsCount() {
+ return customConditionsCount;
+ }
@Override
public void init(RangerPolicy policy, RangerServiceDef serviceDef, RangerPolicyEngineOptions options) {
@@ -72,131 +73,28 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
resourceMatcher.setServiceDef(serviceDef);
resourceMatcher.setPolicyResources(policy == null ? null : policy.getResources());
resourceMatcher.init();
+
+ if(policy != null && CollectionUtils.isNotEmpty(policy.getPolicyItems())) {
+ policyItemEvaluators = new ArrayList<RangerPolicyItemEvaluator>();
- if(options.disableCustomConditions) {
- conditionEvaluators = Collections.<String, RangerConditionEvaluator>emptyMap();
- } else {
- conditionEvaluators = initializeConditionEvaluators(policy, serviceDef);
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerDefaultPolicyEvaluator.init()");
- }
- }
-
- @Override
- public Map<String, RangerConditionEvaluator> getConditionEvaluators() {
- return conditionEvaluators;
- }
+ for(RangerPolicyItem policyItem : policy.getPolicyItems()) {
+ RangerPolicyItemEvaluator itemEvaluator = new RangerDefaultPolicyItemEvaluator(serviceDef, policy, policyItem, options);
- /**
- * Non-private only for testability.
- * @param policy
- * @param serviceDef
- * @return a Map of condition name to a new evaluator object of the class configured in service definition for that condition name
- */
- Map<String, RangerConditionEvaluator> initializeConditionEvaluators(RangerPolicy policy, RangerServiceDef serviceDef) {
- if(LOG.isDebugEnabled()) {
- LOG.debug(String.format("==> RangerDefaultPolicyEvaluator.initializeConditionEvaluators(%s, %s)", policy, serviceDef));
- }
+ itemEvaluator.init();
- Map<String, RangerConditionEvaluator> result = new HashMap<String, RangerConditionEvaluator>();
- if (policy == null) {
- LOG.debug("initializeConditionEvaluators: Policy is null!");
- } else if (CollectionUtils.isEmpty(policy.getPolicyItems())) {
- LOG.debug("initializeConditionEvaluators: Policyitems collection null or empty!");
- } else {
- for (RangerPolicyItem item : policy.getPolicyItems()) {
- if (CollectionUtils.isEmpty(item.getConditions())) {
- if (LOG.isDebugEnabled()) {
- LOG.debug(String.format("initializeConditionEvaluators: null or empty condition collection on policy item[%s]. Ok, skipping", item));
- }
- } else {
- for (RangerPolicyItemCondition condition : item.getConditions()) {
- String conditionName = condition.getType();
- // skip it if we have already processed this condition earlier
- if (result.containsKey(conditionName)) {
- continue;
- }
- RangerPolicyConditionDef conditionDef = getConditionDef(serviceDef, conditionName);
- if (conditionDef == null) {
- LOG.error("initializeConditionEvaluators: Serious Configuration error: Couldn't get condition Definition for condition[" + conditionName + "]! Disabling all checks for this condition.");
- } else {
- String evaluatorClassName = conditionDef.getEvaluator();
- if (Strings.isNullOrEmpty(evaluatorClassName)) {
- LOG.error("initializeConditionEvaluators: Serious Configuration error: Couldn't get condition evaluator class name for condition[" + conditionName + "]! Disabling all checks for this condition.");
- } else {
- RangerConditionEvaluator anEvaluator = newConditionEvaluator(evaluatorClassName);
- if (anEvaluator == null) {
- LOG.error("initializeConditionEvaluators: Serious Configuration error: Couldn't instantiate condition evaluator for class[" + evaluatorClassName + "]. All checks for condition[" + conditionName + "] disabled.");
- } else {
- anEvaluator.setConditionDef(conditionDef);
- anEvaluator.setPolicyItemCondition(condition);
- anEvaluator.init();
- result.put(conditionName, anEvaluator);
- }
- }
- }
- }
+ policyItemEvaluators.add(itemEvaluator);
+
+ if(CollectionUtils.isNotEmpty(itemEvaluator.getConditionEvaluators())) {
+ customConditionsCount += itemEvaluator.getConditionEvaluators().size();
}
}
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug(String.format("<== RangerDefaultPolicyEvaluator.initializeConditionEvaluators(%s)", result.toString()));
- }
- return result;
- }
-
- RangerPolicyConditionDef getConditionDef(RangerServiceDef serviceDef, String conditionName) {
- if(LOG.isDebugEnabled()) {
- LOG.debug(String.format("==> RangerDefaultPolicyEvaluator.initializeConditionEvaluators(%s, %s)", serviceDef, conditionName));
- }
-
- RangerPolicyConditionDef result = null;
- if (Strings.isNullOrEmpty(conditionName)) {
- LOG.debug("initializeConditionEvaluators: Condition name was null or empty!");
- }
- else if (serviceDef == null) {
- LOG.debug("initializeConditionEvaluators: Servicedef was null!");
- } else if (CollectionUtils.isEmpty(serviceDef.getPolicyConditions())) {
- LOG.debug("initializeConditionEvaluators: Policy conditions collection of the service def is empty! Ok, skipping.");
} else {
- Iterator<RangerPolicyConditionDef> iterator = serviceDef.getPolicyConditions().iterator();
- while (iterator.hasNext() && result == null) {
- RangerPolicyConditionDef conditionDef = iterator.next();
- String name = conditionDef.getName();
- if (conditionName.equals(name)) {
- result = conditionDef;
- }
- }
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug(String.format("<== RangerDefaultPolicyEvaluator.initializeConditionEvaluators(%s -> %s)", conditionName, result));
+ policyItemEvaluators = Collections.<RangerPolicyItemEvaluator>emptyList();
}
- return result;
- }
- RangerConditionEvaluator newConditionEvaluator(String className) {
if(LOG.isDebugEnabled()) {
- LOG.debug(String.format("==> RangerDefaultPolicyEvaluator.newConditionEvaluator(%s)", className));
- }
-
- RangerConditionEvaluator evaluator = null;
- try {
- @SuppressWarnings("unchecked")
- Class<RangerConditionEvaluator> matcherClass = (Class<RangerConditionEvaluator>)Class.forName(className);
-
- evaluator = matcherClass.newInstance();
- } catch(Throwable t) {
- LOG.error("Caught Throwable: unexpected error instantiating object of class[" + className + "]. Returning null!", t);
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug(String.format("<== RangerDefaultPolicyEvaluator.newConditionEvaluator(%s)", evaluator == null ? null : evaluator.toString()));
+ LOG.debug("<== RangerDefaultPolicyEvaluator.init()");
}
- return evaluator;
}
@Override
@@ -204,13 +102,12 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
if (LOG.isDebugEnabled()) {
LOG.debug("==> RangerDefaultPolicyEvaluator.evaluate(" + request + ", " + result + ")");
}
- RangerPolicy policy = getPolicy();
- if (policy != null && request != null && result != null) {
- boolean isMatchAttempted = false;
- boolean matchResult = false;
+ if (request != null && result != null) {
+ boolean isMatchAttempted = false;
+ boolean matchResult = false;
boolean isHeadMatchAttempted = false;
- boolean headMatchResult = false;
+ boolean headMatchResult = false;
if (!result.getIsAuditedDetermined()) {
// Need to match request.resource first. If it matches (or head matches), then only more progress can be made
@@ -229,7 +126,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
if (matchResult || headMatchResult) {
// We are done for determining if audit is needed for this policy
- if (policy.getIsAuditEnabled()) {
+ if (isAuditEnabled()) {
result.setIsAudited(true);
}
}
@@ -252,7 +149,7 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
}
// Go further to evaluate access only if match or head match was found at this point
if (matchResult || headMatchResult) {
- evaluatePolicyItemsForAccess(policy, request, result);
+ evaluatePolicyItemsForAccess(request, result);
}
}
}
@@ -262,63 +159,21 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
}
}
- protected void evaluatePolicyItemsForAccess(RangerPolicy policy, RangerAccessRequest request, RangerAccessResult result) {
+ protected void evaluatePolicyItemsForAccess(RangerAccessRequest request, RangerAccessResult result) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerDefaultPolicyEvaluator.evaluatePolicyItemsForAccess(" + request + ", " + result + ")");
}
- for (RangerPolicy.RangerPolicyItem policyItem : policy.getPolicyItems()) {
-
- boolean isUserGroupMatch = matchUserGroup(policyItem, request.getUser(), request.getUserGroups());
-
- if (!isUserGroupMatch) {
- continue;
- }
- // 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 (request.isAccessTypeDelegatedAdmin()) {
- if (policyItem.getDelegateAdmin()) {
- result.setIsAllowed(true);
- result.setPolicyId(policy.getId());
- break;
- }
- continue;
- }
-
- if (CollectionUtils.isEmpty(policyItem.getAccesses())) {
- continue;
- }
-
- boolean accessAllowed = false;
- if (request.isAccessTypeAny()) {
- for (RangerPolicy.RangerPolicyItemAccess access : policyItem.getAccesses()) {
- if (access.getIsAllowed()) {
- accessAllowed = true;
- break;
- }
- }
- } else {
- RangerPolicy.RangerPolicyItemAccess access = getAccess(policyItem, request.getAccessType());
-
- if (access != null && access.getIsAllowed()) {
- accessAllowed = true;
- }
- }
- if (accessAllowed == false) {
- continue;
- }
-
- boolean isCustomConditionsMatch = matchCustomConditions(policyItem, request, getConditionEvaluators());
+ if(CollectionUtils.isNotEmpty(policyItemEvaluators) && !result.getIsAccessDetermined()) {
+ for (RangerPolicyItemEvaluator policyItemEvaluator : policyItemEvaluators) {
+ policyItemEvaluator.evaluate(request, result);
- if (!isCustomConditionsMatch) {
- continue;
- }
-
- result.setIsAllowed(true);
- result.setPolicyId(getPolicy().getId());
- break;
+ if(result.getIsAccessDetermined()) {
+ break;
+ }
+ }
}
+
if(LOG.isDebugEnabled()) {
LOG.debug("<== RangerDefaultPolicyEvaluator.evaluatePolicyItemsForAccess(" + request + ", " + result + ")");
}
@@ -411,102 +266,6 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
return ret;
}
- protected boolean matchUserGroup(RangerPolicyItem policyItem, String user, Collection<String> groups) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("==> RangerDefaultPolicyEvaluator.matchUserGroup(" + policyItem + ", " + user + ", " + groups + ")");
- }
-
- boolean ret = false;
-
- if(policyItem != null) {
- if(!ret && user != null && policyItem.getUsers() != null) {
- ret = policyItem.getUsers().contains(user);
- }
-
- if(!ret && groups != null && policyItem.getGroups() != null) {
- ret = policyItem.getGroups().contains(RangerPolicyEngine.GROUP_PUBLIC) ||
- !Collections.disjoint(policyItem.getGroups(), groups);
- }
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerDefaultPolicyEvaluator.matchUserGroup(" + policyItem + ", " + user + ", " + groups + "): " + ret);
- }
-
- return ret;
- }
-
- // takes map in as argument for testability
- protected boolean matchCustomConditions(RangerPolicyItem policyItem, RangerAccessRequest request, Map<String, RangerConditionEvaluator> evaluatorMap) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("==> RangerDefaultPolicyEvaluator.matchCustomConditions(" + request + ")");
- }
-
- boolean result = true;
- if (policyItem == null) {
- LOG.debug("matchCustomConditions: Unexpected: policyItem was null");
- } else if (CollectionUtils.isEmpty(policyItem.getConditions())) {
- LOG.debug("matchCustomConditions: policy item does not have any conditions! Ok, implicitly passed.");
- } else {
- Iterator<RangerPolicyItemCondition> iterator = policyItem.getConditions().iterator();
- /*
- * We need to let the request be evaluated by the condition evaluator for each condition on the policy item.
- * We bail out as soon as we find a mismatch, i.e. ALL conditions must succeed for condition evaluation to return true.
- */
- boolean matched = true;
- while (iterator.hasNext() && matched) {
- RangerPolicyItemCondition itemCondition = iterator.next();
- if (itemCondition == null) {
- LOG.debug("matchCustomConditions: Unexpected: Item condition on policy item was null! Ignoring...");
- } else {
- String conditionName = itemCondition.getType();
- if (StringUtils.isBlank(conditionName)) {
- LOG.debug("matchCustomConditions: Unexpected: condition name on item conditon [" + conditionName + "] was null/empty/blank! Ignoring...");
- } else if (!evaluatorMap.containsKey(conditionName)) {
- LOG.warn("matchCustomConditions: Unexpected: Could not find condition evaluator for condition[" + conditionName + "]! Ignoring...");
- } else {
- RangerConditionEvaluator conditionEvaluator = evaluatorMap.get(conditionName);
- matched = conditionEvaluator.isMatched(request);
- if (LOG.isDebugEnabled()) {
- LOG.debug(String.format("matchCustomConditions: evaluator for condition[%s] returned[%s] for request[%s]", conditionName, matched, request));
- }
- }
- }
- }
- result = result && matched;
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerDefaultPolicyEvaluator.matchCustomConditions(" + request + "): " + result);
- }
-
- return result;
- }
-
- protected RangerPolicyItemAccess getAccess(RangerPolicyItem policyItem, String accessType) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("==> RangerDefaultPolicyEvaluator.getAccess(" + policyItem + ", " + accessType + ")");
- }
-
- RangerPolicyItemAccess ret = null;
-
- if(policyItem != null && accessType != null && policyItem.getAccesses() != null) {
- for(RangerPolicyItemAccess access : policyItem.getAccesses()) {
- if(StringUtils.equalsIgnoreCase(accessType, access.getType())) {
- ret = access;
-
- break;
- }
- }
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerDefaultPolicyEvaluator.getAccess(" + policyItem + ", " + accessType + "): " + ret);
- }
-
- return ret;
- }
-
protected boolean isMatch(Map<String, RangerPolicyResource> resources) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerDefaultPolicyEvaluator.isMatch(" + resources + ")");
@@ -532,52 +291,15 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
boolean ret = false;
- RangerPolicy policy = getPolicy();
-
- if(policy != null) {
- 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 : policy.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(CollectionUtils.isNotEmpty(policyItemEvaluators)) {
+ for (RangerPolicyItemEvaluator policyItemEvaluator : policyItemEvaluators) {
+ ret = policyItemEvaluator.matchUserGroup(user, userGroups) &&
+ policyItemEvaluator.matchAccessType(accessType);
- 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(ret) {
+ break;
+ }
+ }
}
if(LOG.isDebugEnabled()) {
@@ -675,4 +397,23 @@ public class RangerDefaultPolicyEvaluator extends RangerAbstractPolicyEvaluator
return ret;
}
+
+ private RangerPolicyItemAccess getAccess(RangerPolicyItem policyItem, String accessType) {
+ RangerPolicyItemAccess ret = null;
+
+ if(policyItem != null && CollectionUtils.isNotEmpty(policyItem.getAccesses())) {
+ for(RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) {
+ if(StringUtils.equalsIgnoreCase(itemAccess.getType(), accessType)) {
+ ret = itemAccess;
+
+ break;
+ }
+ }
+ }
+
+ return ret;
+ }
}
+
+
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyItemEvaluator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyItemEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyItemEvaluator.java
new file mode 100644
index 0000000..bf9b243
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyItemEvaluator.java
@@ -0,0 +1,273 @@
+/*
+ * 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.policyevaluator;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Set;
+
+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.conditionevaluator.RangerConditionEvaluator;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerServiceDef;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition;
+import org.apache.ranger.plugin.model.RangerServiceDef.RangerPolicyConditionDef;
+import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
+import org.apache.ranger.plugin.policyengine.RangerAccessResult;
+import org.apache.ranger.plugin.policyengine.RangerPolicyEngine;
+import org.apache.ranger.plugin.policyengine.RangerPolicyEngineOptions;
+
+
+public class RangerDefaultPolicyItemEvaluator extends RangerAbstractPolicyItemEvaluator {
+ private static final Log LOG = LogFactory.getLog(RangerDefaultPolicyItemEvaluator.class);
+
+
+ public RangerDefaultPolicyItemEvaluator(RangerServiceDef serviceDef, RangerPolicy policy, RangerPolicyItem policyItem, RangerPolicyEngineOptions options) {
+ super(serviceDef, policy, policyItem, options);
+ }
+
+ public void init() {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerDefaultPolicyItemEvaluator(policyId=" + policyId + ", policyItem=" + policyItem + ", serviceType=" + getServiceType() + ", conditionsDisabled=" + getConditionsDisabledOption() + ")");
+ }
+
+ if (!getConditionsDisabledOption() && policyItem != null && CollectionUtils.isNotEmpty(policyItem.getConditions())) {
+ conditionEvaluators = new ArrayList<RangerConditionEvaluator>();
+
+ for (RangerPolicyItemCondition condition : policyItem.getConditions()) {
+ RangerPolicyConditionDef conditionDef = getConditionDef(condition.getType());
+
+ if (conditionDef == null) {
+ LOG.error("RangerDefaultPolicyItemEvaluator(policyId=" + policyId + "): conditionDef '" + condition.getType() + "' not found. Ignoring the condition");
+
+ continue;
+ }
+
+ RangerConditionEvaluator conditionEvaluator = newConditionEvaluator(conditionDef.getEvaluator());
+
+ if (conditionEvaluator != null) {
+ conditionEvaluator.setConditionDef(conditionDef);
+ conditionEvaluator.setPolicyItemCondition(condition);
+ conditionEvaluator.init();
+
+ conditionEvaluators.add(conditionEvaluator);
+ } else {
+ LOG.error("RangerDefaultPolicyItemEvaluator(policyId=" + policyId + "): failed to instantiate condition evaluator '" + condition.getType() + "'; evaluatorClassName='" + conditionDef.getEvaluator() + "'");
+ }
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerDefaultPolicyItemEvaluator(policyId=" + policyId + ", conditionsCount=" + getConditionEvaluators().size() + ")");
+ }
+ }
+
+ @Override
+ public void evaluate(RangerAccessRequest request, RangerAccessResult result) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerDefaultPolicyItemEvaluator.evaluate(" + request + ", " + result + ")");
+ }
+
+ if(policyItem != null) {
+ if(matchUserGroup(request.getUser(), request.getUserGroups())) {
+ if (request.isAccessTypeDelegatedAdmin()) { // used only in grant/revoke scenario
+ if (policyItem.getDelegateAdmin()) {
+ result.setIsAllowed(true);
+ result.setPolicyId(policyId);
+ }
+ } else if (CollectionUtils.isNotEmpty(policyItem.getAccesses())) {
+ boolean accessAllowed = false;
+
+ if (request.isAccessTypeAny()) {
+ for (RangerPolicy.RangerPolicyItemAccess access : policyItem.getAccesses()) {
+ if (access.getIsAllowed()) {
+ accessAllowed = true;
+ break;
+ }
+ }
+ } else {
+ for (RangerPolicy.RangerPolicyItemAccess access : policyItem.getAccesses()) {
+ if (access.getIsAllowed() && StringUtils.equalsIgnoreCase(access.getType(), request.getAccessType())) {
+ accessAllowed = true;
+ break;
+ }
+ }
+ }
+
+ if(accessAllowed) {
+ if(matchCustomConditions(request)) {
+ result.setIsAllowed(true);
+ result.setPolicyId(policyId);
+ }
+ }
+ }
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerDefaultPolicyItemEvaluator.evaluate(" + request + ", " + result + ")");
+ }
+ }
+
+ @Override
+ public boolean matchUserGroup(String user, Set<String> userGroups) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerDefaultPolicyItemEvaluator.matchUserGroup(" + policyItem + ", " + user + ", " + userGroups + ")");
+ }
+
+ boolean ret = false;
+
+ if(policyItem != null) {
+ if(!ret && user != null && policyItem.getUsers() != null) {
+ ret = policyItem.getUsers().contains(user);
+ }
+
+ if(!ret && userGroups != null && policyItem.getGroups() != null) {
+ ret = policyItem.getGroups().contains(RangerPolicyEngine.GROUP_PUBLIC) ||
+ !Collections.disjoint(policyItem.getGroups(), userGroups);
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerDefaultPolicyItemEvaluator.matchUserGroup(" + policyItem + ", " + user + ", " + userGroups + "): " + ret);
+ }
+
+ return ret;
+ }
+
+ @Override
+ public boolean matchAccessType(String accessType) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerDefaultPolicyItemEvaluator.matchAccessType(" + accessType + ")");
+ }
+
+ boolean ret = false;
+
+ if(policyItem != null) {
+ boolean isAdminAccess = StringUtils.equals(accessType, RangerPolicyEngine.ADMIN_ACCESS);
+
+ if(isAdminAccess) {
+ ret = policyItem.getDelegateAdmin();
+ } else {
+ if(CollectionUtils.isNotEmpty(policyItem.getAccesses())) {
+ boolean isAnyAccess = StringUtils.equals(accessType, RangerPolicyEngine.ANY_ACCESS);
+
+ for(RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) {
+ if(! itemAccess.getIsAllowed()) {
+ continue;
+ }
+
+ if(isAnyAccess) {
+ ret = true;
+
+ break;
+ } else if(StringUtils.equalsIgnoreCase(itemAccess.getType(), accessType)) {
+ ret = true;
+
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerDefaultPolicyItemEvaluator.matchAccessType(" + accessType + "): " + ret);
+ }
+
+ return ret;
+ }
+
+ @Override
+ public boolean matchCustomConditions(RangerAccessRequest request) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerDefaultPolicyItemEvaluator.matchCustomConditions(" + request + ")");
+ }
+
+ boolean ret = true;
+
+ if (CollectionUtils.isNotEmpty(conditionEvaluators)) {
+ for(RangerConditionEvaluator conditionEvaluator : conditionEvaluators) {
+ if(!conditionEvaluator.isMatched(request)) {
+ ret = false;
+
+ break;
+ }
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerDefaultPolicyItemEvaluator.matchCustomConditions(" + request + "): " + ret);
+ }
+
+ return ret;
+ }
+
+ RangerPolicyConditionDef getConditionDef(String conditionName) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerDefaultPolicyItemEvaluator.getConditionDef(" + conditionName + ")");
+ }
+
+ RangerPolicyConditionDef ret = null;
+
+ if (serviceDef != null && CollectionUtils.isNotEmpty(serviceDef.getPolicyConditions())) {
+ for(RangerPolicyConditionDef conditionDef : serviceDef.getPolicyConditions()) {
+ if(StringUtils.equals(conditionName, conditionDef.getName())) {
+ ret = conditionDef;
+
+ break;
+ }
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerDefaultPolicyItemEvaluator.getConditionDef(" + conditionName + "): " + ret);
+ }
+
+ return ret;
+ }
+
+ RangerConditionEvaluator newConditionEvaluator(String className) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerDefaultPolicyItemEvaluator.newConditionEvaluator(" + className + ")");
+ }
+
+ RangerConditionEvaluator evaluator = null;
+
+ try {
+ @SuppressWarnings("unchecked")
+ Class<RangerConditionEvaluator> matcherClass = (Class<RangerConditionEvaluator>)Class.forName(className);
+
+ evaluator = matcherClass.newInstance();
+ } catch(Throwable t) {
+ LOG.error("RangerDefaultPolicyItemEvaluator.newConditionEvaluator(" + className + "): error instantiating evaluator");
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerDefaultPolicyItemEvaluator.newConditionEvaluator(" + className + "): " + evaluator);
+ }
+
+ return evaluator;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/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 26d5223..4abc1bf 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
@@ -231,7 +231,7 @@ public class RangerOptimizedPolicyEvaluator extends RangerDefaultPolicyEvaluator
}
@Override
- protected void evaluatePolicyItemsForAccess(RangerPolicy policy, RangerAccessRequest request, RangerAccessResult result) {
+ protected void evaluatePolicyItemsForAccess(RangerAccessRequest request, RangerAccessResult result) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerOptimizedPolicyEvaluator.evaluatePolicyItemsForAccess()");
}
@@ -241,7 +241,7 @@ public class RangerOptimizedPolicyEvaluator extends RangerDefaultPolicyEvaluator
if (request.isAccessTypeAny() || (request.isAccessTypeDelegatedAdmin() && delegateAdmin) || hasAllPerms || accessPerms.contains(request.getAccessType())) {
// No need to reject based on aggregated access permissions
- super.evaluatePolicyItemsForAccess(policy, request, result);
+ super.evaluatePolicyItemsForAccess(request, result);
}
}
if(LOG.isDebugEnabled()) {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/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 9fe523a..624ff1c 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
@@ -23,7 +23,6 @@ package org.apache.ranger.plugin.policyevaluator;
import java.util.Map;
import java.util.Set;
-import org.apache.ranger.plugin.conditionevaluator.RangerConditionEvaluator;
import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
import org.apache.ranger.plugin.model.RangerServiceDef;
@@ -43,10 +42,12 @@ public interface RangerPolicyEvaluator extends Comparable<RangerPolicyEvaluator>
RangerServiceDef getServiceDef();
- Map<String, RangerConditionEvaluator> getConditionEvaluators();
-
int getEvalOrder();
+ int getCustomConditionsCount();
+
+ boolean isAuditEnabled();
+
void evaluate(RangerAccessRequest request, RangerAccessResult result);
boolean isMatch(RangerAccessResource resource);
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyItemEvaluator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyItemEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyItemEvaluator.java
new file mode 100644
index 0000000..9bbe4e3
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyItemEvaluator.java
@@ -0,0 +1,55 @@
+/*
+ * 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.policyevaluator;
+
+import java.util.List;
+import java.util.Set;
+
+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.RangerPolicyItem;
+import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
+import org.apache.ranger.plugin.policyengine.RangerAccessResult;
+
+public interface RangerPolicyItemEvaluator {
+
+ void init();
+
+ /*
+ RangerServiceDef getServiceDef();
+
+ RangerPolicy getPolicy();
+
+ RangerPolicyItem getPolicyItem();
+
+ long getPolicyId();
+ */
+
+ List<RangerConditionEvaluator> getConditionEvaluators();
+
+
+ void evaluate(RangerAccessRequest request, RangerAccessResult result);
+
+ boolean matchUserGroup(String user, Set<String> userGroups);
+
+ boolean matchAccessType(String accessType);
+
+ boolean matchCustomConditions(RangerAccessRequest request);
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/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 38b7302..59b7479 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
@@ -81,6 +81,13 @@ public class TestPolicyEngine {
runTestsFromResourceFiles(hbaseTestResourceFiles);
}
+ @Test
+ public void testPolicyEngine_conditions() {
+ String[] conditionsTestResourceFiles = { "/policyengine/test_policyengine_conditions.json" };
+
+ runTestsFromResourceFiles(conditionsTestResourceFiles);
+ }
+
private void runTestsFromResourceFiles(String[] resourceNames) {
for(String resourceName : resourceNames) {
InputStream inStream = this.getClass().getResourceAsStream(resourceName);
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/test/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluatorTest.java
----------------------------------------------------------------------
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluatorTest.java b/agents-common/src/test/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluatorTest.java
index 943b76a..9a3333c 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluatorTest.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluatorTest.java
@@ -20,23 +20,14 @@
package org.apache.ranger.plugin.policyevaluator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.ranger.plugin.conditionevaluator.RangerAbstractConditionEvaluator;
-import org.apache.ranger.plugin.conditionevaluator.RangerConditionEvaluator;
-import org.apache.ranger.plugin.conditionevaluator.RangerIpMatcher;
import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition;
@@ -45,9 +36,7 @@ import org.apache.ranger.plugin.model.RangerServiceDef.RangerPolicyConditionDef;
import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
import org.junit.After;
import org.junit.Before;
-import org.junit.Test;
-import com.google.common.collect.Lists;
public class RangerDefaultPolicyEvaluatorTest {
@@ -58,251 +47,6 @@ public class RangerDefaultPolicyEvaluatorTest {
@After
public void tearDown() throws Exception {
}
-
- @Test
- public void test_newConditionEvaulator() {
- RangerDefaultPolicyEvaluator evaluator = new RangerDefaultPolicyEvaluator();
- RangerConditionEvaluator ipMatcher = evaluator.newConditionEvaluator("org.apache.ranger.plugin.conditionevaluator.RangerIpMatcher");
- assertTrue(ipMatcher.getClass().equals(RangerIpMatcher.class));
-
- // bogus value will lead to null object from coming back
- ipMatcher = evaluator.newConditionEvaluator("org.apache.ranger.plugin.conditionevaluator.RangerIpMatcha");
- assertNull(ipMatcher);
- ipMatcher = evaluator.newConditionEvaluator("RangerIpMatcher");
- assertNull(ipMatcher);
- }
-
- @Test
- public void test_getConditionEvaluator() {
-
- // null service def and/or policy has reasonable response
- RangerDefaultPolicyEvaluator evaluator = new RangerDefaultPolicyEvaluator();
- RangerPolicyConditionDef conditionDef = evaluator.getConditionDef(null, null);
- assertNull(conditionDef);
-
- conditionDef = evaluator.getConditionDef(null, "aCondition");
- assertNull(conditionDef);
-
- RangerServiceDef serviceDef = mock(RangerServiceDef.class);
- conditionDef = evaluator.getConditionDef(null, null);
- assertNull(conditionDef);
-
- // null policy condition def collection should behave sensibly
- when(serviceDef.getPolicyConditions()).thenReturn(null);
- conditionDef = evaluator.getConditionDef(serviceDef, "aCondition");
- assertNull(conditionDef);
-
- // so should an service def with empty list of policy conditions.
- when(serviceDef.getPolicyConditions()).thenReturn(new ArrayList<RangerServiceDef.RangerPolicyConditionDef>());
- conditionDef = evaluator.getConditionDef(serviceDef, "aCondition");
- assertNull(conditionDef);
-
- // if service has a condition then sensible answer should come back
- RangerPolicyConditionDef aConditionDef = getMockPolicyConditionDef("type1", "com.company.SomeEvaluator", null);
-
- Map<String, String> evaluatorOptions = new HashMap<String, String>();
- evaluatorOptions.put("key1", "key1");
-
- RangerPolicyConditionDef anotherConditionDef = getMockPolicyConditionDef("type2", "com.company.AnotherEvaluator", evaluatorOptions);
- List<RangerPolicyConditionDef> conditionDefs = Lists.newArrayList(aConditionDef, anotherConditionDef);
-
- serviceDef = getMockServiceDef(conditionDefs);
- conditionDef = evaluator.getConditionDef(serviceDef, "type1");
- assertEquals(aConditionDef, conditionDef);
- conditionDef = evaluator.getConditionDef(serviceDef, "type2");
- assertEquals(anotherConditionDef, conditionDef);
- conditionDef = evaluator.getConditionDef(serviceDef, "type3");
- assertNull(conditionDef);
- }
-
- @Test
- public void test_initializeConditionEvaluators_firewalling() {
- RangerServiceDef serviceDef = null;
- RangerPolicy policy = null;
- // passing null values should yield sensible response
- RangerDefaultPolicyEvaluator policyEvaluator = new RangerDefaultPolicyEvaluator();
- Map<String, RangerConditionEvaluator> result = policyEvaluator.initializeConditionEvaluators(policy, serviceDef);
- assertNotNull(result);
- assertTrue(result.isEmpty());
-
- // or if is the policy item collection in the policy is null
- policy = mock(RangerPolicy.class);
- when(policy.getPolicyItems()).thenReturn(null);
- result = policyEvaluator.initializeConditionEvaluators(policy, serviceDef);
- assertNotNull(result);
- assertTrue(result.isEmpty());
-
- // or if the policy item collection is empty
- List<RangerPolicyItem> policyItems = new ArrayList<RangerPolicy.RangerPolicyItem>();
- when(policy.getPolicyItems()).thenReturn(policyItems);
- result = policyEvaluator.initializeConditionEvaluators(policy, serviceDef);
- assertNotNull(result);
- assertTrue(result.isEmpty());
-
- // or when the policy conditions collection is null
- RangerPolicyItem aPolicyItem = mock(RangerPolicyItem.class);
- when(aPolicyItem.getConditions()).thenReturn(null);
- policyItems.add(aPolicyItem);
- when(policy.getPolicyItems()).thenReturn(policyItems);
- result = policyEvaluator.initializeConditionEvaluators(policy, serviceDef);
- assertNotNull(result);
- assertTrue(result.isEmpty());
-
- // or when the policy conditions collection is not null but empty
- List<RangerPolicyItemCondition> itemConditions = new ArrayList<RangerPolicy.RangerPolicyItemCondition>();
- when(aPolicyItem.getConditions()).thenReturn(itemConditions);
- // remove left over from prior test
- policyItems.clear(); policyItems.add(aPolicyItem);
- when(policy.getPolicyItems()).thenReturn(policyItems);
- result = policyEvaluator.initializeConditionEvaluators(policy, serviceDef);
- assertNotNull(result);
- assertTrue(result.isEmpty());
-
- // or when any combination of fields of item conditions are null
- RangerPolicyItemCondition anItemCondition = mock(RangerPolicyItemCondition.class);
- when(anItemCondition.getType()).thenReturn(null);
- when(anItemCondition.getValues()).thenReturn(null);
- itemConditions.add(anItemCondition);
- when(aPolicyItem.getConditions()).thenReturn(itemConditions);
- policyItems.clear(); policyItems.add(aPolicyItem);
- when(policy.getPolicyItems()).thenReturn(policyItems);
- result = policyEvaluator.initializeConditionEvaluators(policy, serviceDef);
- assertNotNull(result);
- assertTrue(result.isEmpty());
- }
-
- @Test
- public void test_initializeConditionEvaluators_happyPath() {
- /*
- * A policy could contain several policy items and each policy item could contain non-overlapping sets of conditions in them.
- * Resulting map should contain a union of conditions in it and each pointing to correct evaluator object.
- */
- // first create a service with right condition-name and evaluator names
- Map<String, String[]> conditionEvaluatorMap = new HashMap<String, String[]>();
- conditionEvaluatorMap.put("c1", new String[] { "org.apache.ranger.plugin.policyevaluator.RangerDefaultPolicyEvaluatorTest$Evaluator1", null });
- conditionEvaluatorMap.put("c2", new String[] { "org.apache.ranger.plugin.policyevaluator.RangerDefaultPolicyEvaluatorTest$Evaluator2", null });
- conditionEvaluatorMap.put("c3", new String[] { "org.apache.ranger.plugin.policyevaluator.RangerDefaultPolicyEvaluatorTest$Evaluator3", null });
- conditionEvaluatorMap.put("c4", new String[] { "org.apache.ranger.plugin.policyevaluator.RangerDefaultPolicyEvaluatorTest$Evaluator4", null });
- RangerServiceDef serviceDef = getMockServiceDef(conditionEvaluatorMap);
- // create policy items each with overlapping but dissimilar sets of conditions in them.
- RangerPolicyItem anItem = getMockPolicyItem(new String[] {"c1", "c2"});
- RangerPolicyItem anotherItem = getMockPolicyItem(new String[] {"c2", "c3"});
- RangerPolicy policy = mock(RangerPolicy.class);
- when(policy.getPolicyItems()).thenReturn(Arrays.asList(anItem, anotherItem));
- RangerDefaultPolicyEvaluator policyEvaluator = new RangerDefaultPolicyEvaluator();
- Map<String, RangerConditionEvaluator> result = policyEvaluator.initializeConditionEvaluators(policy, serviceDef);
-
- assertNotNull(result);
- assertEquals(3, result.size());
- assertTrue(result.containsKey("c1"));
- assertTrue(result.containsKey("c2"));
- assertTrue(result.containsKey("c3"));
-
- RangerConditionEvaluator anEvaluator = result.get("c1");
- assertTrue(anEvaluator.getClass().equals(Evaluator1.class));
- anEvaluator = result.get("c2");
- assertTrue(anEvaluator.getClass().equals(Evaluator2.class));
- anEvaluator = result.get("c3");
- assertTrue(anEvaluator.getClass().equals(Evaluator3.class));
- }
-
- /**
- * Test classs: that exists only for testing purposes
- * @author alal
- *
- */
- static class AlwaysPass extends RangerAbstractConditionEvaluator {
-
- @Override
- public void init() {
- super.init();
- }
- @Override
- public boolean isMatched(RangerAccessRequest request) {
- return true;
- }
-
- }
-
- static class AlwaysFail extends RangerAbstractConditionEvaluator {
-
- @Override
- public void init() {
- super.init();
- }
-
- @Override
- public boolean isMatched(RangerAccessRequest request) {
- return false;
- }
-
- }
-
- static class Evaluator1 extends AlwaysPass {}
- static class Evaluator2 extends AlwaysPass {}
- static class Evaluator3 extends AlwaysFail {}
- static class Evaluator4 extends AlwaysFail {}
-
- /**
- * A request may contain a value for several conditions. A policy item could contain evaluators for more/different conditions than that are in the request.
- * check should fail if condition evaluator for any policy fails for a conditions contained in the request. If request does not have data for a condition
- * then it should succeed. Data in request for condition that are not part of the policy item shouldn't affect the result.
- */
- @Test
- public void test_matchCustomConditions_happyPath1() {
-
- // let's create the condition evaluator map for 4 conditions.
- Map<String, RangerConditionEvaluator> evaluators = createEvaluatorMap();
-
- // let's first create a request with 2 different conditions
- RangerAccessRequest request = createAccessRequestWithConditions(new String[] {"c1", "c2"});
-
- // Create a policy item -- which also has same exact same number of policy conditions defined on it (2)
- RangerPolicyItem policyItem = createPolicyItemForConditions(new String[] {"c1", "c2"} );
-
- // check for success
- RangerDefaultPolicyEvaluator policyEvaluator = new RangerDefaultPolicyEvaluator();
- boolean result = policyEvaluator.matchCustomConditions(policyItem, request, evaluators);
- assertTrue(result);
-
- // missing conditions on request are ok, too -- they always succeed
- // policy item has conditions c1 and c2 where as context will only have c1.
- request = createAccessRequestWithConditions(new String[] { "c1" } );
- result = policyEvaluator.matchCustomConditions(policyItem, request, evaluators);
- assertTrue(result);
-
- // Extra conditions on request are ok, too -- they always succeed
- // policy item has conditions c1 and c2 where as context has values for conditions c3 and c4 on it and we know their evaluators always fail!
- request = createAccessRequestWithConditions(new String[] {"c3", "c4"});
- result = policyEvaluator.matchCustomConditions(policyItem, request, evaluators);
- assertTrue(result);
- }
-
- @Test
- public void test_matchCustomConditions_happyPath2() {
- // let's create the condition evaluator map for 4 conditions and some more.
- Map<String, RangerConditionEvaluator> evaluators = createEvaluatorMap();
-
- // create policy item with a condition that we know will always fail
- RangerPolicyItem policyItem = createPolicyItemForConditions(new String[] { "c1", "c3" } );
-
- // let's first create a request with 2 different conditions
- RangerAccessRequest request = createAccessRequestWithConditions(new String[]{"c1", "c3"});
-
- RangerDefaultPolicyEvaluator policyEvaluator = new RangerDefaultPolicyEvaluator();
- boolean result = policyEvaluator.matchCustomConditions(policyItem, request, evaluators);
- assertFalse(result);
- }
-
- Map<String, RangerConditionEvaluator> createEvaluatorMap() {
- Map<String, RangerConditionEvaluator> map = new HashMap<String, RangerConditionEvaluator>();
- map.put("c1", new Evaluator1());
- map.put("c2", new Evaluator2());
- map.put("c3", new Evaluator3()); // conditions 3 and 4 would always fail!
- map.put("c4", new Evaluator4());
-
- return map;
- }
RangerPolicyItem getMockPolicyItem(String[] strings) {
RangerPolicyItem policyItem = mock(RangerPolicyItem.class);
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/test/resources/policyengine/test_policyengine_conditions.json
----------------------------------------------------------------------
diff --git a/agents-common/src/test/resources/policyengine/test_policyengine_conditions.json b/agents-common/src/test/resources/policyengine/test_policyengine_conditions.json
new file mode 100644
index 0000000..2ab2bee
--- /dev/null
+++ b/agents-common/src/test/resources/policyengine/test_policyengine_conditions.json
@@ -0,0 +1,230 @@
+{
+ "serviceName":"hivedev",
+
+ "serviceDef":{
+ "name":"hive",
+ "id":3,
+ "resources":[
+ {"name":"database","level":1,"mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"Hive Database","description":"Hive Database"},
+ {"name":"table","level":2,"parent":"database","mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"Hive Table","description":"Hive Table"},
+ {"name":"udf","level":2,"parent":"database","mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"Hive UDF","description":"Hive UDF"},
+ {"name":"column","level":3,"parent":"table","mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"Hive Column","description":"Hive Column"}
+ ],
+ "accessTypes":[
+ {"name":"select","label":"Select"},
+ {"name":"update","label":"Update"},
+ {"name":"create","label":"Create"},
+ {"name":"drop","label":"Drop"},
+ {"name":"alter","label":"Alter"},
+ {"name":"index","label":"Index"},
+ {"name":"lock","label":"Lock"},
+ {"name":"all","label":"All"}
+ ],
+ "policyConditions":[
+ {"name":"country", "evaluator":"org.apache.ranger.plugin.conditionevaluator.RangerSimpleMatcher", "evaluatorOptions":{"CONTEXT_NAME":"country"}}
+ ]
+ },
+
+ "policies":[
+ {"id":1,"name":"db=default; allow select from all countries","isEnabled":true,"isAuditEnabled":true,
+ "resources":{"database":{"values":["default"]},"table":{"values":["*"]},"column":{"values":["*"]}},
+ "policyItems":[
+ {"accesses":[{"type":"select"}],"users":[],"groups":["public"],"delegateAdmin":false}
+ ]
+ }
+ ,
+ {"id":2,"name":"db=default: allow create only from US","isEnabled":true,"isAuditEnabled":true,
+ "resources":{"database":{"values":["default"]},"table":{"values":["*"]},"column":{"values":["*"]}},
+ "policyItems":[
+ {"accesses":[{"type":"create"}],"users":[],"groups":["public"],"delegateAdmin":false, "conditions":[{"type":"country","values":["US"]}]}
+ ]
+ }
+ ,
+ {"id":3,"name":"db=default: allow update from US,CA","isEnabled":true,"isAuditEnabled":true,
+ "resources":{"database":{"values":["default"]},"table":{"values":["*"]},"column":{"values":["*"]}},
+ "policyItems":[
+ {"accesses":[{"type":"update"}],"users":[],"groups":["public"],"delegateAdmin":false, "conditions":[{"type":"country","values":["US","CA"]}]}
+ ]
+ }
+ ,
+ {"id":4,"name":"db=default: user1 allowed to drop from US; user1 allowed to index from US,CA; user2 allowed to alter from US","isEnabled":true,"isAuditEnabled":true,
+ "resources":{"database":{"values":["default"]},"table":{"values":["*"]},"column":{"values":["*"]}},
+ "policyItems":[
+ {"accesses":[{"type":"drop"}],"users":["user1"],"groups":[],"delegateAdmin":false, "conditions":[{"type":"country","values":["US"]}]},
+ {"accesses":[{"type":"index"}],"users":["user1"],"groups":[],"delegateAdmin":false, "conditions":[{"type":"country","values":["US","CA"]}]},
+ {"accesses":[{"type":"alter"}],"users":["user2"],"groups":[],"delegateAdmin":false, "conditions":[{"type":"country","values":["US"]}]}
+ ]
+ }
+ ],
+
+ "tests":[
+ {"name":"ALLOW 'use default;' no country",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"","user":"user1","userGroups":["users"],"requestData":"use default"
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":1}
+ }
+ ,
+ {"name":"DENY 'create default.testTable;' no country",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"create","user":"user1","userGroups":["users"],"requestData":"create default.testTable"
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"DENY 'update default.testTable;' no country",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"update","user":"user1","userGroups":["users"],"requestData":"update default.testTable"
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"ALLOW 'create default.testTable;' country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"create","user":"user1","userGroups":["users"],"requestData":"create default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":2}
+ }
+ ,
+ {"name":"DENY 'create default.testTable;' country=CA",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"create","user":"user1","userGroups":["users"],"requestData":"create default.testTable",
+ "context":{"country":"CA"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"ALLOW 'update default.testTable;' country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"update","user":"user1","userGroups":["users"],"requestData":"update default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":3}
+ }
+ ,
+ {"name":"ALLOW 'update default.testTable;' country=CA",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"update","user":"user1","userGroups":["users"],"requestData":"update default.testTable",
+ "context":{"country":"CA"}
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":3}
+ }
+ ,
+ {"name":"DENY 'update default.testTable;' country=UK",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"update","user":"user1","userGroups":["users"],"requestData":"update default.testTable",
+ "context":{"country":"UK"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"ALLOW 'drop default.testTable;' user1, country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"drop","user":"user1","userGroups":["users"],"requestData":"drop default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":4}
+ }
+ ,
+ {"name":"DENY 'drop default.testTable;' user1, country=CA",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"drop","user":"user1","userGroups":["users"],"requestData":"drop default.testTable",
+ "context":{"country":"CA"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"DENY 'drop default.testTable;' user2, country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"drop","user":"user2","userGroups":["users"],"requestData":"drop default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"ALLOW 'index default.testTable;' user1, country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"index","user":"user1","userGroups":["users"],"requestData":"index default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":4}
+ }
+ ,
+ {"name":"ALLOW 'index default.testTable;' user1, country=CA",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"index","user":"user1","userGroups":["users"],"requestData":"index default.testTable",
+ "context":{"country":"CA"}
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":4}
+ }
+ ,
+ {"name":"DENY 'index default.testTable;' user1, country=UK",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"index","user":"user1","userGroups":["users"],"requestData":"index default.testTable",
+ "context":{"country":"UK"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"DENY 'index default.testTable;' user2, country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"index","user":"user2","userGroups":["users"],"requestData":"index default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"DENY 'index default.testTable;' user2, country=UK",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"index","user":"user2","userGroups":["users"],"requestData":"index default.testTable",
+ "context":{"country":"CA"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"ALLOW 'alter default.testTable;' user2, country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"alter","user":"user2","userGroups":["users"],"requestData":"alter default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":true,"policyId":4}
+ }
+ ,
+ {"name":"DENY 'alter default.testTable;' user2, country=CA",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"alter","user":"user2","userGroups":["users"],"requestData":"alter default.testTable",
+ "context":{"country":"CA"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ,
+ {"name":"DENY 'alter default.testTable;' user1, country=US",
+ "request":{
+ "resource":{"elements":{"database":"default"}},
+ "accessType":"alter","user":"user1","userGroups":["users"],"requestData":"alter default.testTable",
+ "context":{"country":"US"}
+ },
+ "result":{"isAudited":true,"isAllowed":false,"policyId":-1}
+ }
+ ]
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/c5f61c89/agents-common/src/test/resources/policyengine/test_policyengine_hbase.json
----------------------------------------------------------------------
diff --git a/agents-common/src/test/resources/policyengine/test_policyengine_hbase.json b/agents-common/src/test/resources/policyengine/test_policyengine_hbase.json
index 338d4cf..de9c130 100644
--- a/agents-common/src/test/resources/policyengine/test_policyengine_hbase.json
+++ b/agents-common/src/test/resources/policyengine/test_policyengine_hbase.json
@@ -6,7 +6,7 @@
"id":2,
"resources":[
{"name":"table","level":1,"parent":"","mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"HBase Table","description":"HBase Table"},
- {"name":"column-family","level":2,"table":"database","mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"HBase Column-Family","description":"HBase Column-Family"},
+ {"name":"column-family","level":2,"parent":"table","mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"HBase Column-Family","description":"HBase Column-Family"},
{"name":"column","level":3,"parent":"column-family","mandatory":true,"lookupSupported":true,"matcher":"org.apache.ranger.plugin.resourcematcher.RangerDefaultResourceMatcher","matcherOptions":{"wildCard":true, "ignoreCase":true},"label":"HBase Column","description":"HBase Column"}
],
"accessTypes":[
[5/9] incubator-ranger git commit: RANGER-538: fix - error messages
shown in ranger-admin lack details
Posted by ma...@apache.org.
RANGER-538: fix - error messages shown in ranger-admin lack details
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/43841b7a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/43841b7a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/43841b7a
Branch: refs/heads/tag-policy
Commit: 43841b7a546fd7857a24dea8dad3bdfe7c84a0fa
Parents: 08990c5
Author: Madhan Neethiraj <ma...@apache.org>
Authored: Mon Jun 8 15:50:44 2015 -0700
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Tue Jun 9 18:56:24 2015 -0700
----------------------------------------------------------------------
.../org/apache/ranger/common/RESTErrorUtil.java | 9 +
.../org/apache/ranger/common/ServiceUtil.java | 2 +-
.../java/org/apache/ranger/rest/AssetREST.java | 25 +--
.../org/apache/ranger/rest/ServiceREST.java | 164 ++++++++++++-------
.../org/apache/ranger/rest/TestServiceREST.java | 16 +-
5 files changed, 134 insertions(+), 82 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/43841b7a/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java b/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java
index a17da9b..c46964c 100644
--- a/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java
+++ b/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java
@@ -289,6 +289,15 @@ public class RESTErrorUtil {
return webAppEx;
}
+ public WebApplicationException createRESTException(String errorMessage) {
+ VXResponse gjResponse = new VXResponse();
+ gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ gjResponse.setMsgDesc(errorMessage);
+ WebApplicationException webAppEx = createRESTException(gjResponse);
+ logger.info("Operation error. response=" + gjResponse, webAppEx);
+ return webAppEx;
+ }
+
public WebApplicationException createRESTException(String errorMessage,
MessageEnums messageEnum) {
List<VXMessage> messageList = new ArrayList<VXMessage>();
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/43841b7a/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java b/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java
index 7c2bbdc..8a637a0 100644
--- a/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java
+++ b/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java
@@ -378,7 +378,7 @@ public class ServiceUtil {
private Map<String, RangerPolicy.RangerPolicyResource> toRangerResourceList(String resourceString, String resourceType, Boolean isExcludes, Boolean isRecursive, Map<String, RangerPolicy.RangerPolicyResource> resources) {
Map<String, RangerPolicy.RangerPolicyResource> ret = resources == null ? new HashMap<String, RangerPolicy.RangerPolicyResource>() : resources;
- if(resourceString != null) {
+ if(StringUtils.isNotBlank(resourceString)) {
RangerPolicy.RangerPolicyResource resource = ret.get(resourceType);
if(resource == null) {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/43841b7a/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java b/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java
index 16528bd..e5de160 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java
@@ -34,6 +34,7 @@ import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@@ -650,13 +651,15 @@ public class AssetREST {
GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy);
try {
ret = serviceREST.grantAccess(serviceName, grantRevokeRequest, request);
- } catch (Exception e) {
- logger.error( HttpServletResponse.SC_BAD_REQUEST + "Grant Access Failed for the request " + vXPolicy );
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Grant Access Failed for the request " + e.getMessage(), true);
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable e) {
+ logger.error( HttpServletResponse.SC_BAD_REQUEST + "Grant Access Failed for the request " + vXPolicy, e);
+ throw restErrorUtil.createRESTException("Grant Access Failed for the request: " + vXPolicy + ". " + e.getMessage());
}
} else {
- logger.error( HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter " + vXPolicy );
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Bad Request parameter " , true);
+ logger.error( HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter");
+ throw restErrorUtil.createRESTException("Bad Request parameter");
}
if(logger.isDebugEnabled()) {
@@ -683,13 +686,15 @@ public class AssetREST {
GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy);
try {
ret = serviceREST.revokeAccess(serviceName, grantRevokeRequest, request);
- } catch (Exception e) {
- logger.error( HttpServletResponse.SC_BAD_REQUEST + "Revoke Access Failed for the request " + vXPolicy );
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Grant Access Failed for the request " + e.getMessage(), true);
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable e) {
+ logger.error( HttpServletResponse.SC_BAD_REQUEST + "Revoke Access Failed for the request " + vXPolicy, e);
+ throw restErrorUtil.createRESTException("Revoke Access Failed for the request: " + vXPolicy + ". " + e.getMessage());
}
} else {
- logger.error( HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter " + vXPolicy );
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Bad Request parameter " , true);
+ logger.error( HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter");
+ throw restErrorUtil.createRESTException("Bad Request parameter");
}
if(logger.isDebugEnabled()) {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/43841b7a/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 f9464ec..3d2e8b0 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
@@ -171,10 +171,12 @@ public class ServiceREST {
bizUtil.hasKMSPermissions("Service-Def", serviceDef.getImplClass());
ret = svcStore.createServiceDef(serviceDef);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("createServiceDef(" + serviceDef + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -203,10 +205,12 @@ public class ServiceREST {
bizUtil.hasKMSPermissions("Service-Def", serviceDef.getImplClass());
ret = svcStore.updateServiceDef(serviceDef);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("updateServiceDef(" + serviceDef + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -240,10 +244,12 @@ public class ServiceREST {
}
svcStore.deleteServiceDef(id, forceDelete);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("deleteServiceDef(" + id + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -270,10 +276,12 @@ public class ServiceREST {
}
ret = svcStore.getServiceDef(id);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("getServiceDef(" + id + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(ret == null) {
@@ -308,10 +316,12 @@ public class ServiceREST {
}
ret = svcStore.getServiceDefByName(name);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("getServiceDefByName(" + name + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(ret == null) {
@@ -339,10 +349,12 @@ public class ServiceREST {
try {
ret = svcStore.getPaginatedServiceDefs(filter);
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServiceDefs() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (LOG.isDebugEnabled()) {
@@ -375,10 +387,12 @@ public class ServiceREST {
bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname());
ret = svcStore.createService(service);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("createService(" + service + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -412,10 +426,12 @@ public class ServiceREST {
bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname());
ret = svcStore.updateService(service);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("updateService(" + service + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -448,10 +464,12 @@ public class ServiceREST {
bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname());
svcStore.deleteService(id);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("deleteService(" + id + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -471,10 +489,12 @@ public class ServiceREST {
try {
ret = svcStore.getService(id);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("getService(" + id + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(ret == null) {
@@ -500,10 +520,12 @@ public class ServiceREST {
try {
ret = svcStore.getServiceByName(name);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("getServiceByName(" + name + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(ret == null) {
@@ -531,10 +553,12 @@ public class ServiceREST {
try {
ret = svcStore.getPaginatedServices(filter);
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServices() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (LOG.isDebugEnabled()) {
@@ -552,10 +576,12 @@ public class ServiceREST {
try {
ret = svcStore.getServices(filter);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("getServices() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -580,10 +606,12 @@ public class ServiceREST {
List<RangerService> services = getServices(request).getServices();
ret = new Long(services == null ? 0 : services.size());
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("countServices() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -605,10 +633,12 @@ public class ServiceREST {
try {
ret = serviceMgr.validateConfig(service, svcStore);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("validateConfig(" + service + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -630,10 +660,12 @@ public class ServiceREST {
try {
ret = serviceMgr.lookupResource(serviceName,context, svcStore);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("lookupResource(" + serviceName + ", " + context + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -779,10 +811,10 @@ public class ServiceREST {
}
} catch(WebApplicationException excp) {
throw excp;
- } catch(Exception excp) {
+ } catch(Throwable excp) {
LOG.error("grantAccess(" + serviceName + ", " + grantRequest + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
ret.setStatusCode(RESTResponse.STATUS_SUCCESS);
@@ -876,10 +908,10 @@ public class ServiceREST {
}
} catch(WebApplicationException excp) {
throw excp;
- } catch(Exception excp) {
+ } catch(Throwable excp) {
LOG.error("revokeAccess(" + serviceName + ", " + revokeRequest + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
ret.setStatusCode(RESTResponse.STATUS_SUCCESS);
@@ -926,14 +958,12 @@ public class ServiceREST {
ensureAdminAccess(policy.getService(), policy.getResources());
ret = svcStore.createPolicy(policy);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("createPolicy(" + policy + ") failed", excp);
- if(excp instanceof WebApplicationException) {
- throw (WebApplicationException)excp;
- }
-
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -960,10 +990,12 @@ public class ServiceREST {
ensureAdminAccess(policy.getService(), policy.getResources());
ret = svcStore.updatePolicy(policy);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("updatePolicy(" + policy + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -990,10 +1022,12 @@ public class ServiceREST {
ensureAdminAccess(policy.getService(), policy.getResources());
svcStore.deletePolicy(id);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("deletePolicy(" + id + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -1017,10 +1051,12 @@ public class ServiceREST {
if(ret != null) {
ensureAdminAccess(ret.getService(), ret.getResources());
}
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("getPolicy(" + id + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(ret == null) {
@@ -1050,10 +1086,12 @@ public class ServiceREST {
ret = svcStore.getPaginatedPolicies(filter);
applyAdminAccessFilter(ret);
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getPolicies() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (LOG.isDebugEnabled()) {
@@ -1073,10 +1111,12 @@ public class ServiceREST {
ret = svcStore.getPolicies(filter);
applyAdminAccessFilter(ret);
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("getPolicies() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -1102,10 +1142,12 @@ public class ServiceREST {
applyAdminAccessFilter(policies);
ret = new Long(policies == null ? 0 : policies.size());
- } catch(Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch(Throwable excp) {
LOG.error("countPolicies() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if(LOG.isDebugEnabled()) {
@@ -1132,10 +1174,12 @@ public class ServiceREST {
ret = svcStore.getPaginatedServicePolicies(serviceId, filter);
applyAdminAccessFilter(ret);
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServicePolicies(" + serviceId + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (ret == null) {
@@ -1166,10 +1210,12 @@ public class ServiceREST {
ret = svcStore.getPaginatedServicePolicies(serviceName, filter);
applyAdminAccessFilter(ret);
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServicePolicies(" + serviceName + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (ret == null) {
@@ -1211,7 +1257,7 @@ public class ServiceREST {
httpCode = HttpServletResponse.SC_OK;
logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : 0) + " policies. Policy version=" + ret.getPolicyVersion();
}
- } catch(Exception excp) {
+ } catch(Throwable excp) {
LOG.error("getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ") failed", excp);
httpCode = HttpServletResponse.SC_BAD_REQUEST;
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/43841b7a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
index f024b99..e7324a1 100644
--- a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
+++ b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
@@ -742,9 +742,7 @@ public class TestServiceREST {
Mockito.when(userMgr.getGroupsForUser(userName)).thenReturn(
userGroupsList);
- Mockito.when(
- restErrorUtil.createRESTException(
- HttpServletResponse.SC_BAD_REQUEST, null, true))
+ Mockito.when(restErrorUtil.createRESTException((String)null))
.thenThrow(new WebApplicationException());
thrown.expect(WebApplicationException.class);
@@ -780,9 +778,7 @@ public class TestServiceREST {
Mockito.when(userMgr.getGroupsForUser(userName)).thenReturn(
userGroupsList);
- Mockito.when(
- restErrorUtil.createRESTException(
- HttpServletResponse.SC_BAD_REQUEST, null, true))
+ Mockito.when(restErrorUtil.createRESTException((String)null))
.thenThrow(new WebApplicationException());
thrown.expect(WebApplicationException.class);
RangerPolicy dbRangerPolicy = serviceREST.updatePolicy(rangerPolicy);
@@ -815,9 +811,7 @@ public class TestServiceREST {
Mockito.when(userMgr.getGroupsForUser(userName)).thenReturn(
userGroupsList);
- Mockito.when(
- restErrorUtil.createRESTException(
- HttpServletResponse.SC_BAD_REQUEST, null, true))
+ Mockito.when(restErrorUtil.createRESTException((String)null))
.thenThrow(new WebApplicationException());
thrown.expect(WebApplicationException.class);
serviceREST.deletePolicy(rangerPolicy.getId());
@@ -848,9 +842,7 @@ public class TestServiceREST {
Mockito.when(userMgr.getGroupsForUser(userName)).thenReturn(
userGroupsList);
- Mockito.when(
- restErrorUtil.createRESTException(
- HttpServletResponse.SC_BAD_REQUEST, null, true))
+ Mockito.when(restErrorUtil.createRESTException((String)null))
.thenThrow(new WebApplicationException());
thrown.expect(WebApplicationException.class);
RangerPolicy dbRangerPolicy = serviceREST.getPolicy(rangerPolicy
[7/9] incubator-ranger git commit: RANGER-545 : Fix js error for
lower versions of FF (<30)
Posted by ma...@apache.org.
RANGER-545 : Fix js error for lower versions of FF (<30)
Signed-off-by: Velmurugan Periasamy <ve...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/89002025
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/89002025
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/89002025
Branch: refs/heads/tag-policy
Commit: 89002025e57cf235cbf4c248eb7e468dad9378fb
Parents: 0d38f0f
Author: Gautam Borad <gb...@gmail.com>
Authored: Thu Jun 11 00:54:26 2015 +0530
Committer: Velmurugan Periasamy <ve...@apache.org>
Committed: Wed Jun 10 14:42:35 2015 -0700
----------------------------------------------------------------------
.../RangerAuthenticationEntryPoint.java | 54 +++++++++++---------
.../webapp/scripts/views/service/ServiceForm.js | 6 ++-
2 files changed, 33 insertions(+), 27 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/89002025/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java
index 941db5b..a3f3ed5 100644
--- a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java
+++ b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java
@@ -31,6 +31,7 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
+import org.apache.ranger.biz.SessionMgr;
import org.apache.ranger.common.JSONUtil;
import org.apache.ranger.common.PropertiesUtil;
import org.apache.ranger.common.RangerConfigUtil;
@@ -47,7 +48,8 @@ public class RangerAuthenticationEntryPoint extends
LoginUrlAuthenticationEntryPoint {
public static final int SC_AUTHENTICATION_TIMEOUT = 419;
- static Logger logger = Logger.getLogger(RangerAuthenticationEntryPoint.class);
+ static Logger logger = Logger
+ .getLogger(RangerAuthenticationEntryPoint.class);
static int ajaxReturnCode = -1;
@Autowired
@@ -55,6 +57,9 @@ public class RangerAuthenticationEntryPoint extends
@Autowired
JSONUtil jsonUtil;
+
+ @Autowired
+ SessionMgr sessionMgr;
public RangerAuthenticationEntryPoint() {
super();
@@ -63,7 +68,8 @@ public class RangerAuthenticationEntryPoint extends
}
if (ajaxReturnCode < 0) {
- ajaxReturnCode = PropertiesUtil.getIntProperty("ranger.ajax.auth.required.code", 401);
+ ajaxReturnCode = PropertiesUtil.getIntProperty(
+ "ranger.ajax.auth.required.code", 401);
}
}
@@ -71,35 +77,33 @@ public class RangerAuthenticationEntryPoint extends
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
- HttpSession httpSession = request.getSession();
String ajaxRequestHeader = request.getHeader("X-Requested-With");
if (logger.isDebugEnabled()) {
logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
}
- String requestURL = (request.getRequestURL() != null) ? request.getRequestURL().toString() : "";
- String servletPath = PropertiesUtil.getProperty("ranger.servlet.mapping.url.pattern", "service");
- String reqServletPath = configUtil.getWebAppRootURL() + "/" + servletPath;
-
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- // getting the current date in milliseconds
- Date curentDate = new Date();
- Long currentDateInMillis = (long) (((((curentDate.getHours() * 60) + curentDate
- .getMinutes()) * 60) + curentDate.getSeconds()) * 1000);
- // checking session timeout occurence
- if (httpSession.getMaxInactiveInterval() * 60000 >= (currentDateInMillis - httpSession
- .getLastAccessedTime())) {
- ajaxRequestHeader = null;
- VXResponse vXResponse = new VXResponse();
-
- vXResponse.setStatusCode(SC_AUTHENTICATION_TIMEOUT);
- vXResponse.setMsgDesc("Session Timeout");
-
- response.setStatus(SC_AUTHENTICATION_TIMEOUT);
- response.getWriter()
- .write(jsonUtil.writeObjectAsString(vXResponse));
+ String requestURL = (request.getRequestURL() != null) ? request
+ .getRequestURL().toString() : "";
+ String servletPath = PropertiesUtil.getProperty(
+ "ranger.servlet.mapping.url.pattern", "service");
+ String reqServletPath = configUtil.getWebAppRootURL() + "/"
+ + servletPath;
+
+ if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
+ try {
+
+ VXResponse vXResponse = new VXResponse();
+
+ vXResponse.setStatusCode(SC_AUTHENTICATION_TIMEOUT);
+ vXResponse.setMsgDesc("Session Timeout");
+ response.setStatus(SC_AUTHENTICATION_TIMEOUT);
+ response.getWriter().write(
+ jsonUtil.writeObjectAsString(vXResponse));
+ } catch (IOException e) {
+ logger.info("Error while writing JSON in HttpServletResponse");
+ }
+ return;
} else {
try {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/89002025/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js b/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
index a3ac650..f073036 100644
--- a/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
+++ b/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
@@ -155,9 +155,11 @@ define(function(require){
if(obj.type == 'bool'){
config[obj.name] = that.getBooleanForConfig(obj, that.model);
}else{
- config[obj.name] = that.model.get(obj.name).toString();
+ config[obj.name] = _.isNull(that.model.get(obj.name)) ? "" : that.model.get(obj.name).toString();
+ }
+ if(!_.isNull(obj.name)) {
+ that.model.unset(obj.name);
}
- that.model.unset(obj.name);
}
});
this.extraConfigColl.each(function(obj){ config[obj.get('name')] = obj.get('value');})
[6/9] incubator-ranger git commit: RANGER-533 Hbase plugin: access
denied during get/scan if user does not have family level acces to any family
in a table.
Posted by ma...@apache.org.
RANGER-533 Hbase plugin: access denied during get/scan if user does not have family level acces to any family in a table.
Signed-off-by: Madhan Neethiraj <ma...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/0d38f0f2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/0d38f0f2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/0d38f0f2
Branch: refs/heads/tag-policy
Commit: 0d38f0f2c37fef8fb293c37899dfd377afe7688e
Parents: 43841b7
Author: Alok Lal <al...@hortonworks.com>
Authored: Wed Jun 3 17:45:18 2015 -0700
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Wed Jun 10 00:33:11 2015 -0700
----------------------------------------------------------------------
.../model/validation/RangerPolicyValidator.java | 8 +
.../hbase/AuthorizationSession.java | 21 +-
.../authorization/hbase/HbaseAuditHandler.java | 4 +-
.../hbase/HbaseAuditHandlerImpl.java | 61 +++-
.../hbase/RangerAuthorizationCoprocessor.java | 295 +++++++++++--------
.../hbase/RangerAuthorizationFilter.java | 134 ++++++---
.../hbase/RangerAuthorizationFilterTest.java | 120 ++++----
7 files changed, 419 insertions(+), 224 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/0d38f0f2/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
index cea3e05..d27b667 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
@@ -320,6 +320,10 @@ public class RangerPolicyValidator extends RangerValidator {
policyResources.toString(), toStringHierarchies_all(hierarchies, defHelper)))
.build());
valid = false;
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isValidResourceNames: Found compatible hierarchies: " + toStringHierarchies_all(candidateHierarchies, defHelper));
+ }
}
/*
* Among the candidate hierarchies there should be at least one for which policy specifies all of the mandatory resources. Note that there could be multiple
@@ -335,6 +339,10 @@ public class RangerPolicyValidator extends RangerValidator {
.becauseOf("policy is missing required resources. Mandatory fields of potential hierarchies are: " + toStringHierarchies_mandatory(candidateHierarchies, defHelper))
.build());
valid = false;
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isValidResourceNames: Found hierarchies with all mandatory fields specified: " + toStringHierarchies_mandatory(validHierarchies, defHelper));
+ }
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/0d38f0f2/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
index e0b652e..006629b 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
@@ -179,9 +179,9 @@ public class AuthorizationSession {
AuthorizationSession authorize() {
if (LOG.isDebugEnabled()) {
- String message = "authorize: " + getRequestMessage();
- LOG.debug(message);
+ LOG.debug("==> AuthorizationSession.authorize: " + getRequestMessage());
}
+
if (_request == null) {
String message = String.format("Invalid state transition: buildRequest() must be called before authorize(). This request would ultimately get denied.!");
throw new IllegalStateException(message);
@@ -195,11 +195,11 @@ public class AuthorizationSession {
}
_result = _authorizer.isAccessAllowed(_request, _auditHandler);
}
+
if (LOG.isDebugEnabled()) {
boolean allowed = isAuthorized();
String reason = getDenialReason();
- String message = "AuthorizationSession.authorize: " + getLogMessage(allowed, reason);
- LOG.debug(message);
+ LOG.debug("<== AuthorizationSession.authorize: " + getLogMessage(allowed, reason));
}
return this;
}
@@ -212,7 +212,10 @@ public class AuthorizationSession {
}
void publishResults() throws AccessDeniedException {
-
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("==> AuthorizationSession.publishResults()");
+ }
+
boolean authorized = isAuthorized();
if (_auditHandler != null) {
List<AuthzAuditEvent> events = null;
@@ -226,7 +229,7 @@ public class AuthorizationSession {
events = theseEvents;
}
} else {
- AuthzAuditEvent event = _auditHandler.discardMostRecentEvent();
+ AuthzAuditEvent event = _auditHandler.getAndDiscardMostRecentEvent();
if (event != null) {
events = Lists.newArrayList(event);
}
@@ -244,10 +247,14 @@ public class AuthorizationSession {
String reason = getDenialReason();
String message = getLogMessage(false, reason);
if (LOG.isDebugEnabled()) {
- LOG.debug("AuthorizationSession.publishResults: throwing exception: " + message);
+ LOG.debug("<== AuthorizationSession.publishResults: throwing exception: " + message);
}
throw new AccessDeniedException("Insufficient permissions for user '" + _user.getName() + "' (action=" + _access + ")");
}
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("<== AuthorizationSession.publishResults()");
+ }
}
boolean isAudited() {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/0d38f0f2/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandler.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandler.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandler.java
index bbff6df..c77dc20 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandler.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandler.java
@@ -37,10 +37,10 @@ public interface HbaseAuditHandler extends RangerAccessResultProcessor {
* After this call the last set of audit events won't be returned by <code>getCapturedEvents</code>.
* @return
*/
- AuthzAuditEvent discardMostRecentEvent();
+ AuthzAuditEvent getAndDiscardMostRecentEvent();
/**
- * This is a complement to <code>discardMostRecentEvent</code> to set the most recent events. Often useful to un-pop audit messages that were take out.
+ * This is a complement to <code>getAndDiscardMostRecentEvent</code> to set the most recent events. Often useful to un-pop audit messages that were take out.
* @param capturedEvents
*/
void setMostRecentEvent(AuthzAuditEvent capturedEvents);
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/0d38f0f2/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandlerImpl.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandlerImpl.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandlerImpl.java
index e383614..6fbf5fc 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandlerImpl.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HbaseAuditHandlerImpl.java
@@ -21,12 +21,15 @@ package org.apache.ranger.authorization.hbase;
import java.util.ArrayList;
import java.util.List;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.apache.ranger.audit.model.AuthzAuditEvent;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
import org.apache.ranger.plugin.policyengine.RangerAccessResult;
public class HbaseAuditHandlerImpl extends RangerDefaultAuditHandler implements HbaseAuditHandler {
+ private static final Log LOG = LogFactory.getLog(HbaseAuditHandlerImpl.class);
static final List<AuthzAuditEvent> _EmptyList = new ArrayList<AuthzAuditEvent>();
final List<AuthzAuditEvent> _allEvents = new ArrayList<AuthzAuditEvent>();
// we replace its contents anytime new audit events are generated.
@@ -35,55 +38,109 @@ public class HbaseAuditHandlerImpl extends RangerDefaultAuditHandler implements
@Override
public AuthzAuditEvent getAuthzEvents(RangerAccessResult result) {
-
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> HbaseAuditHandlerImpl.getAuthzEvents(" + result + ")");
+ }
+
AuthzAuditEvent event = super.getAuthzEvents(result);
// first accumulate last set of events and then capture these as the most recent ones
if (_mostRecentEvent != null) {
+ LOG.debug("getAuthzEvents: got one event from default audit handler");
_allEvents.add(_mostRecentEvent);
+ } else {
+ LOG.debug("getAuthzEvents: no event produced by default audit handler");
}
_mostRecentEvent = event;
+
// We return null because we don't want default audit handler to audit anything!
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== HbaseAuditHandlerImpl.getAuthzEvents(" + result + "): null");
+ }
return null;
}
@Override
public List<AuthzAuditEvent> getCapturedEvents() {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> HbaseAuditHandlerImpl.getCapturedEvents()");
+ }
+
// construct a new collection since we don't want to lose track of which were the most recent events;
List<AuthzAuditEvent> result = new ArrayList<AuthzAuditEvent>(_allEvents);
if (_mostRecentEvent != null) {
result.add(_mostRecentEvent);
}
applySuperUserOverride(result);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== HbaseAuditHandlerImpl.getAuthzEvents(): count[" + result.size() + "] :result : " + result);
+ }
return result;
}
@Override
- public AuthzAuditEvent discardMostRecentEvent() {
+ public AuthzAuditEvent getAndDiscardMostRecentEvent() {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> HbaseAuditHandlerImpl.getAndDiscardMostRecentEvent():");
+ }
+
AuthzAuditEvent result = _mostRecentEvent;
applySuperUserOverride(result);
_mostRecentEvent = null;
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== HbaseAuditHandlerImpl.getAndDiscardMostRecentEvent(): " + result);
+ }
return result;
}
@Override
public void setMostRecentEvent(AuthzAuditEvent event) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> HbaseAuditHandlerImpl.setMostRecentEvent(" + event + ")");
+ }
_mostRecentEvent = event;
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== HbaseAuditHandlerImpl.setMostRecentEvent(...)");
+ }
}
@Override
public void setSuperUserOverride(boolean override) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> HbaseAuditHandlerImpl.setSuperUserOverride(" + override + ")");
+ }
+
_superUserOverride = override;
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== HbaseAuditHandlerImpl.setSuperUserOverride(...)");
+ }
}
void applySuperUserOverride(List<AuthzAuditEvent> events) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> HbaseAuditHandlerImpl.applySuperUserOverride(" + events + ")");
+ }
+
for (AuthzAuditEvent event : events) {
applySuperUserOverride(event);
}
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== HbaseAuditHandlerImpl.applySuperUserOverride(...)");
+ }
}
void applySuperUserOverride(AuthzAuditEvent event) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== HbaseAuditHandlerImpl.applySuperUserOverride(" + event + ")");
+ }
if (event != null && _superUserOverride) {
event.setAccessResult((short)1);
}
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> HbaseAuditHandlerImpl.applySuperUserOverride(...)");
+ }
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/0d38f0f2/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
index abf8a33..e64c5af 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
@@ -98,14 +98,13 @@ import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
import org.apache.ranger.authorization.utils.StringUtil;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
import org.apache.ranger.plugin.policyengine.RangerAccessResultProcessor;
+import org.apache.ranger.plugin.policyengine.RangerPolicyEngine;
import org.apache.ranger.plugin.service.RangerBasePlugin;
import org.apache.ranger.plugin.util.GrantRevokeRequest;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.RpcController;
import com.google.protobuf.Service;
@@ -256,21 +255,23 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
final boolean _everythingIsAccessible;
final boolean _somethingIsAccessible;
final List<AuthzAuditEvent> _accessAllowedEvents;
+ final List<AuthzAuditEvent> _familyLevelAccessEvents;
final AuthzAuditEvent _accessDeniedEvent;
- final Map<String, Set<String>> _allowedColumns;
final String _denialReason;
-
- ColumnFamilyAccessResult(
- boolean everythingIsAccessible, boolean somethingIsAccessible,
- List<AuthzAuditEvent> accessAllowedEvents, AuthzAuditEvent accessDeniedEvent,
- Map<String, Set<String>> allowedColumns, String denialReason) {
+ final RangerAuthorizationFilter _filter;
+
+ ColumnFamilyAccessResult(boolean everythingIsAccessible, boolean somethingIsAccessible,
+ List<AuthzAuditEvent> accessAllowedEvents, List<AuthzAuditEvent> familyLevelAccessEvents, AuthzAuditEvent accessDeniedEvent, String denialReason,
+ RangerAuthorizationFilter filter) {
_everythingIsAccessible = everythingIsAccessible;
_somethingIsAccessible = somethingIsAccessible;
// WARNING: we are just holding on to reference of the collection. Potentially risky optimization
_accessAllowedEvents = accessAllowedEvents;
+ _familyLevelAccessEvents = familyLevelAccessEvents;
_accessDeniedEvent = accessDeniedEvent;
- _allowedColumns = allowedColumns;
_denialReason = denialReason;
+ // cached values of access results
+ _filter = filter;
}
@Override
@@ -279,9 +280,10 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
.add("everythingIsAccessible", _everythingIsAccessible)
.add("somethingIsAccessible", _somethingIsAccessible)
.add("accessAllowedEvents", _accessAllowedEvents)
+ .add("familyLevelAccessEvents", _familyLevelAccessEvents)
.add("accessDeniedEvent", _accessDeniedEvent)
- .add("allowedColumns", _allowedColumns)
.add("denialReason", _denialReason)
+ .add("filter", _filter)
.toString();
}
@@ -291,12 +293,12 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
final Map<byte[], ? extends Collection<?>> familyMap) throws AccessDeniedException {
String access = _authUtils.getAccess(action);
-
+ User user = getActiveUser();
+ String userName = _userUtils.getUserAsString(user);
+
if (LOG.isDebugEnabled()) {
- final String format = "evaluateAccess: entered: Operation[%s], access[%s], families[%s]";
- Map<String, Set<String>> families = getColumnFamilies(familyMap);
- String message = String.format(format, operation, access, families.toString());
- LOG.debug(message);
+ LOG.debug(String.format("evaluateAccess: entered: user[%s], Operation[%s], access[%s], families[%s]",
+ userName, operation, access, getColumnFamilies(familyMap).toString()));
}
byte[] tableBytes = getTableName(env);
@@ -307,20 +309,19 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
}
String table = Bytes.toString(tableBytes);
- final String messageTemplate = "evaluateAccess: exiting: Operation[%s], access[%s], families[%s], verdict[%s]";
+ final String messageTemplate = "evaluateAccess: exiting: user[%s], Operation[%s], access[%s], families[%s], verdict[%s]";
ColumnFamilyAccessResult result;
if (canSkipAccessCheck(operation, access, table) || canSkipAccessCheck(operation, access, env)) {
LOG.debug("evaluateAccess: exiting: isKnownAccessPattern returned true: access allowed, not audited");
- result = new ColumnFamilyAccessResult(true, true, null, null, null, null);
+ result = new ColumnFamilyAccessResult(true, true, null, null, null, null, null);
if (LOG.isDebugEnabled()) {
Map<String, Set<String>> families = getColumnFamilies(familyMap);
- String message = String.format(messageTemplate, operation, access, families.toString(), result.toString());
+ String message = String.format(messageTemplate, userName, operation, access, families.toString(), result.toString());
LOG.debug(message);
}
return result;
}
- User user = getActiveUser();
// let's create a session that would be reused. Set things on it that won't change.
HbaseAuditHandler auditHandler = _factory.getAuditHandler();
AuthorizationSession session = new AuthorizationSession(hbasePlugin)
@@ -340,17 +341,21 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
.authorize();
boolean authorized = session.isAuthorized();
String reason = "";
- if (!authorized) {
+ if (authorized) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("evaluateAccess: table level access granted [" + table + "]");
+ }
+ } else {
reason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, no column families found.", user.getName(), operation, table);
}
- AuthzAuditEvent event = auditHandler.discardMostRecentEvent(); // this could be null, of course, depending on audit settings of table.
+ AuthzAuditEvent event = auditHandler.getAndDiscardMostRecentEvent(); // this could be null, of course, depending on audit settings of table.
// if authorized then pass captured events as access allowed set else as access denied set.
result = new ColumnFamilyAccessResult(authorized, authorized,
authorized ? Collections.singletonList(event) : null,
- authorized ? null : event, null, reason);
+ null, authorized ? null : event, reason, null);
if (LOG.isDebugEnabled()) {
- String message = String.format(messageTemplate, operation, access, families.toString(), result.toString());
+ String message = String.format(messageTemplate, userName, operation, access, families.toString(), result.toString());
LOG.debug(message);
}
return result;
@@ -360,13 +365,20 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
boolean everythingIsAccessible = true;
boolean somethingIsAccessible = false;
- // we would have to accumulate audits of all successful accesses and any one denial (which in our case ends up being the last denial)
- List<AuthzAuditEvent> authorizedEvents = new ArrayList<AuthzAuditEvent>();
+ /*
+ * we would have to accumulate audits of all successful accesses and any one denial (which in our case ends up being the last denial)
+ * We need to keep audit events for family level access check seperate because we don't want them logged in some cases.
+ */
+ List<AuthzAuditEvent> authorizedEvents = new ArrayList<AuthzAuditEvent>();
+ List<AuthzAuditEvent> familyLevelAccessEvents = new ArrayList<AuthzAuditEvent>();
AuthzAuditEvent deniedEvent = null;
String denialReason = null;
// we need to cache the auths results so that we can create a filter, if needed
- Map<String, Set<String>> accessResultsCache = new HashMap<String, Set<String>>();
-
+ Map<String, Set<String>> columnsAccessAllowed = new HashMap<String, Set<String>>();
+ Set<String> familesAccessAllowed = new HashSet<String>();
+ Set<String> familesAccessDenied = new HashSet<String>();
+ Set<String> familesAccessIndeterminate = new HashSet<String>();
+
for (Map.Entry<String, Set<String>> anEntry : families.entrySet()) {
String family = anEntry.getKey();
session.columnFamily(family);
@@ -379,19 +391,47 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
session.column(null) // zap stale column from prior iteration of this loop, if any
.buildRequest()
.authorize();
+ AuthzAuditEvent auditEvent = auditHandler.getAndDiscardMostRecentEvent(); // capture it only for success
if (session.isAuthorized()) {
- // we need to do 3 things: housekeeping, capturing audit events, building the results cache for filter
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("evaluateAccess: has family level access [" + family + "]");
+ }
+ // we need to do 3 things: housekeeping, decide about audit events, building the results cache for filter
somethingIsAccessible = true;
- AuthzAuditEvent event = auditHandler.discardMostRecentEvent();
- if (event != null) {
- authorizedEvents.add(event);
+ familesAccessAllowed.add(family);
+ if (auditEvent != null) {
+ LOG.debug("evaluateAccess: adding to family-level-access-granted-event-set");
+ familyLevelAccessEvents.add(auditEvent);
}
- // presence of key with null value would imply access to all columns in a family.
- accessResultsCache.put(family, null);
} else {
everythingIsAccessible = false;
- deniedEvent = auditHandler.discardMostRecentEvent();
- denialReason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, family:%s, no columns found.", user.getName(), operation, table, family);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("evaluateAccess: no family level access [" + family + "]. Checking if has partial access (of any type)...");
+ }
+ session.access(RangerPolicyEngine.ANY_ACCESS)
+ .buildRequest()
+ .authorize();
+ auditEvent = auditHandler.getAndDiscardMostRecentEvent(); // capture it only for failure
+ if (session.isAuthorized()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("evaluateAccess: has partial access (of some type) in family [" + family + "]");
+ }
+ // we need to do 3 things: housekeeping, decide about audit events, building the results cache for filter
+ somethingIsAccessible = true;
+ familesAccessIndeterminate.add(family);
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("evaluateAccess: has no access of any (of any type) in family [" + family + "]");
+ }
+ familesAccessDenied.add(family);
+ denialReason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, family:%s, no columns found.", user.getName(), operation, table, family);
+ if (auditEvent != null && deniedEvent == null) { // we need to capture just one denial event
+ LOG.debug("evaluateAccess: Setting denied access audit event with last auth failure audit event.");
+ deniedEvent = auditEvent;
+ }
+ }
+ // Restore the access back
+ session.access(access);
}
} else {
LOG.debug("evaluateAccess: columns collection not empty. Skipping Family level check, will do finer level access check.");
@@ -403,51 +443,73 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
session.column(column)
.buildRequest()
.authorize();
+ AuthzAuditEvent auditEvent = auditHandler.getAndDiscardMostRecentEvent();
if (session.isAuthorized()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("evaluateAccess: has column level access [" + family + ", " + column + "]");
+ }
// we need to do 3 things: housekeeping, capturing audit events, building the results cache for filter
somethingIsAccessible = true;
- AuthzAuditEvent event = auditHandler.discardMostRecentEvent();
- if (event != null) {
- authorizedEvents.add(event);
- }
accessibleColumns.add(column);
+ if (auditEvent != null) {
+ LOG.debug("evaluateAccess: adding to access-granted-audit-event-set");
+ authorizedEvents.add(auditEvent);
+ }
} else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("evaluateAccess: no column level access [" + family + ", " + column + "]");
+ }
everythingIsAccessible = false;
- deniedEvent = auditHandler.discardMostRecentEvent();
- denialReason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, family:%s, column: %s", user.getName(), operation, table, family, column);
+ denialReason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, family:%s, column: %s", user.getName(), operation, table, family, column);
+ if (auditEvent != null && deniedEvent == null) { // we need to capture just one denial event
+ LOG.debug("evaluateAccess: Setting denied access audit event with last auth failure audit event.");
+ deniedEvent = auditEvent;
+ }
}
+ if (!accessibleColumns.isEmpty()) {
+ columnsAccessAllowed.put(family, accessibleColumns);
+ }
}
- if (!accessibleColumns.isEmpty()) {
- accessResultsCache.put(family, accessibleColumns);
- }
}
}
-
- result = new ColumnFamilyAccessResult(everythingIsAccessible, somethingIsAccessible, authorizedEvents, deniedEvent, accessResultsCache, denialReason);
+ // Cache of auth results are encapsulated the in the filter. Not every caller of the function uses it - only preGet and preOpt will.
+ RangerAuthorizationFilter filter = new RangerAuthorizationFilter(session, familesAccessAllowed, familesAccessDenied, familesAccessIndeterminate, columnsAccessAllowed);
+ result = new ColumnFamilyAccessResult(everythingIsAccessible, somethingIsAccessible, authorizedEvents, familyLevelAccessEvents, deniedEvent, denialReason, filter);
if (LOG.isDebugEnabled()) {
- String message = String.format(messageTemplate, operation, access, families.toString(), result.toString());
+ String message = String.format(messageTemplate, userName, operation, access, families.toString(), result.toString());
LOG.debug(message);
}
return result;
}
-
+
Filter authorizeAccess(String operation, Action action, final RegionCoprocessorEnvironment env, final Map<byte[], NavigableSet<byte[]>> familyMap) throws AccessDeniedException {
- ColumnFamilyAccessResult accessResult = evaluateAccess(operation, action, env, familyMap);
- RangerDefaultAuditHandler auditHandler = new RangerDefaultAuditHandler();
- if (accessResult._everythingIsAccessible) {
- auditHandler.logAuthzAudits(accessResult._accessAllowedEvents);
- LOG.debug("authorizeAccess: exiting: No filter returned since all access was allowed");
- return null; // no filter needed since we are good to go.
- } else if (accessResult._somethingIsAccessible) {
- auditHandler.logAuthzAudits(accessResult._accessAllowedEvents); // we still need to log those to which we got access.
- LOG.debug("authorizeAccess: exiting: Filter returned since some access was allowed");
- return new RangerAuthorizationFilter(accessResult._allowedColumns);
- } else {
- // If we are here then it means nothing was accessible! So let's log one denial (in our case, the last denial) and throw an exception
- auditHandler.logAuthzAudit(accessResult._accessDeniedEvent);
- LOG.debug("authorizeAccess: exiting: Throwing exception since nothing was accessible");
- throw new AccessDeniedException(accessResult._denialReason);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("==> authorizeAccess");
+ }
+ try {
+ ColumnFamilyAccessResult accessResult = evaluateAccess(operation, action, env, familyMap);
+ RangerDefaultAuditHandler auditHandler = new RangerDefaultAuditHandler();
+ if (accessResult._everythingIsAccessible) {
+ auditHandler.logAuthzAudits(accessResult._accessAllowedEvents);
+ auditHandler.logAuthzAudits(accessResult._familyLevelAccessEvents);
+ LOG.debug("authorizeAccess: exiting: No filter returned since all access was allowed");
+ return null; // no filter needed since we are good to go.
+ } else if (accessResult._somethingIsAccessible) {
+ // NOTE: audit logging is split beween logging here (in scope of preOp/preGet) and logging in the filter component for those that couldn't be determined
+ auditHandler.logAuthzAudits(accessResult._accessAllowedEvents);
+ LOG.debug("authorizeAccess: exiting: Filter returned since some access was allowed");
+ return accessResult._filter;
+ } else {
+ // If we are here then it means nothing was accessible! So let's log one denial (in our case, the last denial) and throw an exception
+ auditHandler.logAuthzAudit(accessResult._accessDeniedEvent);
+ LOG.debug("authorizeAccess: exiting: Throwing exception since nothing was accessible");
+ throw new AccessDeniedException(accessResult._denialReason);
+ }
+ } finally {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("<== authorizeAccess");
+ }
}
}
@@ -466,6 +528,7 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
RangerDefaultAuditHandler auditHandler = new RangerDefaultAuditHandler();
if (accessResult._everythingIsAccessible) {
auditHandler.logAuthzAudits(accessResult._accessAllowedEvents);
+ auditHandler.logAuthzAudits(accessResult._familyLevelAccessEvents);
LOG.debug("requirePermission: exiting: all access was allowed");
return;
} else {
@@ -479,7 +542,6 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
* This could run s
* @param operation
* @param otherInformation
- * @param access
* @param table
* @param columnFamily
* @param column
@@ -614,35 +676,6 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
requirePermission(request, perm, env, familyMap);
}
- public void checkPermissions(Permission[] permissions) throws IOException {
- String tableName = regionEnv.getRegion().getTableDesc().getTableName().getNameAsString() ;
- for (Permission permission : permissions) {
- if (permission instanceof TablePermission) {
- TablePermission tperm = (TablePermission) permission;
- for (Permission.Action action : permission.getActions()) {
- if (! tperm.getTableName().getNameAsString().equals(tableName)) {
- throw new AccessDeniedException(String.format("This method can only execute at the table specified in TablePermission. " + "Table of the region:%s , requested table:%s", tableName,
- tperm.getTableName().getNameAsString()));
- }
- HashMap<byte[], Set<byte[]>> familyMap = Maps.newHashMapWithExpectedSize(1);
- if (tperm.getFamily() != null) {
- if (tperm.getQualifier() != null) {
- familyMap.put(tperm.getFamily(), Sets.newHashSet(tperm.getQualifier()));
- } else {
- familyMap.put(tperm.getFamily(), null);
- }
- }
- requirePermission("checkPermissions", action, regionEnv, familyMap);
- }
- } else {
- for (Permission.Action action : permission.getActions()) {
- byte[] tname = regionEnv.getRegion().getTableDesc().getTableName().getName() ;
- requirePermission("checkPermissions", tname, action);
- }
- }
- }
- }
-
@Override
public void postScannerClose(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s) throws IOException {
scannerOwners.remove(s);
@@ -794,7 +827,6 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
final Region region = env.getRegion();
if (region == null) {
LOG.error("NULL region from RegionCoprocessorEnvironment in preOpen()");
- return;
} else {
HRegionInfo regionInfo = region.getRegionInfo();
if (isSpecialTable(regionInfo)) {
@@ -820,24 +852,34 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
}
@Override
public RegionScanner preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s) throws IOException {
- RegionCoprocessorEnvironment e = c.getEnvironment();
-
- Map<byte[], NavigableSet<byte[]>> familyMap = scan.getFamilyMap();
- String operation = "scannerOpen";
- Filter filter = authorizeAccess(operation, Action.READ, e, familyMap);
- if (filter == null) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("preGetOp: Access allowed for all families/column.");
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("==> preScannerOpen");
+ }
+
+ try {
+ RegionCoprocessorEnvironment e = c.getEnvironment();
+
+ Map<byte[], NavigableSet<byte[]>> familyMap = scan.getFamilyMap();
+ String operation = "scannerOpen";
+ Filter filter = authorizeAccess(operation, Action.READ, e, familyMap);
+ if (filter == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("preScannerOpen: Access allowed for all families/column. No filter added");
+ }
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("preScannerOpen: Access allowed for some of the families/column. New filter added.");
+ }
+ Filter existingFilter = scan.getFilter();
+ Filter combinedFilter = combineFilters(filter, existingFilter);
+ scan.setFilter(combinedFilter);
}
- } else {
+ return s;
+ } finally {
if (LOG.isDebugEnabled()) {
- LOG.debug("preGetOp: Access allowed for some of the families/column.");
+ LOG.debug("<== preScannerOpen");
}
- Filter existingFilter = scan.getFilter();
- Filter combinedFilter = combineFilters(filter, existingFilter);
- scan.setFilter(combinedFilter);
}
- return s;
}
@Override
public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
@@ -948,21 +990,32 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
@Override
public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> rEnv, final Get get, final List<Cell> result) throws IOException {
- RegionCoprocessorEnvironment e = rEnv.getEnvironment();
- Map<byte[], NavigableSet<byte[]>> familyMap = get.getFamilyMap() ;
-
- String operation = "get";
- Filter filter = authorizeAccess(operation, Action.READ, e, familyMap);
- if (filter == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("==> preGetOp");
+ }
+ try {
+ RegionCoprocessorEnvironment e = rEnv.getEnvironment();
+ Map<byte[], NavigableSet<byte[]>> familyMap = get.getFamilyMap();
+
+ String operation = "get";
+ Filter filter = authorizeAccess(operation, Action.READ, e, familyMap);
+ if (filter == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("preGetOp: all access allowed, no filter returned");
+ }
+ } else {
+ Filter existingFilter = get.getFilter();
+ Filter combinedFilter = combineFilters(filter, existingFilter);
+ get.setFilter(combinedFilter);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("preGetOp: partial access, new filter added");
+ }
+ }
+ } finally {
if (LOG.isDebugEnabled()) {
- LOG.debug("preGetOp: Access allowed.");
+ LOG.debug("<== preGetOp");
}
- } else {
- Filter existingFilter = get.getFilter();
- Filter combinedFilter = combineFilters(filter, existingFilter);
- get.setFilter(combinedFilter);
}
- return;
}
@Override
public void preRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
@@ -1008,7 +1061,7 @@ public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocess
session.table(tableName).buildRequest().authorize();
if (!session.isAuthorized()) {
itr.remove();
- auditHandler.discardMostRecentEvent();
+ auditHandler.getAndDiscardMostRecentEvent();
}
}
if (descriptors.size() > 0) {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/0d38f0f2/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilter.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilter.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilter.java
index ae61a1e..e281099 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilter.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilter.java
@@ -20,69 +20,127 @@
package org.apache.ranger.authorization.hbase;
import java.io.IOException;
+import java.util.Collections;
import java.util.Map;
import java.util.Set;
-import org.apache.commons.collections.CollectionUtils;
+import com.google.common.base.Objects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.filter.FilterBase;
import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.ranger.audit.model.AuthzAuditEvent;
public class RangerAuthorizationFilter extends FilterBase {
private static final Log LOG = LogFactory.getLog(RangerAuthorizationFilter.class.getName());
- final Map<String, Set<String>> _cache;
+ final Set<String> _familiesAccessAllowed;
+ final Set<String> _familiesAccessDenied;
+ final Set<String> _familiesAccessIndeterminate;
+ final Map<String, Set<String>> _columnsAccessAllowed;
+ final AuthorizationSession _session;
+ final HbaseAuditHandler _auditHandler = HbaseFactory.getInstance().getAuditHandler();
- public RangerAuthorizationFilter(Map<String, Set<String>> cache) {
- _cache = cache;
+ public RangerAuthorizationFilter(AuthorizationSession session, Set<String> familiesAccessAllowed, Set<String> familiesAccessDenied, Set<String> familiesAccessIndeterminate,
+ Map<String, Set<String>> columnsAccessAllowed) {
+ // the class assumes that all of these can be empty but none of these can be null
+ _familiesAccessAllowed = familiesAccessAllowed;
+ _familiesAccessDenied = familiesAccessDenied;
+ _familiesAccessIndeterminate = familiesAccessIndeterminate;
+ _columnsAccessAllowed = columnsAccessAllowed;
+ // this session should have everything set on it except family and column which would be altered based on need
+ _session = session;
+ // we don't want to audit denial, so we need to make sure the hander is what we need it to be.
+ _session.auditHandler(_auditHandler);
}
@SuppressWarnings("deprecation")
@Override
public ReturnCode filterKeyValue(Cell kv) throws IOException {
-
- if (_cache == null || _cache.isEmpty()) {
- LOG.debug("filterKeyValue: if cache is null or empty then there is no hope for any access. Denied!");
- return ReturnCode.NEXT_COL;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("==> filterKeyValue");
}
-
+
+ String family = null;
byte[] familyBytes = kv.getFamily();
- if (familyBytes == null || familyBytes.length == 0) {
- LOG.debug("filterKeyValue: null/empty families in request! Denied!");
- return ReturnCode.NEXT_COL;
+ if (familyBytes != null && familyBytes.length > 0) {
+ family = Bytes.toString(familyBytes);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("filterKeyValue: evaluating family[" + family + "].");
+ }
}
- String family = Bytes.toString(familyBytes);
- if (LOG.isDebugEnabled()) {
- LOG.debug("filterKeyValue: Evaluating family[" + family + "]");
+ String column = null;
+ if (kv.getQualifier() != null && kv.getQualifier().length > 0) {
+ column = Bytes.toString(kv.getQualifier());
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("filterKeyValue: evaluating column[" + column + "].");
+ }
+ } else {
+ LOG.warn("filterKeyValue: empty/null column set! Unexpected!");
}
-
- if (!_cache.containsKey(family)) {
- LOG.debug("filterKeyValue: Cache map did not contain the family, i.e. nothing in family has access! Denied!");
- return ReturnCode.NEXT_COL;
+
+ ReturnCode result = ReturnCode.NEXT_COL;
+ boolean authCheckNeeded = false;
+ if (family == null) {
+ LOG.warn("filterKeyValue: Unexpected - null/empty family! Access denied!");
+ } else if (_familiesAccessDenied.contains(family)) {
+ LOG.debug("filterKeyValue: family found in access denied families cache. Access denied.");
+ } else if (_columnsAccessAllowed.containsKey(family)) {
+ LOG.debug("filterKeyValue: family found in column level access results cache.");
+ if (_columnsAccessAllowed.get(family).contains(column)) {
+ LOG.debug("filterKeyValue: family/column found in column level access results cache. Access allowed.");
+ result = ReturnCode.INCLUDE;
+ } else {
+ LOG.debug("filterKeyValue: family/column not in column level access results cache. Access denied.");
+ }
+ } else if (_familiesAccessAllowed.contains(family)) {
+ LOG.debug("filterKeyValue: family found in access allowed families cache. Must re-authorize for correct audit generation.");
+ authCheckNeeded = true;
+ } else if (_familiesAccessIndeterminate.contains(family)) {
+ LOG.debug("filterKeyValue: family found in indeterminate families cache. Evaluating access...");
+ authCheckNeeded = true;
+ } else {
+ LOG.warn("filterKeyValue: Unexpected - alien family encountered that wasn't seen by pre-hook! Access Denied.!");
}
- Set<String> columns = _cache.get(family);
-
- if (CollectionUtils.isEmpty(columns)) {
- LOG.debug("filterKeyValue: empty/null column set in cache for family implies family level access. No need to bother with column level. Allowed!");
- return ReturnCode.INCLUDE;
- }
- byte[] columnBytes = kv.getQualifier();
- if (columnBytes == null || columnBytes.length == 0) {
- LOG.debug("filterKeyValue: empty/null column set in request implies family level access, which isn't available. Denied!");
- return ReturnCode.NEXT_COL;
+
+ if (authCheckNeeded) {
+ LOG.debug("filterKeyValue: Checking authorization...");
+ _session.columnFamily(family)
+ .column(column)
+ .buildRequest()
+ .authorize();
+ // must always purge the captured audit event out of the audit handler to avoid messing up the next check
+ AuthzAuditEvent auditEvent = _auditHandler.getAndDiscardMostRecentEvent();
+ if (_session.isAuthorized()) {
+ LOG.debug("filterKeyValue: Access granted.");
+ result = ReturnCode.INCLUDE;
+ if (auditEvent != null) {
+ LOG.debug("filterKeyValue: access is audited.");
+ _auditHandler.logAuthzAudits(Collections.singletonList(auditEvent));
+ } else {
+ LOG.debug("filterKeyValue: no audit event returned. Access not audited.");
+ }
+ } else {
+ LOG.debug("filterKeyValue: Access denied. Denial not audited.");
+ }
}
- String column = Bytes.toString(columnBytes);
if (LOG.isDebugEnabled()) {
- LOG.debug("filterKeyValue: Evaluating column[" + column + "]");
- }
- if (columns.contains(column)) {
- LOG.debug("filterKeyValue: cache contains Column in column-family's collection. Access allowed!");
- return ReturnCode.INCLUDE;
- } else {
- LOG.debug("filterKeyValue: cache missing Column in column-family's collection. Access denied!");
- return ReturnCode.NEXT_COL;
+ LOG.debug("filterKeyValue: " + result);
}
+ return result;
}
+
+ @Override
+ public String toString() {
+ return Objects.toStringHelper(getClass())
+ .add("familiesAccessAllowed", _familiesAccessAllowed)
+ .add("familiesAccessDenied", _familiesAccessDenied)
+ .add("familiesAccessUnknown", _familiesAccessIndeterminate)
+ .add("columnsAccessAllowed", _columnsAccessAllowed)
+ .toString();
+
+ }
+
}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/0d38f0f2/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilterTest.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilterTest.java b/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilterTest.java
index 4b49721..2c460d1 100644
--- a/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilterTest.java
+++ b/hbase-agent/src/test/java/org/apache/ranger/authorization/hbase/RangerAuthorizationFilterTest.java
@@ -19,6 +19,7 @@
package org.apache.ranger.authorization.hbase;
import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -28,6 +29,8 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.filter.Filter.ReturnCode;
import org.junit.Test;
@@ -40,68 +43,77 @@ public class RangerAuthorizationFilterTest {
@Test
public void testFilterKeyValueCell_happyPath() throws IOException {
- // null/empty column collection in cache for a family implies family level access
- Map<String, Set<String>> cache = new HashMap<String, Set<String>>();
- cache.put("family1", Collections.<String> emptySet());
- RangerAuthorizationFilter filter = new RangerAuthorizationFilter(cache);
+ // null/empty column collection in cache for a family implies family level access
+ String[] allowedFamilies = new String[] { "family1", "family2" };
+ String[] deniedFamilies = new String[] { "family3", "family4" };
+ String[] indeterminateFamilies = new String[] { "family5", "family6" };
+ Set<String> familiesAccessAllowed = ImmutableSet.copyOf(allowedFamilies);
+ Set<String> familiesAccessDenied = ImmutableSet.copyOf(deniedFamilies);
+ Set<String> familiesAccessIndeterminate = ImmutableSet.copyOf(indeterminateFamilies);
- Cell aCell = mock(Cell.class);
- when(aCell.getFamily()).thenReturn("family1".getBytes());
- when(aCell.getQualifier()).thenReturn("column1".getBytes());
- assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
-
- when(aCell.getQualifier()).thenReturn("column2".getBytes());
- assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
-
- // null empty column collection in REQUEST implies family level access
- when(aCell.getQualifier()).thenReturn(null);
- assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
-
- // specific columns in cache should be allowed only if there is a match of family and column
- cache.clear();
- cache.put("family1", Sets.newHashSet("column11", "column12"));
- cache.put("family2", Sets.newHashSet("column21", "column22"));
- filter = new RangerAuthorizationFilter(cache);
+ Map<String, Set<String>> columnsAccessAllowed = new HashMap<String, Set<String>>();
+ String[] family7KnowGoodColumns = new String[] {"family7-column1", "family7-column2"};
+ columnsAccessAllowed.put("family7", ImmutableSet.copyOf(family7KnowGoodColumns));
+ String[] family8KnowGoodColumns = new String[] {"family8-column1", "family8-column2"};
+ columnsAccessAllowed.put("family8", ImmutableSet.copyOf(family8KnowGoodColumns));
- when(aCell.getFamily()).thenReturn("family1".getBytes());
- when(aCell.getQualifier()).thenReturn("column11".getBytes());
- assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
- when(aCell.getQualifier()).thenReturn("column12".getBytes());
- assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
- when(aCell.getQualifier()).thenReturn("column13".getBytes());
- assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
-
- when(aCell.getFamily()).thenReturn("family2".getBytes());
- when(aCell.getQualifier()).thenReturn("column22".getBytes());
- assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
+ // auth session
+ AuthorizationSession session = createSessionMock();
+ RangerAuthorizationFilter filter = new RangerAuthorizationFilter(session, familiesAccessAllowed, familiesAccessDenied, familiesAccessIndeterminate, columnsAccessAllowed);
- when(aCell.getFamily()).thenReturn("family3".getBytes());
- when(aCell.getQualifier()).thenReturn("column11".getBytes());
- assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
-
- // asking for family level access when one doesn't exist (colum collection for a family is not null/empty then it should get denied
- when(aCell.getFamily()).thenReturn("family1".getBytes());
+ // evaluate access for various types of cases
+ Cell aCell = mock(Cell.class);
+ // families with know denied acess
+ for (String family : deniedFamilies) {
+ when(aCell.getFamily()).thenReturn(family.getBytes());
+ assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
+ }
+ // family that isn't in allowed and if cell does not have column then it should be denied
+ when(aCell.getFamily()).thenReturn("family7".getBytes());
when(aCell.getQualifier()).thenReturn(null);
assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
+ // families with known partial access
+ for (String column : family7KnowGoodColumns ) {
+ when(aCell.getQualifier()).thenReturn(column.getBytes());
+ assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
+ }
+ when(aCell.getFamily()).thenReturn("family8".getBytes());
+ for (String column : family8KnowGoodColumns ) {
+ when(aCell.getQualifier()).thenReturn(column.getBytes());
+ assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
+ }
+ // try some columns that are not in the cache
+ for (String column : new String[] { "family8-column3", "family8-column4"}) {
+ when(aCell.getQualifier()).thenReturn(column.getBytes());
+ assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
+ }
+ // families with known allowed access - for these we need to doctor up the session
+ when(session.isAuthorized()).thenReturn(true);
+ for (String family : allowedFamilies) {
+ when(aCell.getFamily()).thenReturn(family.getBytes());
+ when(aCell.getQualifier()).thenReturn("some-column".getBytes());
+ assertEquals(ReturnCode.INCLUDE, filter.filterKeyValue(aCell));
+ }
+ when(session.isAuthorized()).thenReturn(false);
+ for (String family : indeterminateFamilies) {
+ when(aCell.getFamily()).thenReturn(family.getBytes());
+ when(aCell.getQualifier()).thenReturn("some-column".getBytes());
+ assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
+ }
}
- @Test
- public void testFilterKeyValueCell_firewalling() throws IOException {
- // null cache will deny everything.
- RangerAuthorizationFilter filter = new RangerAuthorizationFilter(null);
- Cell aCell = mock(Cell.class);
- when(aCell.getFamily()).thenReturn("family1".getBytes());
- when(aCell.getQualifier()).thenReturn("column1".getBytes());
- assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
+ AuthorizationSession createSessionMock() {
+ AuthorizationSession session = mock(AuthorizationSession.class);
+ when(session.column(anyString())).thenReturn(session);
+ when(session.columnFamily(anyString())).thenReturn(session);
+ when(session.table(anyString())).thenReturn(session);
+ when(session.buildRequest()).thenReturn(session);
+ when(session.authorize()).thenReturn(session);
+ when(session.isAuthorized()).thenReturn(false); // by default the mock fails all auth requests
- // non-null but empty cache should do the same
- Map<String, Set<String>> cache = new HashMap<String, Set<String>>();
- filter = new RangerAuthorizationFilter(cache);
- assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
+ HbaseAuditHandler auditHandler = mock(HbaseAuditHandler.class);
+ session._auditHandler = auditHandler;
- // Null family in request would get denied, too
- when(aCell.getFamily()).thenReturn(null);
- when(aCell.getQualifier()).thenReturn("column1".getBytes());
- assertEquals(ReturnCode.NEXT_COL, filter.filterKeyValue(aCell));
+ return session;
}
}
[4/9] incubator-ranger git commit: RANGER-543:
RangerTimeOfDataMatcher updated to support time ranges that span across
midnight
Posted by ma...@apache.org.
RANGER-543: RangerTimeOfDataMatcher updated to support time ranges that span across midnight
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/08990c5b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/08990c5b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/08990c5b
Branch: refs/heads/tag-policy
Commit: 08990c5bdee9aacc4f69eaf777202904fcc92ef6
Parents: 4c75d28
Author: Madhan Neethiraj <ma...@apache.org>
Authored: Tue Jun 9 17:55:13 2015 -0700
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Tue Jun 9 17:55:13 2015 -0700
----------------------------------------------------------------------
.../RangerTimeOfDayMatcher.java | 70 +++++++++-----------
.../RangerTimeOfDayMatcherTest.java | 15 +++--
2 files changed, 40 insertions(+), 45 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/08990c5b/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java b/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java
index 40d86a5..3ddb250 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java
@@ -72,7 +72,7 @@ public class RangerTimeOfDayMatcher extends RangerAbstractConditionEvaluator {
}
if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerTimeOfDayMatcher.init(" + condition + "): countries[" + _durations + "]");
+ LOG.debug("<== RangerTimeOfDayMatcher.init(" + condition + "): durations[" + toString() + "]");
}
}
@@ -105,17 +105,13 @@ public class RangerTimeOfDayMatcher extends RangerAbstractConditionEvaluator {
endMinute = Integer.parseInt(m.group(7));
}
String endType = m.group(8).toUpperCase();
- if (startType.equals("P") && endType.equals("A")) {
- LOG.warn("extractDuration: Invalid duration:" + value);
- } else {
- if (startType.equals("P")) {
- startHour += 12;
- }
- if (endType.equals("P")) {
- endHour += 12;
- }
- result = new int[] { (startHour*60)+startMin, (endHour*60)+endMinute };
+ if (startType.equals("P")) {
+ startHour += 12;
}
+ if (endType.equals("P")) {
+ endHour += 12;
+ }
+ result = new int[] { (startHour*60)+startMin, (endHour*60)+endMinute };
}
}
@@ -145,12 +141,12 @@ public class RangerTimeOfDayMatcher extends RangerAbstractConditionEvaluator {
calendar.setTime(date);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
- if (durationMatched(_durations, hourOfDay, minutes)) {
+ if (! durationMatched(_durations, hourOfDay, minutes)) {
+ matched = false;
+
if (LOG.isDebugEnabled()) {
- LOG.debug("isMatched: None of the durations contains this hour of day[" + hourOfDay + "]");
+ LOG.debug("isMatched: None of the durations contains this hour of day[" + hourOfDay + "] and minutes[" + minutes + "]");
}
- } else {
- matched = false;
}
}
@@ -166,36 +162,32 @@ public class RangerTimeOfDayMatcher extends RangerAbstractConditionEvaluator {
int start = aDuration[0];
int end = aDuration[1];
int minutesOfDay = hourOfDay*60 + minutes;
- if (start <= minutesOfDay && minutesOfDay <= end) {
- return true;
+ if(start < end) {
+ if (start <= minutesOfDay && minutesOfDay <= end) {
+ return true;
+ }
+ } else {
+ if(start <= minutesOfDay || minutesOfDay <= end) {
+ return true;
+ }
}
}
return false;
}
- String extractValue(final RangerAccessRequest request, String key) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("==> RangerSimpleMatcher.extractValue(" + request+ ")");
- }
-
- String value = null;
- if (request == null) {
- LOG.debug("isMatched: Unexpected: null request. Returning null!");
- } else if (request.getContext() == null) {
- LOG.debug("isMatched: Context map of request is null. Ok. Returning null!");
- } else if (CollectionUtils.isEmpty(request.getContext().entrySet())) {
- LOG.debug("isMatched: Missing context on request. Ok. Condition isn't applicable. Returning null!");
- } else if (!request.getContext().containsKey(key)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isMatched: Unexpected: Context did not have data for condition[" + key + "]. Returning null!");
- }
- } else {
- value = (String)request.getContext().get(key);
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("RangerTimeOfDayMatcher {");
+ sb.append("_allowAny=" + _allowAny).append(" ");
+ sb.append("_durations=[");
+ for(int[] duration : _durations) {
+ sb.append("{start=" + duration[0] + "; end=" + duration[1] + "} ");
}
+ sb.append("]");
+ sb.append("}");
- if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerSimpleMatcher.extractValue(" + request+ "): " + value);
- }
- return value;
+ return sb.toString();
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/08990c5b/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java
----------------------------------------------------------------------
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java b/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java
index b6ca843..e894d98 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java
@@ -51,7 +51,7 @@ public class RangerTimeOfDayMatcherTest {
String[] durations = new String[] {
"9am-5pm", " 9Am -5 Pm", " 9Am -5 Pm", "9 AM -5 p.m.", "9a.M - 5Pm.",
"9:30am-5:30pm", " 9:00Am -5:59 Pm",
- " 9 am - 4 pm "
+ " 9 am - 4 pm ", "9pm-5AM"
};
check(durations, true);
}
@@ -60,7 +60,6 @@ public class RangerTimeOfDayMatcherTest {
public void test_patterMatching_unexpectedMatches() {
// even semantically illegal durations work -- parsing is just for format not for semantics!
String[] durations = new String[] {
- "9pm-5AM", // illegal duration where start > end is allows parsed as right!
"00PM-44PM", // any two digits are allowed!
"9:0am-5:7pm", // Minute part can be one digit
};
@@ -101,6 +100,7 @@ public class RangerTimeOfDayMatcherTest {
{ "9 AM -5 p.m.", "9", null, "A", "5", null, "p" },
{ "9:30AM - 5:15pm", "9", "30", "A", "5", "15", "p" },
{ "9:30 AM - 5:15 p.m.", "9", "30", "A", "5", "15", "p" },
+ { "9pm-5am", "9", null, "p", "5", null, "a"},
};
checkGroups(input);
}
@@ -125,7 +125,7 @@ public class RangerTimeOfDayMatcherTest {
Object[][] input = new Object[][] {
{ "9am-5pm", true, 9*60, (12+5)*60 },
{ "1 PM - 10P.M.", true, (12+1)*60, (12+10)*60 },
- { "1PM - 9AM", false, null, null }, // illegal duration should come back as null
+ { "1PM - 9AM", true, (12+1)*60, 9*60 },
{ "1PM", false, null, null }, // illegal patterns should come back as null, too
};
for (Object[] data: input) {
@@ -175,7 +175,7 @@ public class RangerTimeOfDayMatcherTest {
@Test
public void test_end2end_happyPath() {
RangerPolicyItemCondition itemCondition = mock(RangerPolicyItemCondition.class);
- when(itemCondition.getValues()).thenReturn(Arrays.asList("2:45a.m. -7:00 AM", " 9:15AM- 5:30P.M. "));
+ when(itemCondition.getValues()).thenReturn(Arrays.asList("2:45a.m. -7:00 AM", " 9:15AM- 5:30P.M. ", "11pm-2am"));
RangerTimeOfDayMatcher matcher = new RangerTimeOfDayMatcher();
matcher.setConditionDef(null);
@@ -183,7 +183,9 @@ public class RangerTimeOfDayMatcherTest {
matcher.init();
Object[][] input = new Object[][] {
- { 1, 0, false },
+ { 1, 0, true },
+ { 2, 0, true },
+ { 2, 1, false },
{ 2, 44, false },
{ 2, 45, true },
{ 3, 0, true },
@@ -196,7 +198,8 @@ public class RangerTimeOfDayMatcherTest {
{17, 30, true},
{17, 31, false},
{18, 0, false },
- {23, 0, false },
+ {22, 59, false },
+ {23, 0, true },
};
RangerAccessRequest request = mock(RangerAccessRequest.class);
[9/9] incubator-ranger git commit: Merge branch 'master' into
tag-policy
Posted by ma...@apache.org.
Merge branch 'master' into tag-policy
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/ea3bcb38
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/ea3bcb38
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/ea3bcb38
Branch: refs/heads/tag-policy
Commit: ea3bcb38eb28ebebed8a29d3429ce6b3ee794141
Parents: c6133b7 c5f61c8
Author: Madhan Neethiraj <ma...@apache.org>
Authored: Wed Jun 10 22:09:30 2015 -0700
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Wed Jun 10 22:09:30 2015 -0700
----------------------------------------------------------------------
.../conditionevaluator/RangerSimpleMatcher.java | 10 +-
.../RangerTimeOfDayMatcher.java | 70 ++--
.../model/validation/RangerPolicyValidator.java | 8 +
.../RangerAbstractPolicyEvaluator.java | 15 +-
.../RangerAbstractPolicyItemEvaluator.java | 61 +++
.../RangerDefaultPolicyEvaluator.java | 387 +++----------------
.../RangerDefaultPolicyItemEvaluator.java | 273 +++++++++++++
.../RangerOptimizedPolicyEvaluator.java | 4 +-
.../policyevaluator/RangerPolicyEvaluator.java | 7 +-
.../RangerPolicyItemEvaluator.java | 55 +++
.../RangerTimeOfDayMatcherTest.java | 15 +-
.../plugin/policyengine/TestPolicyEngine.java | 7 +
.../RangerDefaultPolicyEvaluatorTest.java | 256 ------------
.../test_policyengine_conditions.json | 230 +++++++++++
.../policyengine/test_policyengine_hbase.json | 2 +-
.../hbase/AuthorizationSession.java | 21 +-
.../authorization/hbase/HbaseAuditHandler.java | 4 +-
.../hbase/HbaseAuditHandlerImpl.java | 61 ++-
.../hbase/RangerAuthorizationCoprocessor.java | 295 ++++++++------
.../hbase/RangerAuthorizationFilter.java | 134 +++++--
.../hbase/RangerAuthorizationFilterTest.java | 120 +++---
pom.xml | 35 +-
.../org/apache/ranger/common/RESTErrorUtil.java | 9 +
.../org/apache/ranger/common/ServiceUtil.java | 2 +-
.../java/org/apache/ranger/rest/AssetREST.java | 25 +-
.../org/apache/ranger/rest/ServiceREST.java | 164 +++++---
.../RangerAuthenticationEntryPoint.java | 54 +--
.../src/main/resources/META-INF/persistence.xml | 4 +-
.../conf.dist/ranger-admin-default-site.xml | 2 +-
.../webapp/scripts/views/service/ServiceForm.js | 22 +-
.../org/apache/ranger/rest/TestServiceREST.java | 16 +-
.../config/UserGroupSyncConfig.java | 37 +-
.../ranger/usergroupsync/UserGroupSync.java | 3 +-
unixauthservice/pom.xml | 12 +-
.../authentication/PasswordValidator.java | 3 +-
35 files changed, 1385 insertions(+), 1038 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/ea3bcb38/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
----------------------------------------------------------------------
diff --cc agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
index 8a13839,030cd87..56d15ee
--- 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
@@@ -204,14 -102,12 +102,13 @@@ public class RangerDefaultPolicyEvaluat
if (LOG.isDebugEnabled()) {
LOG.debug("==> RangerDefaultPolicyEvaluator.evaluate(" + request + ", " + result + ")");
}
- RangerPolicy policy = getPolicy();
- if (policy != null && request != null && result != null) {
- boolean isMatchAttempted = false;
- boolean matchResult = false;
+ if (request != null && result != null) {
+ boolean isMatchAttempted = false;
+ boolean matchResult = false;
boolean isHeadMatchAttempted = false;
- boolean headMatchResult = false;
- final boolean isFinalPolicy = isFinal();
+ boolean headMatchResult = false;
++ final boolean isFinalPolicy = isFinal();
if (!result.getIsAuditedDetermined()) {
// Need to match request.resource first. If it matches (or head matches), then only more progress can be made
@@@ -253,13 -149,9 +150,13 @@@
}
// Go further to evaluate access only if match or head match was found at this point
if (matchResult || headMatchResult) {
- evaluatePolicyItemsForAccess(policy, request, result);
+ evaluatePolicyItemsForAccess(request, result);
}
}
+ if ((matchResult || headMatchResult) && !result.getIsAccessDetermined() && isFinalPolicy) {
+ result.setIsAllowed(false);
+ result.setPolicyId(getPolicy().getId());
+ }
}
if(LOG.isDebugEnabled()) {
@@@ -680,8 -397,23 +402,25 @@@
return ret;
}
+
+ private RangerPolicyItemAccess getAccess(RangerPolicyItem policyItem, String accessType) {
+ RangerPolicyItemAccess ret = null;
+
+ if(policyItem != null && CollectionUtils.isNotEmpty(policyItem.getAccesses())) {
+ for(RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) {
+ if(StringUtils.equalsIgnoreCase(itemAccess.getType(), accessType)) {
+ ret = itemAccess;
+
+ break;
+ }
+ }
+ }
+
+ return ret;
+ }
-}
-
-
+
+ @Override
+ public boolean isFinal() {
+ return getPolicy().isPolicyTypeFinal();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/ea3bcb38/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerOptimizedPolicyEvaluator.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/ea3bcb38/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerPolicyEvaluator.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/ea3bcb38/agents-common/src/test/java/org/apache/ranger/plugin/policyengine/TestPolicyEngine.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/ea3bcb38/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
----------------------------------------------------------------------
diff --cc security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
index 1e724c9,3d2e8b0..fd9fc3d
--- a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
@@@ -342,25 -348,15 +352,27 @@@ public class ServiceREST
SearchFilter filter = searchUtil.getSearchFilter(request, serviceDefService.sortFields);
try {
- ret = svcStore.getPaginatedServiceDefs(filter);
+ paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter);
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServiceDefs() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
+ if(paginatedSvcDefs != null) {
+ ret = new RangerServiceDefList();
+
+ ret.setServiceDefs(paginatedSvcDefs.getList());
+ ret.setPageSize(paginatedSvcDefs.getPageSize());
+ ret.setResultSize(paginatedSvcDefs.getResultSize());
+ ret.setStartIndex(paginatedSvcDefs.getStartIndex());
+ ret.setTotalCount(paginatedSvcDefs.getTotalCount());
+ ret.setSortBy(paginatedSvcDefs.getSortBy());
+ ret.setSortType(paginatedSvcDefs.getSortType());
+ }
+
if (LOG.isDebugEnabled()) {
LOG.debug("<== ServiceREST.getServiceDefs(): count=" + (ret == null ? 0 : ret.getListSize()));
}
@@@ -548,26 -552,15 +570,28 @@@
SearchFilter filter = searchUtil.getSearchFilter(request, svcService.sortFields);
try {
- ret = svcStore.getPaginatedServices(filter);
+ paginatedSvcs = svcStore.getPaginatedServices(filter);
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServices() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
+ if(paginatedSvcs != null) {
+ ret = new RangerServiceList();
+
+
+ ret.setServices(paginatedSvcs.getList());
+ ret.setPageSize(paginatedSvcs.getPageSize());
+ ret.setResultSize(paginatedSvcs.getResultSize());
+ ret.setStartIndex(paginatedSvcs.getStartIndex());
+ ret.setTotalCount(paginatedSvcs.getTotalCount());
+ ret.setSortBy(paginatedSvcs.getSortBy());
+ ret.setSortType(paginatedSvcs.getSortType());
+ }
+
if (LOG.isDebugEnabled()) {
LOG.debug("<== ServiceREST.getServices(): count=" + (ret == null ? 0 : ret.getListSize()));
}
@@@ -1080,25 -1083,15 +1116,27 @@@
SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields);
try {
- ret = svcStore.getPaginatedPolicies(filter);
+ paginatedPolicies = svcStore.getPaginatedPolicies(filter);
- applyAdminAccessFilter(ret);
+ if(paginatedPolicies != null) {
+ ret = new RangerPolicyList();
+
+ ret.setPolicies(paginatedPolicies.getList());
+ ret.setPageSize(paginatedPolicies.getPageSize());
+ ret.setResultSize(paginatedPolicies.getResultSize());
+ ret.setStartIndex(paginatedPolicies.getStartIndex());
+ ret.setTotalCount(paginatedPolicies.getTotalCount());
+ ret.setSortBy(paginatedPolicies.getSortBy());
+ ret.setSortType(paginatedPolicies.getSortType());
+
+ applyAdminAccessFilter(ret);
+ }
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getPolicies() failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (LOG.isDebugEnabled()) {
@@@ -1176,25 -1171,15 +1218,27 @@@
SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields);
try {
- ret = svcStore.getPaginatedServicePolicies(serviceId, filter);
+ paginatedPolicies = svcStore.getPaginatedServicePolicies(serviceId, filter);
- applyAdminAccessFilter(ret);
+ if(paginatedPolicies != null) {
+ ret = new RangerPolicyList();
+
+ ret.setPolicies(paginatedPolicies.getList());
+ ret.setPageSize(paginatedPolicies.getPageSize());
+ ret.setResultSize(paginatedPolicies.getResultSize());
+ ret.setStartIndex(paginatedPolicies.getStartIndex());
+ ret.setTotalCount(paginatedPolicies.getTotalCount());
+ ret.setSortBy(paginatedPolicies.getSortBy());
+ ret.setSortType(paginatedPolicies.getSortType());
+
+ applyAdminAccessFilter(ret);
+ }
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServicePolicies(" + serviceId + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (ret == null) {
@@@ -1224,25 -1207,15 +1268,27 @@@
SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields);
try {
- ret = svcStore.getPaginatedServicePolicies(serviceName, filter);
+ paginatedPolicies = svcStore.getPaginatedServicePolicies(serviceName, filter);
- applyAdminAccessFilter(ret);
+ if(paginatedPolicies != null) {
+ ret = new RangerPolicyList();
+
+ ret.setPolicies(paginatedPolicies.getList());
+ ret.setPageSize(paginatedPolicies.getPageSize());
+ ret.setResultSize(paginatedPolicies.getResultSize());
+ ret.setStartIndex(paginatedPolicies.getStartIndex());
+ ret.setTotalCount(paginatedPolicies.getTotalCount());
+ ret.setSortBy(paginatedPolicies.getSortBy());
+ ret.setSortType(paginatedPolicies.getSortType());
+
+ applyAdminAccessFilter(ret);
+ }
- } catch (Exception excp) {
+ } catch(WebApplicationException excp) {
+ throw excp;
+ } catch (Throwable excp) {
LOG.error("getServicePolicies(" + serviceName + ") failed", excp);
- throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true);
+ throw restErrorUtil.createRESTException(excp.getMessage());
}
if (ret == null) {
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/ea3bcb38/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
----------------------------------------------------------------------
diff --cc security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
index da1da83,f073036..058a407
--- a/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
+++ b/security-admin/src/main/webapp/scripts/views/service/ServiceForm.js
@@@ -149,20 -150,20 +149,22 @@@ define(function(require)
var that = this;
//Set configs for service
var config = {};
+ if(!_.isEmpty(this.rangerServiceDefModel.get('configs'))){
- _.each(this.rangerServiceDefModel.get('configs'),function(obj){
- if(!_.isNull(obj)){
- if(obj.type == 'bool'){
- config[obj.name] = that.getBooleanForConfig(obj, that.model);
- }else{
- config[obj.name] = that.model.get(obj.name).toString();
- }
+ _.each(this.rangerServiceDefModel.get('configs'),function(obj){
+ if(!_.isNull(obj)){
+ if(obj.type == 'bool'){
+ config[obj.name] = that.getBooleanForConfig(obj, that.model);
+ }else{
+ config[obj.name] = _.isNull(that.model.get(obj.name)) ? "" : that.model.get(obj.name).toString();
+ }
+ if(!_.isNull(obj.name)) {
that.model.unset(obj.name);
}
- });
- this.extraConfigColl.each(function(obj){ config[obj.get('name')] = obj.get('value');})
- this.model.set('configs',config);
+ }
+ });
+ this.extraConfigColl.each(function(obj){ config[obj.get('name')] = obj.get('value');})
+ this.model.set('configs',config);
+ }
//Set service type
this.model.set('type',this.rangerServiceDefModel.get('name'))
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/ea3bcb38/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
----------------------------------------------------------------------
[2/9] incubator-ranger git commit: RANGER-539: fixes to support
rolling upgrade/downgrade of ranger components
Posted by ma...@apache.org.
RANGER-539: fixes to support rolling upgrade/downgrade of ranger components
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/2c54590a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/2c54590a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/2c54590a
Branch: refs/heads/tag-policy
Commit: 2c54590a83ab4cf37924876ae468699746d2a751
Parents: 065b431
Author: sneethiraj <sn...@apache.org>
Authored: Mon Jun 8 23:04:40 2015 -0700
Committer: sneethiraj <sn...@apache.org>
Committed: Mon Jun 8 23:26:27 2015 -0700
----------------------------------------------------------------------
.../conf.dist/ranger-admin-default-site.xml | 2 +-
.../config/UserGroupSyncConfig.java | 37 ++++++++++++++------
.../ranger/usergroupsync/UserGroupSync.java | 3 +-
unixauthservice/pom.xml | 12 ++++++-
.../authentication/PasswordValidator.java | 3 +-
5 files changed, 42 insertions(+), 15 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/2c54590a/security-admin/src/main/resources/conf.dist/ranger-admin-default-site.xml
----------------------------------------------------------------------
diff --git a/security-admin/src/main/resources/conf.dist/ranger-admin-default-site.xml b/security-admin/src/main/resources/conf.dist/ranger-admin-default-site.xml
index 580341b..bd21365 100644
--- a/security-admin/src/main/resources/conf.dist/ranger-admin-default-site.xml
+++ b/security-admin/src/main/resources/conf.dist/ranger-admin-default-site.xml
@@ -438,7 +438,7 @@
</property>
<property>
<name>ranger.sha256Password.update.disable</name>
- <value>false</value>
+ <value>true</value>
<description></description>
</property>
</configuration>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/2c54590a/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
----------------------------------------------------------------------
diff --git a/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java b/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
index d9efe1a..f8b68f2 100644
--- a/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
+++ b/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
@@ -40,9 +40,14 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
+import org.apache.log4j.Logger;
+
+
+
public class UserGroupSyncConfig {
public static final String CONFIG_FILE = "ranger-ugsync-site.xml" ;
+ private static final Logger LOG = Logger.getLogger(UserGroupSyncConfig.class) ;
public static final String DEFAULT_CONFIG_FILE = "ranger-ugsync-default-site.xml" ;
@@ -70,6 +75,8 @@ public class UserGroupSyncConfig {
private static final String UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_PARAM = "ranger.usersync.sleeptimeinmillisbetweensynccycle" ;
+ private static final long UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_MIN_VALUE = 30000L ;
+
private static final long UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_UNIX_DEFAULT_VALUE = 300000L ;
private static final long UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_LDAP_DEFAULT_VALUE = 21600000L ;
@@ -356,27 +363,37 @@ public class UserGroupSyncConfig {
}
else {
long ret = Long.parseLong(val) ;
+ if (ret < UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_MIN_VALUE) {
+ LOG.info("Sleep Time Between Cycle can not be lower than [" + UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_MIN_VALUE + "] millisec. resetting to min value.") ;
+ ret = UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_MIN_VALUE ;
+ }
return ret;
}
-
}
public UserGroupSource getUserGroupSource() throws Throwable {
+
String val = prop.getProperty(UGSYNC_SOURCE_CLASS_PARAM) ;
+ String syncSource = null ;
+
if(val == null || val.trim().isEmpty()) {
- String syncSource=getSyncSource();
- if(syncSource!=null && syncSource.equalsIgnoreCase("UNIX")){
- val = UGSYNC_SOURCE_CLASS;
- }else if(syncSource!=null && syncSource.equalsIgnoreCase("LDAP")){
- val = LGSYNC_SOURCE_CLASS;
- }else{
- val = UGSYNC_SOURCE_CLASS;
- }
+ syncSource=getSyncSource();
+ }
+ else {
+ syncSource = val ;
+ }
+
+ String className = val ;
+
+ if(syncSource!=null && syncSource.equalsIgnoreCase("UNIX")){
+ className = UGSYNC_SOURCE_CLASS;
+ }else if(syncSource!=null && syncSource.equalsIgnoreCase("LDAP")){
+ className = LGSYNC_SOURCE_CLASS;
}
- Class<UserGroupSource> ugSourceClass = (Class<UserGroupSource>)Class.forName(val);
+ Class<UserGroupSource> ugSourceClass = (Class<UserGroupSource>)Class.forName(className);
UserGroupSource ret = ugSourceClass.newInstance();
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/2c54590a/ugsync/src/main/java/org/apache/ranger/usergroupsync/UserGroupSync.java
----------------------------------------------------------------------
diff --git a/ugsync/src/main/java/org/apache/ranger/usergroupsync/UserGroupSync.java b/ugsync/src/main/java/org/apache/ranger/usergroupsync/UserGroupSync.java
index f5b213e..9d20aaa 100644
--- a/ugsync/src/main/java/org/apache/ranger/usergroupsync/UserGroupSync.java
+++ b/ugsync/src/main/java/org/apache/ranger/usergroupsync/UserGroupSync.java
@@ -64,8 +64,8 @@ public class UserGroupSync implements Runnable {
}
catch(Throwable t) {
LOG.error("Failed to initialize UserGroup source/sink. Will retry after " + sleepTimeBetweenCycleInMillis + " milliseconds. Error details: ", t) ;
-
try {
+ LOG.debug("Sleeping for [" + sleepTimeBetweenCycleInMillis + "] milliSeconds") ;
Thread.sleep(sleepTimeBetweenCycleInMillis) ;
} catch (Exception e) {
LOG.error("Failed to wait for [" + sleepTimeBetweenCycleInMillis + "] milliseconds before attempting to initialize UserGroup source/sink", e) ;
@@ -77,6 +77,7 @@ public class UserGroupSync implements Runnable {
while (! shutdownFlag ) {
try {
+ LOG.debug("Sleeping for [" + sleepTimeBetweenCycleInMillis + "] milliSeconds") ;
Thread.sleep(sleepTimeBetweenCycleInMillis);
} catch (InterruptedException e) {
LOG.error("Failed to wait for [" + sleepTimeBetweenCycleInMillis + "] milliseconds before attempting to synchronize UserGroup information", e) ;
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/2c54590a/unixauthservice/pom.xml
----------------------------------------------------------------------
diff --git a/unixauthservice/pom.xml b/unixauthservice/pom.xml
index 89c0a81..4d44e6f 100644
--- a/unixauthservice/pom.xml
+++ b/unixauthservice/pom.xml
@@ -97,7 +97,17 @@
</dependency>
</dependencies>
-
+ <build>
+ <resources>
+ <resource>
+ <targetPath>${project.build.outputDirectory}/</targetPath>
+ <directory>conf.dist</directory>
+ <includes>
+ <include>log4j.xml</include>
+ </includes>
+ </resource>
+ </resources>
+ </build>
</project>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/2c54590a/unixauthservice/src/main/java/org/apache/ranger/authentication/PasswordValidator.java
----------------------------------------------------------------------
diff --git a/unixauthservice/src/main/java/org/apache/ranger/authentication/PasswordValidator.java b/unixauthservice/src/main/java/org/apache/ranger/authentication/PasswordValidator.java
index 19d38eb..b8cfbcc 100644
--- a/unixauthservice/src/main/java/org/apache/ranger/authentication/PasswordValidator.java
+++ b/unixauthservice/src/main/java/org/apache/ranger/authentication/PasswordValidator.java
@@ -111,11 +111,10 @@ public class PasswordValidator implements Runnable {
}
catch(Throwable t) {
- if (writer != null){
+ if (userName != null && writer != null ) {
String res = "FAILED: unable to validate due to error " + t ;
writer.println(res) ;
LOG.error("Response [" + res + "] for user: " + userName, t);
-
}
}
finally {